var vr = Object.defineProperty
  , yr = Object.defineProperties;
var Tr = Object.getOwnPropertyDescriptors;
var or = Object.getOwnPropertySymbols;
var _r = Object.prototype.hasOwnProperty
  , mr = Object.prototype.propertyIsEnumerable;
var sr = (a,e,i)=>e in a ? vr(a, e, {
    enumerable: !0,
    configurable: !0,
    writable: !0,
    value: i
}) : a[e] = i
  , $t = (a,e)=>{
    for (var i in e || (e = {}))
        _r.call(e, i) && sr(a, i, e[i]);
    if (or)
        for (var i of or(e))
            mr.call(e, i) && sr(a, i, e[i]);
    return a
}
  , Zt = (a,e)=>yr(a, Tr(e));
var gr = (a,e)=>{
    var i = {};
    for (var o in a)
        _r.call(a, o) && e.indexOf(o) < 0 && (i[o] = a[o]);
    if (a != null && or)
        for (var o of or(a))
            e.indexOf(o) < 0 && mr.call(a, o) && (i[o] = a[o]);
    return i
}
;
var Tt = (a,e,i)=>(sr(a, typeof e != "symbol" ? e + "" : e, i),
i);
function _mergeNamespaces(a, e) {
    return e.forEach(function(i) {
        i && typeof i != "string" && !Array.isArray(i) && Object.keys(i).forEach(function(o) {
            if (o !== "default" && !(o in a)) {
                var s = Object.getOwnPropertyDescriptor(i, o);
                Object.defineProperty(a, o, s.get ? s : {
                    enumerable: !0,
                    get: function() {
                        return i[o]
                    }
                })
            }
        })
    }),
    Object.freeze(Object.defineProperty(a, Symbol.toStringTag, {
        value: "Module"
    }))
}
const p$2 = function() {
    const e = document.createElement("link").relList;
    if (e && e.supports && e.supports("modulepreload"))
        return;
    for (const s of document.querySelectorAll('link[rel="modulepreload"]'))
        o(s);
    new MutationObserver(s=>{
        for (const c of s)
            if (c.type === "childList")
                for (const d of c.addedNodes)
                    d.tagName === "LINK" && d.rel === "modulepreload" && o(d)
    }
    ).observe(document, {
        childList: !0,
        subtree: !0
    });
    function i(s) {
        const c = {};
        return s.integrity && (c.integrity = s.integrity),
        s.referrerpolicy && (c.referrerPolicy = s.referrerpolicy),
        s.crossorigin === "use-credentials" ? c.credentials = "include" : s.crossorigin === "anonymous" ? c.credentials = "omit" : c.credentials = "same-origin",
        c
    }
    function o(s) {
        if (s.ep)
            return;
        s.ep = !0;
        const c = i(s);
        fetch(s.href, c)
    }
};
p$2();
var commonjsGlobal = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : typeof global != "undefined" ? global : typeof self != "undefined" ? self : {};
function commonjsRequire(a) {
    throw new Error('Could not dynamically require "' + a + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')
}
var react = {
    exports: {}
}
  , react_production_min = {};
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var getOwnPropertySymbols = Object.getOwnPropertySymbols
  , hasOwnProperty = Object.prototype.hasOwnProperty
  , propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(a) {
    if (a == null)
        throw new TypeError("Object.assign cannot be called with null or undefined");
    return Object(a)
}
function shouldUseNative() {
    try {
        if (!Object.assign)
            return !1;
        var a = new String("abc");
        if (a[5] = "de",
        Object.getOwnPropertyNames(a)[0] === "5")
            return !1;
        for (var e = {}, i = 0; i < 10; i++)
            e["_" + String.fromCharCode(i)] = i;
        var o = Object.getOwnPropertyNames(e).map(function(c) {
            return e[c]
        });
        if (o.join("") !== "0123456789")
            return !1;
        var s = {};
        return "abcdefghijklmnopqrst".split("").forEach(function(c) {
            s[c] = c
        }),
        Object.keys(Object.assign({}, s)).join("") === "abcdefghijklmnopqrst"
    } catch {
        return !1
    }
}
var objectAssign = shouldUseNative() ? Object.assign : function(a, e) {
    for (var i, o = toObject(a), s, c = 1; c < arguments.length; c++) {
        i = Object(arguments[c]);
        for (var d in i)
            hasOwnProperty.call(i, d) && (o[d] = i[d]);
        if (getOwnPropertySymbols) {
            s = getOwnPropertySymbols(i);
            for (var _ = 0; _ < s.length; _++)
                propIsEnumerable.call(i, s[_]) && (o[s[_]] = i[s[_]])
        }
    }
    return o
}
;
/** @license React v17.0.2
 * react.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var l = objectAssign
  , n$1 = 60103
  , p$1 = 60106;
react_production_min.Fragment = 60107;
react_production_min.StrictMode = 60108;
react_production_min.Profiler = 60114;
var q$1 = 60109
  , r$1 = 60110
  , t = 60112;
react_production_min.Suspense = 60113;
var u = 60115
  , v = 60116;
if (typeof Symbol == "function" && Symbol.for) {
    var w = Symbol.for;
    n$1 = w("react.element"),
    p$1 = w("react.portal"),
    react_production_min.Fragment = w("react.fragment"),
    react_production_min.StrictMode = w("react.strict_mode"),
    react_production_min.Profiler = w("react.profiler"),
    q$1 = w("react.provider"),
    r$1 = w("react.context"),
    t = w("react.forward_ref"),
    react_production_min.Suspense = w("react.suspense"),
    u = w("react.memo"),
    v = w("react.lazy")
}
var x = typeof Symbol == "function" && Symbol.iterator;
function y$1(a) {
    return a === null || typeof a != "object" ? null : (a = x && a[x] || a["@@iterator"],
    typeof a == "function" ? a : null)
}
function z(a) {
    for (var e = "https://reactjs.org/docs/error-decoder.html?invariant=" + a, i = 1; i < arguments.length; i++)
        e += "&args[]=" + encodeURIComponent(arguments[i]);
    return "Minified React error #" + a + "; visit " + e + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."
}
var A = {
    isMounted: function() {
        return !1
    },
    enqueueForceUpdate: function() {},
    enqueueReplaceState: function() {},
    enqueueSetState: function() {}
}
  , B$1 = {};
function C(a, e, i) {
    this.props = a,
    this.context = e,
    this.refs = B$1,
    this.updater = i || A
}
C.prototype.isReactComponent = {};
C.prototype.setState = function(a, e) {
    if (typeof a != "object" && typeof a != "function" && a != null)
        throw Error(z(85));
    this.updater.enqueueSetState(this, a, e, "setState")
}
;
C.prototype.forceUpdate = function(a) {
    this.updater.enqueueForceUpdate(this, a, "forceUpdate")
}
;
function D$1() {}
D$1.prototype = C.prototype;
function E$1(a, e, i) {
    this.props = a,
    this.context = e,
    this.refs = B$1,
    this.updater = i || A
}
var F$1 = E$1.prototype = new D$1;
F$1.constructor = E$1;
l(F$1, C.prototype);
F$1.isPureReactComponent = !0;
var G$1 = {
    current: null
}
  , H$1 = Object.prototype.hasOwnProperty
  , I$1 = {
    key: !0,
    ref: !0,
    __self: !0,
    __source: !0
};
function J(a, e, i) {
    var o, s = {}, c = null, d = null;
    if (e != null)
        for (o in e.ref !== void 0 && (d = e.ref),
        e.key !== void 0 && (c = "" + e.key),
        e)
            H$1.call(e, o) && !I$1.hasOwnProperty(o) && (s[o] = e[o]);
    var _ = arguments.length - 2;
    if (_ === 1)
        s.children = i;
    else if (1 < _) {
        for (var b = Array(_), k = 0; k < _; k++)
            b[k] = arguments[k + 2];
        s.children = b
    }
    if (a && a.defaultProps)
        for (o in _ = a.defaultProps,
        _)
            s[o] === void 0 && (s[o] = _[o]);
    return {
        $$typeof: n$1,
        type: a,
        key: c,
        ref: d,
        props: s,
        _owner: G$1.current
    }
}
function K(a, e) {
    return {
        $$typeof: n$1,
        type: a.type,
        key: e,
        ref: a.ref,
        props: a.props,
        _owner: a._owner
    }
}
function L(a) {
    return typeof a == "object" && a !== null && a.$$typeof === n$1
}
function escape$1(a) {
    var e = {
        "=": "=0",
        ":": "=2"
    };
    return "$" + a.replace(/[=:]/g, function(i) {
        return e[i]
    })
}
var M$1 = /\/+/g;
function N$1(a, e) {
    return typeof a == "object" && a !== null && a.key != null ? escape$1("" + a.key) : e.toString(36)
}
function O$1(a, e, i, o, s) {
    var c = typeof a;
    (c === "undefined" || c === "boolean") && (a = null);
    var d = !1;
    if (a === null)
        d = !0;
    else
        switch (c) {
        case "string":
        case "number":
            d = !0;
            break;
        case "object":
            switch (a.$$typeof) {
            case n$1:
            case p$1:
                d = !0
            }
        }
    if (d)
        return d = a,
        s = s(d),
        a = o === "" ? "." + N$1(d, 0) : o,
        Array.isArray(s) ? (i = "",
        a != null && (i = a.replace(M$1, "$&/") + "/"),
        O$1(s, e, i, "", function(k) {
            return k
        })) : s != null && (L(s) && (s = K(s, i + (!s.key || d && d.key === s.key ? "" : ("" + s.key).replace(M$1, "$&/") + "/") + a)),
        e.push(s)),
        1;
    if (d = 0,
    o = o === "" ? "." : o + ":",
    Array.isArray(a))
        for (var _ = 0; _ < a.length; _++) {
            c = a[_];
            var b = o + N$1(c, _);
            d += O$1(c, e, i, b, s)
        }
    else if (b = y$1(a),
    typeof b == "function")
        for (a = b.call(a),
        _ = 0; !(c = a.next()).done; )
            c = c.value,
            b = o + N$1(c, _++),
            d += O$1(c, e, i, b, s);
    else if (c === "object")
        throw e = "" + a,
        Error(z(31, e === "[object Object]" ? "object with keys {" + Object.keys(a).join(", ") + "}" : e));
    return d
}
function P$1(a, e, i) {
    if (a == null)
        return a;
    var o = []
      , s = 0;
    return O$1(a, o, "", "", function(c) {
        return e.call(i, c, s++)
    }),
    o
}
function Q(a) {
    if (a._status === -1) {
        var e = a._result;
        e = e(),
        a._status = 0,
        a._result = e,
        e.then(function(i) {
            a._status === 0 && (i = i.default,
            a._status = 1,
            a._result = i)
        }, function(i) {
            a._status === 0 && (a._status = 2,
            a._result = i)
        })
    }
    if (a._status === 1)
        return a._result;
    throw a._result
}
var R$1 = {
    current: null
};
function S$1() {
    var a = R$1.current;
    if (a === null)
        throw Error(z(321));
    return a
}
var T$1 = {
    ReactCurrentDispatcher: R$1,
    ReactCurrentBatchConfig: {
        transition: 0
    },
    ReactCurrentOwner: G$1,
    IsSomeRendererActing: {
        current: !1
    },
    assign: l
};
react_production_min.Children = {
    map: P$1,
    forEach: function(a, e, i) {
        P$1(a, function() {
            e.apply(this, arguments)
        }, i)
    },
    count: function(a) {
        var e = 0;
        return P$1(a, function() {
            e++
        }),
        e
    },
    toArray: function(a) {
        return P$1(a, function(e) {
            return e
        }) || []
    },
    only: function(a) {
        if (!L(a))
            throw Error(z(143));
        return a
    }
};
react_production_min.Component = C;
react_production_min.PureComponent = E$1;
react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = T$1;
react_production_min.cloneElement = function(a, e, i) {
    if (a == null)
        throw Error(z(267, a));
    var o = l({}, a.props)
      , s = a.key
      , c = a.ref
      , d = a._owner;
    if (e != null) {
        if (e.ref !== void 0 && (c = e.ref,
        d = G$1.current),
        e.key !== void 0 && (s = "" + e.key),
        a.type && a.type.defaultProps)
            var _ = a.type.defaultProps;
        for (b in e)
            H$1.call(e, b) && !I$1.hasOwnProperty(b) && (o[b] = e[b] === void 0 && _ !== void 0 ? _[b] : e[b])
    }
    var b = arguments.length - 2;
    if (b === 1)
        o.children = i;
    else if (1 < b) {
        _ = Array(b);
        for (var k = 0; k < b; k++)
            _[k] = arguments[k + 2];
        o.children = _
    }
    return {
        $$typeof: n$1,
        type: a.type,
        key: s,
        ref: c,
        props: o,
        _owner: d
    }
}
;
react_production_min.createContext = function(a, e) {
    return e === void 0 && (e = null),
    a = {
        $$typeof: r$1,
        _calculateChangedBits: e,
        _currentValue: a,
        _currentValue2: a,
        _threadCount: 0,
        Provider: null,
        Consumer: null
    },
    a.Provider = {
        $$typeof: q$1,
        _context: a
    },
    a.Consumer = a
}
;
react_production_min.createElement = J;
react_production_min.createFactory = function(a) {
    var e = J.bind(null, a);
    return e.type = a,
    e
}
;
react_production_min.createRef = function() {
    return {
        current: null
    }
}
;
react_production_min.forwardRef = function(a) {
    return {
        $$typeof: t,
        render: a
    }
}
;
react_production_min.isValidElement = L;
react_production_min.lazy = function(a) {
    return {
        $$typeof: v,
        _payload: {
            _status: -1,
            _result: a
        },
        _init: Q
    }
}
;
react_production_min.memo = function(a, e) {
    return {
        $$typeof: u,
        type: a,
        compare: e === void 0 ? null : e
    }
}
;
react_production_min.useCallback = function(a, e) {
    return S$1().useCallback(a, e)
}
;
react_production_min.useContext = function(a, e) {
    return S$1().useContext(a, e)
}
;
react_production_min.useDebugValue = function() {}
;
react_production_min.useEffect = function(a, e) {
    return S$1().useEffect(a, e)
}
;
react_production_min.useImperativeHandle = function(a, e, i) {
    return S$1().useImperativeHandle(a, e, i)
}
;
react_production_min.useLayoutEffect = function(a, e) {
    return S$1().useLayoutEffect(a, e)
}
;
react_production_min.useMemo = function(a, e) {
    return S$1().useMemo(a, e)
}
;
react_production_min.useReducer = function(a, e, i) {
    return S$1().useReducer(a, e, i)
}
;
react_production_min.useRef = function(a) {
    return S$1().useRef(a)
}
;
react_production_min.useState = function(a) {
    return S$1().useState(a)
}
;
react_production_min.version = "17.0.2";
react.exports = react_production_min;
var React = react.exports
  , reactDom = {
    exports: {}
}
  , reactDom_production_min = {}
  , scheduler = {
    exports: {}
}
  , scheduler_production_min = {};
/** @license React v0.20.2
 * scheduler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
(function(a) {
    var e, i, o, s;
    if (typeof performance == "object" && typeof performance.now == "function") {
        var c = performance;
        a.unstable_now = function() {
            return c.now()
        }
    } else {
        var d = Date
          , _ = d.now();
        a.unstable_now = function() {
            return d.now() - _
        }
    }
    if (typeof window == "undefined" || typeof MessageChannel != "function") {
        var b = null
          , k = null
          , j = function() {
            if (b !== null)
                try {
                    var bt = a.unstable_now();
                    b(!0, bt),
                    b = null
                } catch (Rt) {
                    throw setTimeout(j, 0),
                    Rt
                }
        };
        e = function(bt) {
            b !== null ? setTimeout(e, 0, bt) : (b = bt,
            setTimeout(j, 0))
        }
        ,
        i = function(bt, Rt) {
            k = setTimeout(bt, Rt)
        }
        ,
        o = function() {
            clearTimeout(k)
        }
        ,
        a.unstable_shouldYield = function() {
            return !1
        }
        ,
        s = a.unstable_forceFrameRate = function() {}
    } else {
        var $ = window.setTimeout
          , _e = window.clearTimeout;
        if (typeof console != "undefined") {
            var et = window.cancelAnimationFrame;
            typeof window.requestAnimationFrame != "function" && console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"),
            typeof et != "function" && console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills")
        }
        var tt = !1
          , rt = null
          , it = -1
          , nt = 5
          , ot = 0;
        a.unstable_shouldYield = function() {
            return a.unstable_now() >= ot
        }
        ,
        s = function() {}
        ,
        a.unstable_forceFrameRate = function(bt) {
            0 > bt || 125 < bt ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : nt = 0 < bt ? Math.floor(1e3 / bt) : 5
        }
        ;
        var at = new MessageChannel
          , st = at.port2;
        at.port1.onmessage = function() {
            if (rt !== null) {
                var bt = a.unstable_now();
                ot = bt + nt;
                try {
                    rt(!0, bt) ? st.postMessage(null) : (tt = !1,
                    rt = null)
                } catch (Rt) {
                    throw st.postMessage(null),
                    Rt
                }
            } else
                tt = !1
        }
        ,
        e = function(bt) {
            rt = bt,
            tt || (tt = !0,
            st.postMessage(null))
        }
        ,
        i = function(bt, Rt) {
            it = $(function() {
                bt(a.unstable_now())
            }, Rt)
        }
        ,
        o = function() {
            _e(it),
            it = -1
        }
    }
    function ut(bt, Rt) {
        var Mt = bt.length;
        bt.push(Rt);
        e: for (; ; ) {
            var Pt = Mt - 1 >>> 1
              , It = bt[Pt];
            if (It !== void 0 && 0 < ft(It, Rt))
                bt[Pt] = Rt,
                bt[Mt] = It,
                Mt = Pt;
            else
                break e
        }
    }
    function ct(bt) {
        return bt = bt[0],
        bt === void 0 ? null : bt
    }
    function lt(bt) {
        var Rt = bt[0];
        if (Rt !== void 0) {
            var Mt = bt.pop();
            if (Mt !== Rt) {
                bt[0] = Mt;
                e: for (var Pt = 0, It = bt.length; Pt < It; ) {
                    var Dt = 2 * (Pt + 1) - 1
                      , Ct = bt[Dt]
                      , Ot = Dt + 1
                      , wt = bt[Ot];
                    if (Ct !== void 0 && 0 > ft(Ct, Mt))
                        wt !== void 0 && 0 > ft(wt, Ct) ? (bt[Pt] = wt,
                        bt[Ot] = Mt,
                        Pt = Ot) : (bt[Pt] = Ct,
                        bt[Dt] = Mt,
                        Pt = Dt);
                    else if (wt !== void 0 && 0 > ft(wt, Mt))
                        bt[Pt] = wt,
                        bt[Ot] = Mt,
                        Pt = Ot;
                    else
                        break e
                }
            }
            return Rt
        }
        return null
    }
    function ft(bt, Rt) {
        var Mt = bt.sortIndex - Rt.sortIndex;
        return Mt !== 0 ? Mt : bt.id - Rt.id
    }
    var ht = []
      , pt = []
      , dt = 1
      , _t = null
      , mt = 3
      , vt = !1
      , yt = !1
      , Et = !1;
    function At(bt) {
        for (var Rt = ct(pt); Rt !== null; ) {
            if (Rt.callback === null)
                lt(pt);
            else if (Rt.startTime <= bt)
                lt(pt),
                Rt.sortIndex = Rt.expirationTime,
                ut(ht, Rt);
            else
                break;
            Rt = ct(pt)
        }
    }
    function gt(bt) {
        if (Et = !1,
        At(bt),
        !yt)
            if (ct(ht) !== null)
                yt = !0,
                e(St);
            else {
                var Rt = ct(pt);
                Rt !== null && i(gt, Rt.startTime - bt)
            }
    }
    function St(bt, Rt) {
        yt = !1,
        Et && (Et = !1,
        o()),
        vt = !0;
        var Mt = mt;
        try {
            for (At(Rt),
            _t = ct(ht); _t !== null && (!(_t.expirationTime > Rt) || bt && !a.unstable_shouldYield()); ) {
                var Pt = _t.callback;
                if (typeof Pt == "function") {
                    _t.callback = null,
                    mt = _t.priorityLevel;
                    var It = Pt(_t.expirationTime <= Rt);
                    Rt = a.unstable_now(),
                    typeof It == "function" ? _t.callback = It : _t === ct(ht) && lt(ht),
                    At(Rt)
                } else
                    lt(ht);
                _t = ct(ht)
            }
            if (_t !== null)
                var Dt = !0;
            else {
                var Ct = ct(pt);
                Ct !== null && i(gt, Ct.startTime - Rt),
                Dt = !1
            }
            return Dt
        } finally {
            _t = null,
            mt = Mt,
            vt = !1
        }
    }
    var xt = s;
    a.unstable_IdlePriority = 5,
    a.unstable_ImmediatePriority = 1,
    a.unstable_LowPriority = 4,
    a.unstable_NormalPriority = 3,
    a.unstable_Profiling = null,
    a.unstable_UserBlockingPriority = 2,
    a.unstable_cancelCallback = function(bt) {
        bt.callback = null
    }
    ,
    a.unstable_continueExecution = function() {
        yt || vt || (yt = !0,
        e(St))
    }
    ,
    a.unstable_getCurrentPriorityLevel = function() {
        return mt
    }
    ,
    a.unstable_getFirstCallbackNode = function() {
        return ct(ht)
    }
    ,
    a.unstable_next = function(bt) {
        switch (mt) {
        case 1:
        case 2:
        case 3:
            var Rt = 3;
            break;
        default:
            Rt = mt
        }
        var Mt = mt;
        mt = Rt;
        try {
            return bt()
        } finally {
            mt = Mt
        }
    }
    ,
    a.unstable_pauseExecution = function() {}
    ,
    a.unstable_requestPaint = xt,
    a.unstable_runWithPriority = function(bt, Rt) {
        switch (bt) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            break;
        default:
            bt = 3
        }
        var Mt = mt;
        mt = bt;
        try {
            return Rt()
        } finally {
            mt = Mt
        }
    }
    ,
    a.unstable_scheduleCallback = function(bt, Rt, Mt) {
        var Pt = a.unstable_now();
        switch (typeof Mt == "object" && Mt !== null ? (Mt = Mt.delay,
        Mt = typeof Mt == "number" && 0 < Mt ? Pt + Mt : Pt) : Mt = Pt,
        bt) {
        case 1:
            var It = -1;
            break;
        case 2:
            It = 250;
            break;
        case 5:
            It = 1073741823;
            break;
        case 4:
            It = 1e4;
            break;
        default:
            It = 5e3
        }
        return It = Mt + It,
        bt = {
            id: dt++,
            callback: Rt,
            priorityLevel: bt,
            startTime: Mt,
            expirationTime: It,
            sortIndex: -1
        },
        Mt > Pt ? (bt.sortIndex = Mt,
        ut(pt, bt),
        ct(ht) === null && bt === ct(pt) && (Et ? o() : Et = !0,
        i(gt, Mt - Pt))) : (bt.sortIndex = It,
        ut(ht, bt),
        yt || vt || (yt = !0,
        e(St))),
        bt
    }
    ,
    a.unstable_wrapCallback = function(bt) {
        var Rt = mt;
        return function() {
            var Mt = mt;
            mt = Rt;
            try {
                return bt.apply(this, arguments)
            } finally {
                mt = Mt
            }
        }
    }
}
)(scheduler_production_min);
scheduler.exports = scheduler_production_min;
/** @license React v17.0.2
 * react-dom.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var aa = react.exports
  , m$1 = objectAssign
  , r = scheduler.exports;
function y(a) {
    for (var e = "https://reactjs.org/docs/error-decoder.html?invariant=" + a, i = 1; i < arguments.length; i++)
        e += "&args[]=" + encodeURIComponent(arguments[i]);
    return "Minified React error #" + a + "; visit " + e + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."
}
if (!aa)
    throw Error(y(227));
var ba = new Set
  , ca = {};
function da(a, e) {
    ea(a, e),
    ea(a + "Capture", e)
}
function ea(a, e) {
    for (ca[a] = e,
    a = 0; a < e.length; a++)
        ba.add(e[a])
}
var fa = !(typeof window == "undefined" || typeof window.document == "undefined" || typeof window.document.createElement == "undefined")
  , ha = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/
  , ia = Object.prototype.hasOwnProperty
  , ja = {}
  , ka = {};
function la(a) {
    return ia.call(ka, a) ? !0 : ia.call(ja, a) ? !1 : ha.test(a) ? ka[a] = !0 : (ja[a] = !0,
    !1)
}
function ma(a, e, i, o) {
    if (i !== null && i.type === 0)
        return !1;
    switch (typeof e) {
    case "function":
    case "symbol":
        return !0;
    case "boolean":
        return o ? !1 : i !== null ? !i.acceptsBooleans : (a = a.toLowerCase().slice(0, 5),
        a !== "data-" && a !== "aria-");
    default:
        return !1
    }
}
function na(a, e, i, o) {
    if (e === null || typeof e == "undefined" || ma(a, e, i, o))
        return !0;
    if (o)
        return !1;
    if (i !== null)
        switch (i.type) {
        case 3:
            return !e;
        case 4:
            return e === !1;
        case 5:
            return isNaN(e);
        case 6:
            return isNaN(e) || 1 > e
        }
    return !1
}
function B(a, e, i, o, s, c, d) {
    this.acceptsBooleans = e === 2 || e === 3 || e === 4,
    this.attributeName = o,
    this.attributeNamespace = s,
    this.mustUseProperty = i,
    this.propertyName = a,
    this.type = e,
    this.sanitizeURL = c,
    this.removeEmptyString = d
}
var D = {};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a) {
    D[a] = new B(a,0,!1,a,null,!1,!1)
});
[["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a) {
    var e = a[0];
    D[e] = new B(e,1,!1,a[1],null,!1,!1)
});
["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a) {
    D[a] = new B(a,2,!1,a.toLowerCase(),null,!1,!1)
});
["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a) {
    D[a] = new B(a,2,!1,a,null,!1,!1)
});
"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a) {
    D[a] = new B(a,3,!1,a.toLowerCase(),null,!1,!1)
});
["checked", "multiple", "muted", "selected"].forEach(function(a) {
    D[a] = new B(a,3,!0,a,null,!1,!1)
});
["capture", "download"].forEach(function(a) {
    D[a] = new B(a,4,!1,a,null,!1,!1)
});
["cols", "rows", "size", "span"].forEach(function(a) {
    D[a] = new B(a,6,!1,a,null,!1,!1)
});
["rowSpan", "start"].forEach(function(a) {
    D[a] = new B(a,5,!1,a.toLowerCase(),null,!1,!1)
});
var oa = /[\-:]([a-z])/g;
function pa(a) {
    return a[1].toUpperCase()
}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a) {
    var e = a.replace(oa, pa);
    D[e] = new B(e,1,!1,a,null,!1,!1)
});
"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a) {
    var e = a.replace(oa, pa);
    D[e] = new B(e,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)
});
["xml:base", "xml:lang", "xml:space"].forEach(function(a) {
    var e = a.replace(oa, pa);
    D[e] = new B(e,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)
});
["tabIndex", "crossOrigin"].forEach(function(a) {
    D[a] = new B(a,1,!1,a.toLowerCase(),null,!1,!1)
});
D.xlinkHref = new B("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);
["src", "href", "action", "formAction"].forEach(function(a) {
    D[a] = new B(a,1,!1,a.toLowerCase(),null,!0,!0)
});
function qa(a, e, i, o) {
    var s = D.hasOwnProperty(e) ? D[e] : null
      , c = s !== null ? s.type === 0 : o ? !1 : !(!(2 < e.length) || e[0] !== "o" && e[0] !== "O" || e[1] !== "n" && e[1] !== "N");
    c || (na(e, i, s, o) && (i = null),
    o || s === null ? la(e) && (i === null ? a.removeAttribute(e) : a.setAttribute(e, "" + i)) : s.mustUseProperty ? a[s.propertyName] = i === null ? s.type === 3 ? !1 : "" : i : (e = s.attributeName,
    o = s.attributeNamespace,
    i === null ? a.removeAttribute(e) : (s = s.type,
    i = s === 3 || s === 4 && i === !0 ? "" : "" + i,
    o ? a.setAttributeNS(o, e, i) : a.setAttribute(e, i))))
}
var ra = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
  , sa = 60103
  , ta = 60106
  , ua = 60107
  , wa = 60108
  , xa = 60114
  , ya = 60109
  , za = 60110
  , Aa = 60112
  , Ba = 60113
  , Ca = 60120
  , Da = 60115
  , Ea = 60116
  , Fa = 60121
  , Ga = 60128
  , Ha = 60129
  , Ia = 60130
  , Ja = 60131;
if (typeof Symbol == "function" && Symbol.for) {
    var E = Symbol.for;
    sa = E("react.element"),
    ta = E("react.portal"),
    ua = E("react.fragment"),
    wa = E("react.strict_mode"),
    xa = E("react.profiler"),
    ya = E("react.provider"),
    za = E("react.context"),
    Aa = E("react.forward_ref"),
    Ba = E("react.suspense"),
    Ca = E("react.suspense_list"),
    Da = E("react.memo"),
    Ea = E("react.lazy"),
    Fa = E("react.block"),
    E("react.scope"),
    Ga = E("react.opaque.id"),
    Ha = E("react.debug_trace_mode"),
    Ia = E("react.offscreen"),
    Ja = E("react.legacy_hidden")
}
var Ka = typeof Symbol == "function" && Symbol.iterator;
function La(a) {
    return a === null || typeof a != "object" ? null : (a = Ka && a[Ka] || a["@@iterator"],
    typeof a == "function" ? a : null)
}
var Ma;
function Na(a) {
    if (Ma === void 0)
        try {
            throw Error()
        } catch (i) {
            var e = i.stack.trim().match(/\n( *(at )?)/);
            Ma = e && e[1] || ""
        }
    return `
` + Ma + a
}
var Oa = !1;
function Pa(a, e) {
    if (!a || Oa)
        return "";
    Oa = !0;
    var i = Error.prepareStackTrace;
    Error.prepareStackTrace = void 0;
    try {
        if (e)
            if (e = function() {
                throw Error()
            }
            ,
            Object.defineProperty(e.prototype, "props", {
                set: function() {
                    throw Error()
                }
            }),
            typeof Reflect == "object" && Reflect.construct) {
                try {
                    Reflect.construct(e, [])
                } catch (b) {
                    var o = b
                }
                Reflect.construct(a, [], e)
            } else {
                try {
                    e.call()
                } catch (b) {
                    o = b
                }
                a.call(e.prototype)
            }
        else {
            try {
                throw Error()
            } catch (b) {
                o = b
            }
            a()
        }
    } catch (b) {
        if (b && o && typeof b.stack == "string") {
            for (var s = b.stack.split(`
`), c = o.stack.split(`
`), d = s.length - 1, _ = c.length - 1; 1 <= d && 0 <= _ && s[d] !== c[_]; )
                _--;
            for (; 1 <= d && 0 <= _; d--,
            _--)
                if (s[d] !== c[_]) {
                    if (d !== 1 || _ !== 1)
                        do
                            if (d--,
                            _--,
                            0 > _ || s[d] !== c[_])
                                return `
` + s[d].replace(" at new ", " at ");
                        while (1 <= d && 0 <= _);
                    break
                }
        }
    } finally {
        Oa = !1,
        Error.prepareStackTrace = i
    }
    return (a = a ? a.displayName || a.name : "") ? Na(a) : ""
}
function Qa(a) {
    switch (a.tag) {
    case 5:
        return Na(a.type);
    case 16:
        return Na("Lazy");
    case 13:
        return Na("Suspense");
    case 19:
        return Na("SuspenseList");
    case 0:
    case 2:
    case 15:
        return a = Pa(a.type, !1),
        a;
    case 11:
        return a = Pa(a.type.render, !1),
        a;
    case 22:
        return a = Pa(a.type._render, !1),
        a;
    case 1:
        return a = Pa(a.type, !0),
        a;
    default:
        return ""
    }
}
function Ra(a) {
    if (a == null)
        return null;
    if (typeof a == "function")
        return a.displayName || a.name || null;
    if (typeof a == "string")
        return a;
    switch (a) {
    case ua:
        return "Fragment";
    case ta:
        return "Portal";
    case xa:
        return "Profiler";
    case wa:
        return "StrictMode";
    case Ba:
        return "Suspense";
    case Ca:
        return "SuspenseList"
    }
    if (typeof a == "object")
        switch (a.$$typeof) {
        case za:
            return (a.displayName || "Context") + ".Consumer";
        case ya:
            return (a._context.displayName || "Context") + ".Provider";
        case Aa:
            var e = a.render;
            return e = e.displayName || e.name || "",
            a.displayName || (e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef");
        case Da:
            return Ra(a.type);
        case Fa:
            return Ra(a._render);
        case Ea:
            e = a._payload,
            a = a._init;
            try {
                return Ra(a(e))
            } catch {}
        }
    return null
}
function Sa(a) {
    switch (typeof a) {
    case "boolean":
    case "number":
    case "object":
    case "string":
    case "undefined":
        return a;
    default:
        return ""
    }
}
function Ta(a) {
    var e = a.type;
    return (a = a.nodeName) && a.toLowerCase() === "input" && (e === "checkbox" || e === "radio")
}
function Ua(a) {
    var e = Ta(a) ? "checked" : "value"
      , i = Object.getOwnPropertyDescriptor(a.constructor.prototype, e)
      , o = "" + a[e];
    if (!a.hasOwnProperty(e) && typeof i != "undefined" && typeof i.get == "function" && typeof i.set == "function") {
        var s = i.get
          , c = i.set;
        return Object.defineProperty(a, e, {
            configurable: !0,
            get: function() {
                return s.call(this)
            },
            set: function(d) {
                o = "" + d,
                c.call(this, d)
            }
        }),
        Object.defineProperty(a, e, {
            enumerable: i.enumerable
        }),
        {
            getValue: function() {
                return o
            },
            setValue: function(d) {
                o = "" + d
            },
            stopTracking: function() {
                a._valueTracker = null,
                delete a[e]
            }
        }
    }
}
function Va(a) {
    a._valueTracker || (a._valueTracker = Ua(a))
}
function Wa(a) {
    if (!a)
        return !1;
    var e = a._valueTracker;
    if (!e)
        return !0;
    var i = e.getValue()
      , o = "";
    return a && (o = Ta(a) ? a.checked ? "true" : "false" : a.value),
    a = o,
    a !== i ? (e.setValue(a),
    !0) : !1
}
function Xa(a) {
    if (a = a || (typeof document != "undefined" ? document : void 0),
    typeof a == "undefined")
        return null;
    try {
        return a.activeElement || a.body
    } catch {
        return a.body
    }
}
function Ya(a, e) {
    var i = e.checked;
    return m$1({}, e, {
        defaultChecked: void 0,
        defaultValue: void 0,
        value: void 0,
        checked: i != null ? i : a._wrapperState.initialChecked
    })
}
function Za(a, e) {
    var i = e.defaultValue == null ? "" : e.defaultValue
      , o = e.checked != null ? e.checked : e.defaultChecked;
    i = Sa(e.value != null ? e.value : i),
    a._wrapperState = {
        initialChecked: o,
        initialValue: i,
        controlled: e.type === "checkbox" || e.type === "radio" ? e.checked != null : e.value != null
    }
}
function $a(a, e) {
    e = e.checked,
    e != null && qa(a, "checked", e, !1)
}
function ab(a, e) {
    $a(a, e);
    var i = Sa(e.value)
      , o = e.type;
    if (i != null)
        o === "number" ? (i === 0 && a.value === "" || a.value != i) && (a.value = "" + i) : a.value !== "" + i && (a.value = "" + i);
    else if (o === "submit" || o === "reset") {
        a.removeAttribute("value");
        return
    }
    e.hasOwnProperty("value") ? bb(a, e.type, i) : e.hasOwnProperty("defaultValue") && bb(a, e.type, Sa(e.defaultValue)),
    e.checked == null && e.defaultChecked != null && (a.defaultChecked = !!e.defaultChecked)
}
function cb(a, e, i) {
    if (e.hasOwnProperty("value") || e.hasOwnProperty("defaultValue")) {
        var o = e.type;
        if (!(o !== "submit" && o !== "reset" || e.value !== void 0 && e.value !== null))
            return;
        e = "" + a._wrapperState.initialValue,
        i || e === a.value || (a.value = e),
        a.defaultValue = e
    }
    i = a.name,
    i !== "" && (a.name = ""),
    a.defaultChecked = !!a._wrapperState.initialChecked,
    i !== "" && (a.name = i)
}
function bb(a, e, i) {
    (e !== "number" || Xa(a.ownerDocument) !== a) && (i == null ? a.defaultValue = "" + a._wrapperState.initialValue : a.defaultValue !== "" + i && (a.defaultValue = "" + i))
}
function db(a) {
    var e = "";
    return aa.Children.forEach(a, function(i) {
        i != null && (e += i)
    }),
    e
}
function eb(a, e) {
    return a = m$1({
        children: void 0
    }, e),
    (e = db(e.children)) && (a.children = e),
    a
}
function fb(a, e, i, o) {
    if (a = a.options,
    e) {
        e = {};
        for (var s = 0; s < i.length; s++)
            e["$" + i[s]] = !0;
        for (i = 0; i < a.length; i++)
            s = e.hasOwnProperty("$" + a[i].value),
            a[i].selected !== s && (a[i].selected = s),
            s && o && (a[i].defaultSelected = !0)
    } else {
        for (i = "" + Sa(i),
        e = null,
        s = 0; s < a.length; s++) {
            if (a[s].value === i) {
                a[s].selected = !0,
                o && (a[s].defaultSelected = !0);
                return
            }
            e !== null || a[s].disabled || (e = a[s])
        }
        e !== null && (e.selected = !0)
    }
}
function gb(a, e) {
    if (e.dangerouslySetInnerHTML != null)
        throw Error(y(91));
    return m$1({}, e, {
        value: void 0,
        defaultValue: void 0,
        children: "" + a._wrapperState.initialValue
    })
}
function hb(a, e) {
    var i = e.value;
    if (i == null) {
        if (i = e.children,
        e = e.defaultValue,
        i != null) {
            if (e != null)
                throw Error(y(92));
            if (Array.isArray(i)) {
                if (!(1 >= i.length))
                    throw Error(y(93));
                i = i[0]
            }
            e = i
        }
        e == null && (e = ""),
        i = e
    }
    a._wrapperState = {
        initialValue: Sa(i)
    }
}
function ib(a, e) {
    var i = Sa(e.value)
      , o = Sa(e.defaultValue);
    i != null && (i = "" + i,
    i !== a.value && (a.value = i),
    e.defaultValue == null && a.defaultValue !== i && (a.defaultValue = i)),
    o != null && (a.defaultValue = "" + o)
}
function jb(a) {
    var e = a.textContent;
    e === a._wrapperState.initialValue && e !== "" && e !== null && (a.value = e)
}
var kb = {
    html: "http://www.w3.org/1999/xhtml",
    mathml: "http://www.w3.org/1998/Math/MathML",
    svg: "http://www.w3.org/2000/svg"
};
function lb(a) {
    switch (a) {
    case "svg":
        return "http://www.w3.org/2000/svg";
    case "math":
        return "http://www.w3.org/1998/Math/MathML";
    default:
        return "http://www.w3.org/1999/xhtml"
    }
}
function mb(a, e) {
    return a == null || a === "http://www.w3.org/1999/xhtml" ? lb(e) : a === "http://www.w3.org/2000/svg" && e === "foreignObject" ? "http://www.w3.org/1999/xhtml" : a
}
var nb, ob = function(a) {
    return typeof MSApp != "undefined" && MSApp.execUnsafeLocalFunction ? function(e, i, o, s) {
        MSApp.execUnsafeLocalFunction(function() {
            return a(e, i, o, s)
        })
    }
    : a
}(function(a, e) {
    if (a.namespaceURI !== kb.svg || "innerHTML"in a)
        a.innerHTML = e;
    else {
        for (nb = nb || document.createElement("div"),
        nb.innerHTML = "<svg>" + e.valueOf().toString() + "</svg>",
        e = nb.firstChild; a.firstChild; )
            a.removeChild(a.firstChild);
        for (; e.firstChild; )
            a.appendChild(e.firstChild)
    }
});
function pb(a, e) {
    if (e) {
        var i = a.firstChild;
        if (i && i === a.lastChild && i.nodeType === 3) {
            i.nodeValue = e;
            return
        }
    }
    a.textContent = e
}
var qb = {
    animationIterationCount: !0,
    borderImageOutset: !0,
    borderImageSlice: !0,
    borderImageWidth: !0,
    boxFlex: !0,
    boxFlexGroup: !0,
    boxOrdinalGroup: !0,
    columnCount: !0,
    columns: !0,
    flex: !0,
    flexGrow: !0,
    flexPositive: !0,
    flexShrink: !0,
    flexNegative: !0,
    flexOrder: !0,
    gridArea: !0,
    gridRow: !0,
    gridRowEnd: !0,
    gridRowSpan: !0,
    gridRowStart: !0,
    gridColumn: !0,
    gridColumnEnd: !0,
    gridColumnSpan: !0,
    gridColumnStart: !0,
    fontWeight: !0,
    lineClamp: !0,
    lineHeight: !0,
    opacity: !0,
    order: !0,
    orphans: !0,
    tabSize: !0,
    widows: !0,
    zIndex: !0,
    zoom: !0,
    fillOpacity: !0,
    floodOpacity: !0,
    stopOpacity: !0,
    strokeDasharray: !0,
    strokeDashoffset: !0,
    strokeMiterlimit: !0,
    strokeOpacity: !0,
    strokeWidth: !0
}
  , rb = ["Webkit", "ms", "Moz", "O"];
Object.keys(qb).forEach(function(a) {
    rb.forEach(function(e) {
        e = e + a.charAt(0).toUpperCase() + a.substring(1),
        qb[e] = qb[a]
    })
});
function sb(a, e, i) {
    return e == null || typeof e == "boolean" || e === "" ? "" : i || typeof e != "number" || e === 0 || qb.hasOwnProperty(a) && qb[a] ? ("" + e).trim() : e + "px"
}
function tb(a, e) {
    a = a.style;
    for (var i in e)
        if (e.hasOwnProperty(i)) {
            var o = i.indexOf("--") === 0
              , s = sb(i, e[i], o);
            i === "float" && (i = "cssFloat"),
            o ? a.setProperty(i, s) : a[i] = s
        }
}
var ub = m$1({
    menuitem: !0
}, {
    area: !0,
    base: !0,
    br: !0,
    col: !0,
    embed: !0,
    hr: !0,
    img: !0,
    input: !0,
    keygen: !0,
    link: !0,
    meta: !0,
    param: !0,
    source: !0,
    track: !0,
    wbr: !0
});
function vb(a, e) {
    if (e) {
        if (ub[a] && (e.children != null || e.dangerouslySetInnerHTML != null))
            throw Error(y(137, a));
        if (e.dangerouslySetInnerHTML != null) {
            if (e.children != null)
                throw Error(y(60));
            if (!(typeof e.dangerouslySetInnerHTML == "object" && "__html"in e.dangerouslySetInnerHTML))
                throw Error(y(61))
        }
        if (e.style != null && typeof e.style != "object")
            throw Error(y(62))
    }
}
function wb(a, e) {
    if (a.indexOf("-") === -1)
        return typeof e.is == "string";
    switch (a) {
    case "annotation-xml":
    case "color-profile":
    case "font-face":
    case "font-face-src":
    case "font-face-uri":
    case "font-face-format":
    case "font-face-name":
    case "missing-glyph":
        return !1;
    default:
        return !0
    }
}
function xb(a) {
    return a = a.target || a.srcElement || window,
    a.correspondingUseElement && (a = a.correspondingUseElement),
    a.nodeType === 3 ? a.parentNode : a
}
var yb = null
  , zb = null
  , Ab = null;
function Bb(a) {
    if (a = Cb(a)) {
        if (typeof yb != "function")
            throw Error(y(280));
        var e = a.stateNode;
        e && (e = Db(e),
        yb(a.stateNode, a.type, e))
    }
}
function Eb(a) {
    zb ? Ab ? Ab.push(a) : Ab = [a] : zb = a
}
function Fb() {
    if (zb) {
        var a = zb
          , e = Ab;
        if (Ab = zb = null,
        Bb(a),
        e)
            for (a = 0; a < e.length; a++)
                Bb(e[a])
    }
}
function Gb(a, e) {
    return a(e)
}
function Hb(a, e, i, o, s) {
    return a(e, i, o, s)
}
function Ib() {}
var Jb = Gb
  , Kb = !1
  , Lb = !1;
function Mb() {
    (zb !== null || Ab !== null) && (Ib(),
    Fb())
}
function Nb(a, e, i) {
    if (Lb)
        return a(e, i);
    Lb = !0;
    try {
        return Jb(a, e, i)
    } finally {
        Lb = !1,
        Mb()
    }
}
function Ob(a, e) {
    var i = a.stateNode;
    if (i === null)
        return null;
    var o = Db(i);
    if (o === null)
        return null;
    i = o[e];
    e: switch (e) {
    case "onClick":
    case "onClickCapture":
    case "onDoubleClick":
    case "onDoubleClickCapture":
    case "onMouseDown":
    case "onMouseDownCapture":
    case "onMouseMove":
    case "onMouseMoveCapture":
    case "onMouseUp":
    case "onMouseUpCapture":
    case "onMouseEnter":
        (o = !o.disabled) || (a = a.type,
        o = !(a === "button" || a === "input" || a === "select" || a === "textarea")),
        a = !o;
        break e;
    default:
        a = !1
    }
    if (a)
        return null;
    if (i && typeof i != "function")
        throw Error(y(231, e, typeof i));
    return i
}
var Pb = !1;
if (fa)
    try {
        var Qb = {};
        Object.defineProperty(Qb, "passive", {
            get: function() {
                Pb = !0
            }
        }),
        window.addEventListener("test", Qb, Qb),
        window.removeEventListener("test", Qb, Qb)
    } catch {
        Pb = !1
    }
function Rb(a, e, i, o, s, c, d, _, b) {
    var k = Array.prototype.slice.call(arguments, 3);
    try {
        e.apply(i, k)
    } catch (j) {
        this.onError(j)
    }
}
var Sb = !1
  , Tb = null
  , Ub = !1
  , Vb = null
  , Wb = {
    onError: function(a) {
        Sb = !0,
        Tb = a
    }
};
function Xb(a, e, i, o, s, c, d, _, b) {
    Sb = !1,
    Tb = null,
    Rb.apply(Wb, arguments)
}
function Yb(a, e, i, o, s, c, d, _, b) {
    if (Xb.apply(this, arguments),
    Sb) {
        if (Sb) {
            var k = Tb;
            Sb = !1,
            Tb = null
        } else
            throw Error(y(198));
        Ub || (Ub = !0,
        Vb = k)
    }
}
function Zb(a) {
    var e = a
      , i = a;
    if (a.alternate)
        for (; e.return; )
            e = e.return;
    else {
        a = e;
        do
            e = a,
            (e.flags & 1026) !== 0 && (i = e.return),
            a = e.return;
        while (a)
    }
    return e.tag === 3 ? i : null
}
function $b(a) {
    if (a.tag === 13) {
        var e = a.memoizedState;
        if (e === null && (a = a.alternate,
        a !== null && (e = a.memoizedState)),
        e !== null)
            return e.dehydrated
    }
    return null
}
function ac(a) {
    if (Zb(a) !== a)
        throw Error(y(188))
}
function bc(a) {
    var e = a.alternate;
    if (!e) {
        if (e = Zb(a),
        e === null)
            throw Error(y(188));
        return e !== a ? null : a
    }
    for (var i = a, o = e; ; ) {
        var s = i.return;
        if (s === null)
            break;
        var c = s.alternate;
        if (c === null) {
            if (o = s.return,
            o !== null) {
                i = o;
                continue
            }
            break
        }
        if (s.child === c.child) {
            for (c = s.child; c; ) {
                if (c === i)
                    return ac(s),
                    a;
                if (c === o)
                    return ac(s),
                    e;
                c = c.sibling
            }
            throw Error(y(188))
        }
        if (i.return !== o.return)
            i = s,
            o = c;
        else {
            for (var d = !1, _ = s.child; _; ) {
                if (_ === i) {
                    d = !0,
                    i = s,
                    o = c;
                    break
                }
                if (_ === o) {
                    d = !0,
                    o = s,
                    i = c;
                    break
                }
                _ = _.sibling
            }
            if (!d) {
                for (_ = c.child; _; ) {
                    if (_ === i) {
                        d = !0,
                        i = c,
                        o = s;
                        break
                    }
                    if (_ === o) {
                        d = !0,
                        o = c,
                        i = s;
                        break
                    }
                    _ = _.sibling
                }
                if (!d)
                    throw Error(y(189))
            }
        }
        if (i.alternate !== o)
            throw Error(y(190))
    }
    if (i.tag !== 3)
        throw Error(y(188));
    return i.stateNode.current === i ? a : e
}
function cc(a) {
    if (a = bc(a),
    !a)
        return null;
    for (var e = a; ; ) {
        if (e.tag === 5 || e.tag === 6)
            return e;
        if (e.child)
            e.child.return = e,
            e = e.child;
        else {
            if (e === a)
                break;
            for (; !e.sibling; ) {
                if (!e.return || e.return === a)
                    return null;
                e = e.return
            }
            e.sibling.return = e.return,
            e = e.sibling
        }
    }
    return null
}
function dc(a, e) {
    for (var i = a.alternate; e !== null; ) {
        if (e === a || e === i)
            return !0;
        e = e.return
    }
    return !1
}
var ec, fc, gc, hc, ic = !1, jc = [], kc = null, lc = null, mc = null, nc = new Map, oc = new Map, pc = [], qc = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
function rc(a, e, i, o, s) {
    return {
        blockedOn: a,
        domEventName: e,
        eventSystemFlags: i | 16,
        nativeEvent: s,
        targetContainers: [o]
    }
}
function sc(a, e) {
    switch (a) {
    case "focusin":
    case "focusout":
        kc = null;
        break;
    case "dragenter":
    case "dragleave":
        lc = null;
        break;
    case "mouseover":
    case "mouseout":
        mc = null;
        break;
    case "pointerover":
    case "pointerout":
        nc.delete(e.pointerId);
        break;
    case "gotpointercapture":
    case "lostpointercapture":
        oc.delete(e.pointerId)
    }
}
function tc(a, e, i, o, s, c) {
    return a === null || a.nativeEvent !== c ? (a = rc(e, i, o, s, c),
    e !== null && (e = Cb(e),
    e !== null && fc(e)),
    a) : (a.eventSystemFlags |= o,
    e = a.targetContainers,
    s !== null && e.indexOf(s) === -1 && e.push(s),
    a)
}
function uc(a, e, i, o, s) {
    switch (e) {
    case "focusin":
        return kc = tc(kc, a, e, i, o, s),
        !0;
    case "dragenter":
        return lc = tc(lc, a, e, i, o, s),
        !0;
    case "mouseover":
        return mc = tc(mc, a, e, i, o, s),
        !0;
    case "pointerover":
        var c = s.pointerId;
        return nc.set(c, tc(nc.get(c) || null, a, e, i, o, s)),
        !0;
    case "gotpointercapture":
        return c = s.pointerId,
        oc.set(c, tc(oc.get(c) || null, a, e, i, o, s)),
        !0
    }
    return !1
}
function vc(a) {
    var e = wc(a.target);
    if (e !== null) {
        var i = Zb(e);
        if (i !== null) {
            if (e = i.tag,
            e === 13) {
                if (e = $b(i),
                e !== null) {
                    a.blockedOn = e,
                    hc(a.lanePriority, function() {
                        r.unstable_runWithPriority(a.priority, function() {
                            gc(i)
                        })
                    });
                    return
                }
            } else if (e === 3 && i.stateNode.hydrate) {
                a.blockedOn = i.tag === 3 ? i.stateNode.containerInfo : null;
                return
            }
        }
    }
    a.blockedOn = null
}
function xc(a) {
    if (a.blockedOn !== null)
        return !1;
    for (var e = a.targetContainers; 0 < e.length; ) {
        var i = yc(a.domEventName, a.eventSystemFlags, e[0], a.nativeEvent);
        if (i !== null)
            return e = Cb(i),
            e !== null && fc(e),
            a.blockedOn = i,
            !1;
        e.shift()
    }
    return !0
}
function zc(a, e, i) {
    xc(a) && i.delete(e)
}
function Ac() {
    for (ic = !1; 0 < jc.length; ) {
        var a = jc[0];
        if (a.blockedOn !== null) {
            a = Cb(a.blockedOn),
            a !== null && ec(a);
            break
        }
        for (var e = a.targetContainers; 0 < e.length; ) {
            var i = yc(a.domEventName, a.eventSystemFlags, e[0], a.nativeEvent);
            if (i !== null) {
                a.blockedOn = i;
                break
            }
            e.shift()
        }
        a.blockedOn === null && jc.shift()
    }
    kc !== null && xc(kc) && (kc = null),
    lc !== null && xc(lc) && (lc = null),
    mc !== null && xc(mc) && (mc = null),
    nc.forEach(zc),
    oc.forEach(zc)
}
function Bc(a, e) {
    a.blockedOn === e && (a.blockedOn = null,
    ic || (ic = !0,
    r.unstable_scheduleCallback(r.unstable_NormalPriority, Ac)))
}
function Cc(a) {
    function e(s) {
        return Bc(s, a)
    }
    if (0 < jc.length) {
        Bc(jc[0], a);
        for (var i = 1; i < jc.length; i++) {
            var o = jc[i];
            o.blockedOn === a && (o.blockedOn = null)
        }
    }
    for (kc !== null && Bc(kc, a),
    lc !== null && Bc(lc, a),
    mc !== null && Bc(mc, a),
    nc.forEach(e),
    oc.forEach(e),
    i = 0; i < pc.length; i++)
        o = pc[i],
        o.blockedOn === a && (o.blockedOn = null);
    for (; 0 < pc.length && (i = pc[0],
    i.blockedOn === null); )
        vc(i),
        i.blockedOn === null && pc.shift()
}
function Dc(a, e) {
    var i = {};
    return i[a.toLowerCase()] = e.toLowerCase(),
    i["Webkit" + a] = "webkit" + e,
    i["Moz" + a] = "moz" + e,
    i
}
var Ec = {
    animationend: Dc("Animation", "AnimationEnd"),
    animationiteration: Dc("Animation", "AnimationIteration"),
    animationstart: Dc("Animation", "AnimationStart"),
    transitionend: Dc("Transition", "TransitionEnd")
}
  , Fc = {}
  , Gc = {};
fa && (Gc = document.createElement("div").style,
"AnimationEvent"in window || (delete Ec.animationend.animation,
delete Ec.animationiteration.animation,
delete Ec.animationstart.animation),
"TransitionEvent"in window || delete Ec.transitionend.transition);
function Hc(a) {
    if (Fc[a])
        return Fc[a];
    if (!Ec[a])
        return a;
    var e = Ec[a], i;
    for (i in e)
        if (e.hasOwnProperty(i) && i in Gc)
            return Fc[a] = e[i];
    return a
}
var Ic = Hc("animationend")
  , Jc = Hc("animationiteration")
  , Kc = Hc("animationstart")
  , Lc = Hc("transitionend")
  , Mc = new Map
  , Nc = new Map
  , Oc = ["abort", "abort", Ic, "animationEnd", Jc, "animationIteration", Kc, "animationStart", "canplay", "canPlay", "canplaythrough", "canPlayThrough", "durationchange", "durationChange", "emptied", "emptied", "encrypted", "encrypted", "ended", "ended", "error", "error", "gotpointercapture", "gotPointerCapture", "load", "load", "loadeddata", "loadedData", "loadedmetadata", "loadedMetadata", "loadstart", "loadStart", "lostpointercapture", "lostPointerCapture", "playing", "playing", "progress", "progress", "seeking", "seeking", "stalled", "stalled", "suspend", "suspend", "timeupdate", "timeUpdate", Lc, "transitionEnd", "waiting", "waiting"];
function Pc(a, e) {
    for (var i = 0; i < a.length; i += 2) {
        var o = a[i]
          , s = a[i + 1];
        s = "on" + (s[0].toUpperCase() + s.slice(1)),
        Nc.set(o, e),
        Mc.set(o, s),
        da(s, [o])
    }
}
var Qc = r.unstable_now;
Qc();
var F = 8;
function Rc(a) {
    if ((1 & a) !== 0)
        return F = 15,
        1;
    if ((2 & a) !== 0)
        return F = 14,
        2;
    if ((4 & a) !== 0)
        return F = 13,
        4;
    var e = 24 & a;
    return e !== 0 ? (F = 12,
    e) : (a & 32) !== 0 ? (F = 11,
    32) : (e = 192 & a,
    e !== 0 ? (F = 10,
    e) : (a & 256) !== 0 ? (F = 9,
    256) : (e = 3584 & a,
    e !== 0 ? (F = 8,
    e) : (a & 4096) !== 0 ? (F = 7,
    4096) : (e = 4186112 & a,
    e !== 0 ? (F = 6,
    e) : (e = 62914560 & a,
    e !== 0 ? (F = 5,
    e) : a & 67108864 ? (F = 4,
    67108864) : (a & 134217728) !== 0 ? (F = 3,
    134217728) : (e = 805306368 & a,
    e !== 0 ? (F = 2,
    e) : (1073741824 & a) !== 0 ? (F = 1,
    1073741824) : (F = 8,
    a))))))
}
function Sc(a) {
    switch (a) {
    case 99:
        return 15;
    case 98:
        return 10;
    case 97:
    case 96:
        return 8;
    case 95:
        return 2;
    default:
        return 0
    }
}
function Tc(a) {
    switch (a) {
    case 15:
    case 14:
        return 99;
    case 13:
    case 12:
    case 11:
    case 10:
        return 98;
    case 9:
    case 8:
    case 7:
    case 6:
    case 4:
    case 5:
        return 97;
    case 3:
    case 2:
    case 1:
        return 95;
    case 0:
        return 90;
    default:
        throw Error(y(358, a))
    }
}
function Uc(a, e) {
    var i = a.pendingLanes;
    if (i === 0)
        return F = 0;
    var o = 0
      , s = 0
      , c = a.expiredLanes
      , d = a.suspendedLanes
      , _ = a.pingedLanes;
    if (c !== 0)
        o = c,
        s = F = 15;
    else if (c = i & 134217727,
    c !== 0) {
        var b = c & ~d;
        b !== 0 ? (o = Rc(b),
        s = F) : (_ &= c,
        _ !== 0 && (o = Rc(_),
        s = F))
    } else
        c = i & ~d,
        c !== 0 ? (o = Rc(c),
        s = F) : _ !== 0 && (o = Rc(_),
        s = F);
    if (o === 0)
        return 0;
    if (o = 31 - Vc(o),
    o = i & ((0 > o ? 0 : 1 << o) << 1) - 1,
    e !== 0 && e !== o && (e & d) === 0) {
        if (Rc(e),
        s <= F)
            return e;
        F = s
    }
    if (e = a.entangledLanes,
    e !== 0)
        for (a = a.entanglements,
        e &= o; 0 < e; )
            i = 31 - Vc(e),
            s = 1 << i,
            o |= a[i],
            e &= ~s;
    return o
}
function Wc(a) {
    return a = a.pendingLanes & -1073741825,
    a !== 0 ? a : a & 1073741824 ? 1073741824 : 0
}
function Xc(a, e) {
    switch (a) {
    case 15:
        return 1;
    case 14:
        return 2;
    case 12:
        return a = Yc(24 & ~e),
        a === 0 ? Xc(10, e) : a;
    case 10:
        return a = Yc(192 & ~e),
        a === 0 ? Xc(8, e) : a;
    case 8:
        return a = Yc(3584 & ~e),
        a === 0 && (a = Yc(4186112 & ~e),
        a === 0 && (a = 512)),
        a;
    case 2:
        return e = Yc(805306368 & ~e),
        e === 0 && (e = 268435456),
        e
    }
    throw Error(y(358, a))
}
function Yc(a) {
    return a & -a
}
function Zc(a) {
    for (var e = [], i = 0; 31 > i; i++)
        e.push(a);
    return e
}
function $c(a, e, i) {
    a.pendingLanes |= e;
    var o = e - 1;
    a.suspendedLanes &= o,
    a.pingedLanes &= o,
    a = a.eventTimes,
    e = 31 - Vc(e),
    a[e] = i
}
var Vc = Math.clz32 ? Math.clz32 : ad
  , bd = Math.log
  , cd = Math.LN2;
function ad(a) {
    return a === 0 ? 32 : 31 - (bd(a) / cd | 0) | 0
}
var dd = r.unstable_UserBlockingPriority
  , ed = r.unstable_runWithPriority
  , fd = !0;
function gd(a, e, i, o) {
    Kb || Ib();
    var s = hd
      , c = Kb;
    Kb = !0;
    try {
        Hb(s, a, e, i, o)
    } finally {
        (Kb = c) || Mb()
    }
}
function id(a, e, i, o) {
    ed(dd, hd.bind(null, a, e, i, o))
}
function hd(a, e, i, o) {
    if (fd) {
        var s;
        if ((s = (e & 4) === 0) && 0 < jc.length && -1 < qc.indexOf(a))
            a = rc(null, a, e, i, o),
            jc.push(a);
        else {
            var c = yc(a, e, i, o);
            if (c === null)
                s && sc(a, o);
            else {
                if (s) {
                    if (-1 < qc.indexOf(a)) {
                        a = rc(c, a, e, i, o),
                        jc.push(a);
                        return
                    }
                    if (uc(c, a, e, i, o))
                        return;
                    sc(a, o)
                }
                jd(a, e, o, null, i)
            }
        }
    }
}
function yc(a, e, i, o) {
    var s = xb(o);
    if (s = wc(s),
    s !== null) {
        var c = Zb(s);
        if (c === null)
            s = null;
        else {
            var d = c.tag;
            if (d === 13) {
                if (s = $b(c),
                s !== null)
                    return s;
                s = null
            } else if (d === 3) {
                if (c.stateNode.hydrate)
                    return c.tag === 3 ? c.stateNode.containerInfo : null;
                s = null
            } else
                c !== s && (s = null)
        }
    }
    return jd(a, e, o, s, i),
    null
}
var kd = null
  , ld = null
  , md = null;
function nd() {
    if (md)
        return md;
    var a, e = ld, i = e.length, o, s = "value"in kd ? kd.value : kd.textContent, c = s.length;
    for (a = 0; a < i && e[a] === s[a]; a++)
        ;
    var d = i - a;
    for (o = 1; o <= d && e[i - o] === s[c - o]; o++)
        ;
    return md = s.slice(a, 1 < o ? 1 - o : void 0)
}
function od(a) {
    var e = a.keyCode;
    return "charCode"in a ? (a = a.charCode,
    a === 0 && e === 13 && (a = 13)) : a = e,
    a === 10 && (a = 13),
    32 <= a || a === 13 ? a : 0
}
function pd() {
    return !0
}
function qd() {
    return !1
}
function rd(a) {
    function e(i, o, s, c, d) {
        this._reactName = i,
        this._targetInst = s,
        this.type = o,
        this.nativeEvent = c,
        this.target = d,
        this.currentTarget = null;
        for (var _ in a)
            a.hasOwnProperty(_) && (i = a[_],
            this[_] = i ? i(c) : c[_]);
        return this.isDefaultPrevented = (c.defaultPrevented != null ? c.defaultPrevented : c.returnValue === !1) ? pd : qd,
        this.isPropagationStopped = qd,
        this
    }
    return m$1(e.prototype, {
        preventDefault: function() {
            this.defaultPrevented = !0;
            var i = this.nativeEvent;
            i && (i.preventDefault ? i.preventDefault() : typeof i.returnValue != "unknown" && (i.returnValue = !1),
            this.isDefaultPrevented = pd)
        },
        stopPropagation: function() {
            var i = this.nativeEvent;
            i && (i.stopPropagation ? i.stopPropagation() : typeof i.cancelBubble != "unknown" && (i.cancelBubble = !0),
            this.isPropagationStopped = pd)
        },
        persist: function() {},
        isPersistent: pd
    }),
    e
}
var sd = {
    eventPhase: 0,
    bubbles: 0,
    cancelable: 0,
    timeStamp: function(a) {
        return a.timeStamp || Date.now()
    },
    defaultPrevented: 0,
    isTrusted: 0
}, td = rd(sd), ud = m$1({}, sd, {
    view: 0,
    detail: 0
}), vd = rd(ud), wd, xd, yd, Ad = m$1({}, ud, {
    screenX: 0,
    screenY: 0,
    clientX: 0,
    clientY: 0,
    pageX: 0,
    pageY: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    getModifierState: zd,
    button: 0,
    buttons: 0,
    relatedTarget: function(a) {
        return a.relatedTarget === void 0 ? a.fromElement === a.srcElement ? a.toElement : a.fromElement : a.relatedTarget
    },
    movementX: function(a) {
        return "movementX"in a ? a.movementX : (a !== yd && (yd && a.type === "mousemove" ? (wd = a.screenX - yd.screenX,
        xd = a.screenY - yd.screenY) : xd = wd = 0,
        yd = a),
        wd)
    },
    movementY: function(a) {
        return "movementY"in a ? a.movementY : xd
    }
}), Bd = rd(Ad), Cd = m$1({}, Ad, {
    dataTransfer: 0
}), Dd = rd(Cd), Ed = m$1({}, ud, {
    relatedTarget: 0
}), Fd = rd(Ed), Gd = m$1({}, sd, {
    animationName: 0,
    elapsedTime: 0,
    pseudoElement: 0
}), Hd = rd(Gd), Id = m$1({}, sd, {
    clipboardData: function(a) {
        return "clipboardData"in a ? a.clipboardData : window.clipboardData
    }
}), Jd = rd(Id), Kd = m$1({}, sd, {
    data: 0
}), Ld = rd(Kd), Md = {
    Esc: "Escape",
    Spacebar: " ",
    Left: "ArrowLeft",
    Up: "ArrowUp",
    Right: "ArrowRight",
    Down: "ArrowDown",
    Del: "Delete",
    Win: "OS",
    Menu: "ContextMenu",
    Apps: "ContextMenu",
    Scroll: "ScrollLock",
    MozPrintableKey: "Unidentified"
}, Nd = {
    8: "Backspace",
    9: "Tab",
    12: "Clear",
    13: "Enter",
    16: "Shift",
    17: "Control",
    18: "Alt",
    19: "Pause",
    20: "CapsLock",
    27: "Escape",
    32: " ",
    33: "PageUp",
    34: "PageDown",
    35: "End",
    36: "Home",
    37: "ArrowLeft",
    38: "ArrowUp",
    39: "ArrowRight",
    40: "ArrowDown",
    45: "Insert",
    46: "Delete",
    112: "F1",
    113: "F2",
    114: "F3",
    115: "F4",
    116: "F5",
    117: "F6",
    118: "F7",
    119: "F8",
    120: "F9",
    121: "F10",
    122: "F11",
    123: "F12",
    144: "NumLock",
    145: "ScrollLock",
    224: "Meta"
}, Od = {
    Alt: "altKey",
    Control: "ctrlKey",
    Meta: "metaKey",
    Shift: "shiftKey"
};
function Pd(a) {
    var e = this.nativeEvent;
    return e.getModifierState ? e.getModifierState(a) : (a = Od[a]) ? !!e[a] : !1
}
function zd() {
    return Pd
}
var Qd = m$1({}, ud, {
    key: function(a) {
        if (a.key) {
            var e = Md[a.key] || a.key;
            if (e !== "Unidentified")
                return e
        }
        return a.type === "keypress" ? (a = od(a),
        a === 13 ? "Enter" : String.fromCharCode(a)) : a.type === "keydown" || a.type === "keyup" ? Nd[a.keyCode] || "Unidentified" : ""
    },
    code: 0,
    location: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    repeat: 0,
    locale: 0,
    getModifierState: zd,
    charCode: function(a) {
        return a.type === "keypress" ? od(a) : 0
    },
    keyCode: function(a) {
        return a.type === "keydown" || a.type === "keyup" ? a.keyCode : 0
    },
    which: function(a) {
        return a.type === "keypress" ? od(a) : a.type === "keydown" || a.type === "keyup" ? a.keyCode : 0
    }
})
  , Rd = rd(Qd)
  , Sd = m$1({}, Ad, {
    pointerId: 0,
    width: 0,
    height: 0,
    pressure: 0,
    tangentialPressure: 0,
    tiltX: 0,
    tiltY: 0,
    twist: 0,
    pointerType: 0,
    isPrimary: 0
})
  , Td = rd(Sd)
  , Ud = m$1({}, ud, {
    touches: 0,
    targetTouches: 0,
    changedTouches: 0,
    altKey: 0,
    metaKey: 0,
    ctrlKey: 0,
    shiftKey: 0,
    getModifierState: zd
})
  , Vd = rd(Ud)
  , Wd = m$1({}, sd, {
    propertyName: 0,
    elapsedTime: 0,
    pseudoElement: 0
})
  , Xd = rd(Wd)
  , Yd = m$1({}, Ad, {
    deltaX: function(a) {
        return "deltaX"in a ? a.deltaX : "wheelDeltaX"in a ? -a.wheelDeltaX : 0
    },
    deltaY: function(a) {
        return "deltaY"in a ? a.deltaY : "wheelDeltaY"in a ? -a.wheelDeltaY : "wheelDelta"in a ? -a.wheelDelta : 0
    },
    deltaZ: 0,
    deltaMode: 0
})
  , Zd = rd(Yd)
  , $d = [9, 13, 27, 32]
  , ae = fa && "CompositionEvent"in window
  , be = null;
fa && "documentMode"in document && (be = document.documentMode);
var ce = fa && "TextEvent"in window && !be
  , de = fa && (!ae || be && 8 < be && 11 >= be)
  , ee = String.fromCharCode(32)
  , fe = !1;
function ge(a, e) {
    switch (a) {
    case "keyup":
        return $d.indexOf(e.keyCode) !== -1;
    case "keydown":
        return e.keyCode !== 229;
    case "keypress":
    case "mousedown":
    case "focusout":
        return !0;
    default:
        return !1
    }
}
function he(a) {
    return a = a.detail,
    typeof a == "object" && "data"in a ? a.data : null
}
var ie = !1;
function je(a, e) {
    switch (a) {
    case "compositionend":
        return he(e);
    case "keypress":
        return e.which !== 32 ? null : (fe = !0,
        ee);
    case "textInput":
        return a = e.data,
        a === ee && fe ? null : a;
    default:
        return null
    }
}
function ke(a, e) {
    if (ie)
        return a === "compositionend" || !ae && ge(a, e) ? (a = nd(),
        md = ld = kd = null,
        ie = !1,
        a) : null;
    switch (a) {
    case "paste":
        return null;
    case "keypress":
        if (!(e.ctrlKey || e.altKey || e.metaKey) || e.ctrlKey && e.altKey) {
            if (e.char && 1 < e.char.length)
                return e.char;
            if (e.which)
                return String.fromCharCode(e.which)
        }
        return null;
    case "compositionend":
        return de && e.locale !== "ko" ? null : e.data;
    default:
        return null
    }
}
var le = {
    color: !0,
    date: !0,
    datetime: !0,
    "datetime-local": !0,
    email: !0,
    month: !0,
    number: !0,
    password: !0,
    range: !0,
    search: !0,
    tel: !0,
    text: !0,
    time: !0,
    url: !0,
    week: !0
};
function me(a) {
    var e = a && a.nodeName && a.nodeName.toLowerCase();
    return e === "input" ? !!le[a.type] : e === "textarea"
}
function ne(a, e, i, o) {
    Eb(o),
    e = oe(e, "onChange"),
    0 < e.length && (i = new td("onChange","change",null,i,o),
    a.push({
        event: i,
        listeners: e
    }))
}
var pe = null
  , qe = null;
function re(a) {
    se(a, 0)
}
function te(a) {
    var e = ue(a);
    if (Wa(e))
        return a
}
function ve(a, e) {
    if (a === "change")
        return e
}
var we = !1;
if (fa) {
    var xe;
    if (fa) {
        var ye = "oninput"in document;
        if (!ye) {
            var ze = document.createElement("div");
            ze.setAttribute("oninput", "return;"),
            ye = typeof ze.oninput == "function"
        }
        xe = ye
    } else
        xe = !1;
    we = xe && (!document.documentMode || 9 < document.documentMode)
}
function Ae() {
    pe && (pe.detachEvent("onpropertychange", Be),
    qe = pe = null)
}
function Be(a) {
    if (a.propertyName === "value" && te(qe)) {
        var e = [];
        if (ne(e, qe, a, xb(a)),
        a = re,
        Kb)
            a(e);
        else {
            Kb = !0;
            try {
                Gb(a, e)
            } finally {
                Kb = !1,
                Mb()
            }
        }
    }
}
function Ce(a, e, i) {
    a === "focusin" ? (Ae(),
    pe = e,
    qe = i,
    pe.attachEvent("onpropertychange", Be)) : a === "focusout" && Ae()
}
function De(a) {
    if (a === "selectionchange" || a === "keyup" || a === "keydown")
        return te(qe)
}
function Ee(a, e) {
    if (a === "click")
        return te(e)
}
function Fe(a, e) {
    if (a === "input" || a === "change")
        return te(e)
}
function Ge(a, e) {
    return a === e && (a !== 0 || 1 / a === 1 / e) || a !== a && e !== e
}
var He = typeof Object.is == "function" ? Object.is : Ge
  , Ie = Object.prototype.hasOwnProperty;
function Je(a, e) {
    if (He(a, e))
        return !0;
    if (typeof a != "object" || a === null || typeof e != "object" || e === null)
        return !1;
    var i = Object.keys(a)
      , o = Object.keys(e);
    if (i.length !== o.length)
        return !1;
    for (o = 0; o < i.length; o++)
        if (!Ie.call(e, i[o]) || !He(a[i[o]], e[i[o]]))
            return !1;
    return !0
}
function Ke(a) {
    for (; a && a.firstChild; )
        a = a.firstChild;
    return a
}
function Le(a, e) {
    var i = Ke(a);
    a = 0;
    for (var o; i; ) {
        if (i.nodeType === 3) {
            if (o = a + i.textContent.length,
            a <= e && o >= e)
                return {
                    node: i,
                    offset: e - a
                };
            a = o
        }
        e: {
            for (; i; ) {
                if (i.nextSibling) {
                    i = i.nextSibling;
                    break e
                }
                i = i.parentNode
            }
            i = void 0
        }
        i = Ke(i)
    }
}
function Me(a, e) {
    return a && e ? a === e ? !0 : a && a.nodeType === 3 ? !1 : e && e.nodeType === 3 ? Me(a, e.parentNode) : "contains"in a ? a.contains(e) : a.compareDocumentPosition ? !!(a.compareDocumentPosition(e) & 16) : !1 : !1
}
function Ne() {
    for (var a = window, e = Xa(); e instanceof a.HTMLIFrameElement; ) {
        try {
            var i = typeof e.contentWindow.location.href == "string"
        } catch {
            i = !1
        }
        if (i)
            a = e.contentWindow;
        else
            break;
        e = Xa(a.document)
    }
    return e
}
function Oe(a) {
    var e = a && a.nodeName && a.nodeName.toLowerCase();
    return e && (e === "input" && (a.type === "text" || a.type === "search" || a.type === "tel" || a.type === "url" || a.type === "password") || e === "textarea" || a.contentEditable === "true")
}
var Pe = fa && "documentMode"in document && 11 >= document.documentMode
  , Qe = null
  , Re = null
  , Se = null
  , Te = !1;
function Ue(a, e, i) {
    var o = i.window === i ? i.document : i.nodeType === 9 ? i : i.ownerDocument;
    Te || Qe == null || Qe !== Xa(o) || (o = Qe,
    "selectionStart"in o && Oe(o) ? o = {
        start: o.selectionStart,
        end: o.selectionEnd
    } : (o = (o.ownerDocument && o.ownerDocument.defaultView || window).getSelection(),
    o = {
        anchorNode: o.anchorNode,
        anchorOffset: o.anchorOffset,
        focusNode: o.focusNode,
        focusOffset: o.focusOffset
    }),
    Se && Je(Se, o) || (Se = o,
    o = oe(Re, "onSelect"),
    0 < o.length && (e = new td("onSelect","select",null,e,i),
    a.push({
        event: e,
        listeners: o
    }),
    e.target = Qe)))
}
Pc("cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focusin focus focusout blur input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange".split(" "), 0);
Pc("drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel".split(" "), 1);
Pc(Oc, 2);
for (var Ve = "change selectionchange textInput compositionstart compositionend compositionupdate".split(" "), We = 0; We < Ve.length; We++)
    Nc.set(Ve[We], 0);
ea("onMouseEnter", ["mouseout", "mouseover"]);
ea("onMouseLeave", ["mouseout", "mouseover"]);
ea("onPointerEnter", ["pointerout", "pointerover"]);
ea("onPointerLeave", ["pointerout", "pointerover"]);
da("onChange", "change click focusin focusout input keydown keyup selectionchange".split(" "));
da("onSelect", "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));
da("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
da("onCompositionEnd", "compositionend focusout keydown keypress keyup mousedown".split(" "));
da("onCompositionStart", "compositionstart focusout keydown keypress keyup mousedown".split(" "));
da("onCompositionUpdate", "compositionupdate focusout keydown keypress keyup mousedown".split(" "));
var Xe = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" ")
  , Ye = new Set("cancel close invalid load scroll toggle".split(" ").concat(Xe));
function Ze(a, e, i) {
    var o = a.type || "unknown-event";
    a.currentTarget = i,
    Yb(o, e, void 0, a),
    a.currentTarget = null
}
function se(a, e) {
    e = (e & 4) !== 0;
    for (var i = 0; i < a.length; i++) {
        var o = a[i]
          , s = o.event;
        o = o.listeners;
        e: {
            var c = void 0;
            if (e)
                for (var d = o.length - 1; 0 <= d; d--) {
                    var _ = o[d]
                      , b = _.instance
                      , k = _.currentTarget;
                    if (_ = _.listener,
                    b !== c && s.isPropagationStopped())
                        break e;
                    Ze(s, _, k),
                    c = b
                }
            else
                for (d = 0; d < o.length; d++) {
                    if (_ = o[d],
                    b = _.instance,
                    k = _.currentTarget,
                    _ = _.listener,
                    b !== c && s.isPropagationStopped())
                        break e;
                    Ze(s, _, k),
                    c = b
                }
        }
    }
    if (Ub)
        throw a = Vb,
        Ub = !1,
        Vb = null,
        a
}
function G(a, e) {
    var i = $e(e)
      , o = a + "__bubble";
    i.has(o) || (af(e, a, 2, !1),
    i.add(o))
}
var bf = "_reactListening" + Math.random().toString(36).slice(2);
function cf(a) {
    a[bf] || (a[bf] = !0,
    ba.forEach(function(e) {
        Ye.has(e) || df(e, !1, a, null),
        df(e, !0, a, null)
    }))
}
function df(a, e, i, o) {
    var s = 4 < arguments.length && arguments[4] !== void 0 ? arguments[4] : 0
      , c = i;
    if (a === "selectionchange" && i.nodeType !== 9 && (c = i.ownerDocument),
    o !== null && !e && Ye.has(a)) {
        if (a !== "scroll")
            return;
        s |= 2,
        c = o
    }
    var d = $e(c)
      , _ = a + "__" + (e ? "capture" : "bubble");
    d.has(_) || (e && (s |= 4),
    af(c, a, s, e),
    d.add(_))
}
function af(a, e, i, o) {
    var s = Nc.get(e);
    switch (s === void 0 ? 2 : s) {
    case 0:
        s = gd;
        break;
    case 1:
        s = id;
        break;
    default:
        s = hd
    }
    i = s.bind(null, e, i, a),
    s = void 0,
    !Pb || e !== "touchstart" && e !== "touchmove" && e !== "wheel" || (s = !0),
    o ? s !== void 0 ? a.addEventListener(e, i, {
        capture: !0,
        passive: s
    }) : a.addEventListener(e, i, !0) : s !== void 0 ? a.addEventListener(e, i, {
        passive: s
    }) : a.addEventListener(e, i, !1)
}
function jd(a, e, i, o, s) {
    var c = o;
    if ((e & 1) === 0 && (e & 2) === 0 && o !== null)
        e: for (; ; ) {
            if (o === null)
                return;
            var d = o.tag;
            if (d === 3 || d === 4) {
                var _ = o.stateNode.containerInfo;
                if (_ === s || _.nodeType === 8 && _.parentNode === s)
                    break;
                if (d === 4)
                    for (d = o.return; d !== null; ) {
                        var b = d.tag;
                        if ((b === 3 || b === 4) && (b = d.stateNode.containerInfo,
                        b === s || b.nodeType === 8 && b.parentNode === s))
                            return;
                        d = d.return
                    }
                for (; _ !== null; ) {
                    if (d = wc(_),
                    d === null)
                        return;
                    if (b = d.tag,
                    b === 5 || b === 6) {
                        o = c = d;
                        continue e
                    }
                    _ = _.parentNode
                }
            }
            o = o.return
        }
    Nb(function() {
        var k = c
          , j = xb(i)
          , $ = [];
        e: {
            var _e = Mc.get(a);
            if (_e !== void 0) {
                var et = td
                  , tt = a;
                switch (a) {
                case "keypress":
                    if (od(i) === 0)
                        break e;
                case "keydown":
                case "keyup":
                    et = Rd;
                    break;
                case "focusin":
                    tt = "focus",
                    et = Fd;
                    break;
                case "focusout":
                    tt = "blur",
                    et = Fd;
                    break;
                case "beforeblur":
                case "afterblur":
                    et = Fd;
                    break;
                case "click":
                    if (i.button === 2)
                        break e;
                case "auxclick":
                case "dblclick":
                case "mousedown":
                case "mousemove":
                case "mouseup":
                case "mouseout":
                case "mouseover":
                case "contextmenu":
                    et = Bd;
                    break;
                case "drag":
                case "dragend":
                case "dragenter":
                case "dragexit":
                case "dragleave":
                case "dragover":
                case "dragstart":
                case "drop":
                    et = Dd;
                    break;
                case "touchcancel":
                case "touchend":
                case "touchmove":
                case "touchstart":
                    et = Vd;
                    break;
                case Ic:
                case Jc:
                case Kc:
                    et = Hd;
                    break;
                case Lc:
                    et = Xd;
                    break;
                case "scroll":
                    et = vd;
                    break;
                case "wheel":
                    et = Zd;
                    break;
                case "copy":
                case "cut":
                case "paste":
                    et = Jd;
                    break;
                case "gotpointercapture":
                case "lostpointercapture":
                case "pointercancel":
                case "pointerdown":
                case "pointermove":
                case "pointerout":
                case "pointerover":
                case "pointerup":
                    et = Td
                }
                var rt = (e & 4) !== 0
                  , it = !rt && a === "scroll"
                  , nt = rt ? _e !== null ? _e + "Capture" : null : _e;
                rt = [];
                for (var ot = k, at; ot !== null; ) {
                    at = ot;
                    var st = at.stateNode;
                    if (at.tag === 5 && st !== null && (at = st,
                    nt !== null && (st = Ob(ot, nt),
                    st != null && rt.push(ef(ot, st, at)))),
                    it)
                        break;
                    ot = ot.return
                }
                0 < rt.length && (_e = new et(_e,tt,null,i,j),
                $.push({
                    event: _e,
                    listeners: rt
                }))
            }
        }
        if ((e & 7) === 0) {
            e: {
                if (_e = a === "mouseover" || a === "pointerover",
                et = a === "mouseout" || a === "pointerout",
                _e && (e & 16) === 0 && (tt = i.relatedTarget || i.fromElement) && (wc(tt) || tt[ff]))
                    break e;
                if ((et || _e) && (_e = j.window === j ? j : (_e = j.ownerDocument) ? _e.defaultView || _e.parentWindow : window,
                et ? (tt = i.relatedTarget || i.toElement,
                et = k,
                tt = tt ? wc(tt) : null,
                tt !== null && (it = Zb(tt),
                tt !== it || tt.tag !== 5 && tt.tag !== 6) && (tt = null)) : (et = null,
                tt = k),
                et !== tt)) {
                    if (rt = Bd,
                    st = "onMouseLeave",
                    nt = "onMouseEnter",
                    ot = "mouse",
                    (a === "pointerout" || a === "pointerover") && (rt = Td,
                    st = "onPointerLeave",
                    nt = "onPointerEnter",
                    ot = "pointer"),
                    it = et == null ? _e : ue(et),
                    at = tt == null ? _e : ue(tt),
                    _e = new rt(st,ot + "leave",et,i,j),
                    _e.target = it,
                    _e.relatedTarget = at,
                    st = null,
                    wc(j) === k && (rt = new rt(nt,ot + "enter",tt,i,j),
                    rt.target = at,
                    rt.relatedTarget = it,
                    st = rt),
                    it = st,
                    et && tt)
                        t: {
                            for (rt = et,
                            nt = tt,
                            ot = 0,
                            at = rt; at; at = gf(at))
                                ot++;
                            for (at = 0,
                            st = nt; st; st = gf(st))
                                at++;
                            for (; 0 < ot - at; )
                                rt = gf(rt),
                                ot--;
                            for (; 0 < at - ot; )
                                nt = gf(nt),
                                at--;
                            for (; ot--; ) {
                                if (rt === nt || nt !== null && rt === nt.alternate)
                                    break t;
                                rt = gf(rt),
                                nt = gf(nt)
                            }
                            rt = null
                        }
                    else
                        rt = null;
                    et !== null && hf($, _e, et, rt, !1),
                    tt !== null && it !== null && hf($, it, tt, rt, !0)
                }
            }
            e: {
                if (_e = k ? ue(k) : window,
                et = _e.nodeName && _e.nodeName.toLowerCase(),
                et === "select" || et === "input" && _e.type === "file")
                    var ut = ve;
                else if (me(_e))
                    if (we)
                        ut = Fe;
                    else {
                        ut = De;
                        var ct = Ce
                    }
                else
                    (et = _e.nodeName) && et.toLowerCase() === "input" && (_e.type === "checkbox" || _e.type === "radio") && (ut = Ee);
                if (ut && (ut = ut(a, k))) {
                    ne($, ut, i, j);
                    break e
                }
                ct && ct(a, _e, k),
                a === "focusout" && (ct = _e._wrapperState) && ct.controlled && _e.type === "number" && bb(_e, "number", _e.value)
            }
            switch (ct = k ? ue(k) : window,
            a) {
            case "focusin":
                (me(ct) || ct.contentEditable === "true") && (Qe = ct,
                Re = k,
                Se = null);
                break;
            case "focusout":
                Se = Re = Qe = null;
                break;
            case "mousedown":
                Te = !0;
                break;
            case "contextmenu":
            case "mouseup":
            case "dragend":
                Te = !1,
                Ue($, i, j);
                break;
            case "selectionchange":
                if (Pe)
                    break;
            case "keydown":
            case "keyup":
                Ue($, i, j)
            }
            var lt;
            if (ae)
                e: {
                    switch (a) {
                    case "compositionstart":
                        var ft = "onCompositionStart";
                        break e;
                    case "compositionend":
                        ft = "onCompositionEnd";
                        break e;
                    case "compositionupdate":
                        ft = "onCompositionUpdate";
                        break e
                    }
                    ft = void 0
                }
            else
                ie ? ge(a, i) && (ft = "onCompositionEnd") : a === "keydown" && i.keyCode === 229 && (ft = "onCompositionStart");
            ft && (de && i.locale !== "ko" && (ie || ft !== "onCompositionStart" ? ft === "onCompositionEnd" && ie && (lt = nd()) : (kd = j,
            ld = "value"in kd ? kd.value : kd.textContent,
            ie = !0)),
            ct = oe(k, ft),
            0 < ct.length && (ft = new Ld(ft,a,null,i,j),
            $.push({
                event: ft,
                listeners: ct
            }),
            lt ? ft.data = lt : (lt = he(i),
            lt !== null && (ft.data = lt)))),
            (lt = ce ? je(a, i) : ke(a, i)) && (k = oe(k, "onBeforeInput"),
            0 < k.length && (j = new Ld("onBeforeInput","beforeinput",null,i,j),
            $.push({
                event: j,
                listeners: k
            }),
            j.data = lt))
        }
        se($, e)
    })
}
function ef(a, e, i) {
    return {
        instance: a,
        listener: e,
        currentTarget: i
    }
}
function oe(a, e) {
    for (var i = e + "Capture", o = []; a !== null; ) {
        var s = a
          , c = s.stateNode;
        s.tag === 5 && c !== null && (s = c,
        c = Ob(a, i),
        c != null && o.unshift(ef(a, c, s)),
        c = Ob(a, e),
        c != null && o.push(ef(a, c, s))),
        a = a.return
    }
    return o
}
function gf(a) {
    if (a === null)
        return null;
    do
        a = a.return;
    while (a && a.tag !== 5);
    return a || null
}
function hf(a, e, i, o, s) {
    for (var c = e._reactName, d = []; i !== null && i !== o; ) {
        var _ = i
          , b = _.alternate
          , k = _.stateNode;
        if (b !== null && b === o)
            break;
        _.tag === 5 && k !== null && (_ = k,
        s ? (b = Ob(i, c),
        b != null && d.unshift(ef(i, b, _))) : s || (b = Ob(i, c),
        b != null && d.push(ef(i, b, _)))),
        i = i.return
    }
    d.length !== 0 && a.push({
        event: e,
        listeners: d
    })
}
function jf() {}
var kf = null
  , lf = null;
function mf(a, e) {
    switch (a) {
    case "button":
    case "input":
    case "select":
    case "textarea":
        return !!e.autoFocus
    }
    return !1
}
function nf(a, e) {
    return a === "textarea" || a === "option" || a === "noscript" || typeof e.children == "string" || typeof e.children == "number" || typeof e.dangerouslySetInnerHTML == "object" && e.dangerouslySetInnerHTML !== null && e.dangerouslySetInnerHTML.__html != null
}
var of = typeof setTimeout == "function" ? setTimeout : void 0
  , pf = typeof clearTimeout == "function" ? clearTimeout : void 0;
function qf(a) {
    a.nodeType === 1 ? a.textContent = "" : a.nodeType === 9 && (a = a.body,
    a != null && (a.textContent = ""))
}
function rf(a) {
    for (; a != null; a = a.nextSibling) {
        var e = a.nodeType;
        if (e === 1 || e === 3)
            break
    }
    return a
}
function sf(a) {
    a = a.previousSibling;
    for (var e = 0; a; ) {
        if (a.nodeType === 8) {
            var i = a.data;
            if (i === "$" || i === "$!" || i === "$?") {
                if (e === 0)
                    return a;
                e--
            } else
                i === "/$" && e++
        }
        a = a.previousSibling
    }
    return null
}
var tf = 0;
function uf(a) {
    return {
        $$typeof: Ga,
        toString: a,
        valueOf: a
    }
}
var vf = Math.random().toString(36).slice(2)
  , wf = "__reactFiber$" + vf
  , xf = "__reactProps$" + vf
  , ff = "__reactContainer$" + vf
  , yf = "__reactEvents$" + vf;
function wc(a) {
    var e = a[wf];
    if (e)
        return e;
    for (var i = a.parentNode; i; ) {
        if (e = i[ff] || i[wf]) {
            if (i = e.alternate,
            e.child !== null || i !== null && i.child !== null)
                for (a = sf(a); a !== null; ) {
                    if (i = a[wf])
                        return i;
                    a = sf(a)
                }
            return e
        }
        a = i,
        i = a.parentNode
    }
    return null
}
function Cb(a) {
    return a = a[wf] || a[ff],
    !a || a.tag !== 5 && a.tag !== 6 && a.tag !== 13 && a.tag !== 3 ? null : a
}
function ue(a) {
    if (a.tag === 5 || a.tag === 6)
        return a.stateNode;
    throw Error(y(33))
}
function Db(a) {
    return a[xf] || null
}
function $e(a) {
    var e = a[yf];
    return e === void 0 && (e = a[yf] = new Set),
    e
}
var zf = []
  , Af = -1;
function Bf(a) {
    return {
        current: a
    }
}
function H(a) {
    0 > Af || (a.current = zf[Af],
    zf[Af] = null,
    Af--)
}
function I(a, e) {
    Af++,
    zf[Af] = a.current,
    a.current = e
}
var Cf = {}
  , M = Bf(Cf)
  , N = Bf(!1)
  , Df = Cf;
function Ef(a, e) {
    var i = a.type.contextTypes;
    if (!i)
        return Cf;
    var o = a.stateNode;
    if (o && o.__reactInternalMemoizedUnmaskedChildContext === e)
        return o.__reactInternalMemoizedMaskedChildContext;
    var s = {}, c;
    for (c in i)
        s[c] = e[c];
    return o && (a = a.stateNode,
    a.__reactInternalMemoizedUnmaskedChildContext = e,
    a.__reactInternalMemoizedMaskedChildContext = s),
    s
}
function Ff(a) {
    return a = a.childContextTypes,
    a != null
}
function Gf() {
    H(N),
    H(M)
}
function Hf(a, e, i) {
    if (M.current !== Cf)
        throw Error(y(168));
    I(M, e),
    I(N, i)
}
function If(a, e, i) {
    var o = a.stateNode;
    if (a = e.childContextTypes,
    typeof o.getChildContext != "function")
        return i;
    o = o.getChildContext();
    for (var s in o)
        if (!(s in a))
            throw Error(y(108, Ra(e) || "Unknown", s));
    return m$1({}, i, o)
}
function Jf(a) {
    return a = (a = a.stateNode) && a.__reactInternalMemoizedMergedChildContext || Cf,
    Df = M.current,
    I(M, a),
    I(N, N.current),
    !0
}
function Kf(a, e, i) {
    var o = a.stateNode;
    if (!o)
        throw Error(y(169));
    i ? (a = If(a, e, Df),
    o.__reactInternalMemoizedMergedChildContext = a,
    H(N),
    H(M),
    I(M, a)) : H(N),
    I(N, i)
}
var Lf = null
  , Mf = null
  , Nf = r.unstable_runWithPriority
  , Of = r.unstable_scheduleCallback
  , Pf = r.unstable_cancelCallback
  , Qf = r.unstable_shouldYield
  , Rf = r.unstable_requestPaint
  , Sf = r.unstable_now
  , Tf = r.unstable_getCurrentPriorityLevel
  , Uf = r.unstable_ImmediatePriority
  , Vf = r.unstable_UserBlockingPriority
  , Wf = r.unstable_NormalPriority
  , Xf = r.unstable_LowPriority
  , Yf = r.unstable_IdlePriority
  , Zf = {}
  , $f = Rf !== void 0 ? Rf : function() {}
  , ag = null
  , bg = null
  , cg = !1
  , dg = Sf()
  , O = 1e4 > dg ? Sf : function() {
    return Sf() - dg
}
;
function eg() {
    switch (Tf()) {
    case Uf:
        return 99;
    case Vf:
        return 98;
    case Wf:
        return 97;
    case Xf:
        return 96;
    case Yf:
        return 95;
    default:
        throw Error(y(332))
    }
}
function fg(a) {
    switch (a) {
    case 99:
        return Uf;
    case 98:
        return Vf;
    case 97:
        return Wf;
    case 96:
        return Xf;
    case 95:
        return Yf;
    default:
        throw Error(y(332))
    }
}
function gg(a, e) {
    return a = fg(a),
    Nf(a, e)
}
function hg(a, e, i) {
    return a = fg(a),
    Of(a, e, i)
}
function ig() {
    if (bg !== null) {
        var a = bg;
        bg = null,
        Pf(a)
    }
    jg()
}
function jg() {
    if (!cg && ag !== null) {
        cg = !0;
        var a = 0;
        try {
            var e = ag;
            gg(99, function() {
                for (; a < e.length; a++) {
                    var i = e[a];
                    do
                        i = i(!0);
                    while (i !== null)
                }
            }),
            ag = null
        } catch (i) {
            throw ag !== null && (ag = ag.slice(a + 1)),
            Of(Uf, ig),
            i
        } finally {
            cg = !1
        }
    }
}
var kg = ra.ReactCurrentBatchConfig;
function lg(a, e) {
    if (a && a.defaultProps) {
        e = m$1({}, e),
        a = a.defaultProps;
        for (var i in a)
            e[i] === void 0 && (e[i] = a[i]);
        return e
    }
    return e
}
var mg = Bf(null)
  , ng = null
  , og = null
  , pg = null;
function qg() {
    pg = og = ng = null
}
function rg(a) {
    var e = mg.current;
    H(mg),
    a.type._context._currentValue = e
}
function sg(a, e) {
    for (; a !== null; ) {
        var i = a.alternate;
        if ((a.childLanes & e) === e) {
            if (i === null || (i.childLanes & e) === e)
                break;
            i.childLanes |= e
        } else
            a.childLanes |= e,
            i !== null && (i.childLanes |= e);
        a = a.return
    }
}
function tg(a, e) {
    ng = a,
    pg = og = null,
    a = a.dependencies,
    a !== null && a.firstContext !== null && ((a.lanes & e) !== 0 && (ug = !0),
    a.firstContext = null)
}
function vg(a, e) {
    if (pg !== a && e !== !1 && e !== 0)
        if ((typeof e != "number" || e === 1073741823) && (pg = a,
        e = 1073741823),
        e = {
            context: a,
            observedBits: e,
            next: null
        },
        og === null) {
            if (ng === null)
                throw Error(y(308));
            og = e,
            ng.dependencies = {
                lanes: 0,
                firstContext: e,
                responders: null
            }
        } else
            og = og.next = e;
    return a._currentValue
}
var wg = !1;
function xg(a) {
    a.updateQueue = {
        baseState: a.memoizedState,
        firstBaseUpdate: null,
        lastBaseUpdate: null,
        shared: {
            pending: null
        },
        effects: null
    }
}
function yg(a, e) {
    a = a.updateQueue,
    e.updateQueue === a && (e.updateQueue = {
        baseState: a.baseState,
        firstBaseUpdate: a.firstBaseUpdate,
        lastBaseUpdate: a.lastBaseUpdate,
        shared: a.shared,
        effects: a.effects
    })
}
function zg(a, e) {
    return {
        eventTime: a,
        lane: e,
        tag: 0,
        payload: null,
        callback: null,
        next: null
    }
}
function Ag(a, e) {
    if (a = a.updateQueue,
    a !== null) {
        a = a.shared;
        var i = a.pending;
        i === null ? e.next = e : (e.next = i.next,
        i.next = e),
        a.pending = e
    }
}
function Bg(a, e) {
    var i = a.updateQueue
      , o = a.alternate;
    if (o !== null && (o = o.updateQueue,
    i === o)) {
        var s = null
          , c = null;
        if (i = i.firstBaseUpdate,
        i !== null) {
            do {
                var d = {
                    eventTime: i.eventTime,
                    lane: i.lane,
                    tag: i.tag,
                    payload: i.payload,
                    callback: i.callback,
                    next: null
                };
                c === null ? s = c = d : c = c.next = d,
                i = i.next
            } while (i !== null);
            c === null ? s = c = e : c = c.next = e
        } else
            s = c = e;
        i = {
            baseState: o.baseState,
            firstBaseUpdate: s,
            lastBaseUpdate: c,
            shared: o.shared,
            effects: o.effects
        },
        a.updateQueue = i;
        return
    }
    a = i.lastBaseUpdate,
    a === null ? i.firstBaseUpdate = e : a.next = e,
    i.lastBaseUpdate = e
}
function Cg(a, e, i, o) {
    var s = a.updateQueue;
    wg = !1;
    var c = s.firstBaseUpdate
      , d = s.lastBaseUpdate
      , _ = s.shared.pending;
    if (_ !== null) {
        s.shared.pending = null;
        var b = _
          , k = b.next;
        b.next = null,
        d === null ? c = k : d.next = k,
        d = b;
        var j = a.alternate;
        if (j !== null) {
            j = j.updateQueue;
            var $ = j.lastBaseUpdate;
            $ !== d && ($ === null ? j.firstBaseUpdate = k : $.next = k,
            j.lastBaseUpdate = b)
        }
    }
    if (c !== null) {
        $ = s.baseState,
        d = 0,
        j = k = b = null;
        do {
            _ = c.lane;
            var _e = c.eventTime;
            if ((o & _) === _) {
                j !== null && (j = j.next = {
                    eventTime: _e,
                    lane: 0,
                    tag: c.tag,
                    payload: c.payload,
                    callback: c.callback,
                    next: null
                });
                e: {
                    var et = a
                      , tt = c;
                    switch (_ = e,
                    _e = i,
                    tt.tag) {
                    case 1:
                        if (et = tt.payload,
                        typeof et == "function") {
                            $ = et.call(_e, $, _);
                            break e
                        }
                        $ = et;
                        break e;
                    case 3:
                        et.flags = et.flags & -4097 | 64;
                    case 0:
                        if (et = tt.payload,
                        _ = typeof et == "function" ? et.call(_e, $, _) : et,
                        _ == null)
                            break e;
                        $ = m$1({}, $, _);
                        break e;
                    case 2:
                        wg = !0
                    }
                }
                c.callback !== null && (a.flags |= 32,
                _ = s.effects,
                _ === null ? s.effects = [c] : _.push(c))
            } else
                _e = {
                    eventTime: _e,
                    lane: _,
                    tag: c.tag,
                    payload: c.payload,
                    callback: c.callback,
                    next: null
                },
                j === null ? (k = j = _e,
                b = $) : j = j.next = _e,
                d |= _;
            if (c = c.next,
            c === null) {
                if (_ = s.shared.pending,
                _ === null)
                    break;
                c = _.next,
                _.next = null,
                s.lastBaseUpdate = _,
                s.shared.pending = null
            }
        } while (1);
        j === null && (b = $),
        s.baseState = b,
        s.firstBaseUpdate = k,
        s.lastBaseUpdate = j,
        Dg |= d,
        a.lanes = d,
        a.memoizedState = $
    }
}
function Eg(a, e, i) {
    if (a = e.effects,
    e.effects = null,
    a !== null)
        for (e = 0; e < a.length; e++) {
            var o = a[e]
              , s = o.callback;
            if (s !== null) {
                if (o.callback = null,
                o = i,
                typeof s != "function")
                    throw Error(y(191, s));
                s.call(o)
            }
        }
}
var Fg = new aa.Component().refs;
function Gg(a, e, i, o) {
    e = a.memoizedState,
    i = i(o, e),
    i = i == null ? e : m$1({}, e, i),
    a.memoizedState = i,
    a.lanes === 0 && (a.updateQueue.baseState = i)
}
var Kg = {
    isMounted: function(a) {
        return (a = a._reactInternals) ? Zb(a) === a : !1
    },
    enqueueSetState: function(a, e, i) {
        a = a._reactInternals;
        var o = Hg()
          , s = Ig(a)
          , c = zg(o, s);
        c.payload = e,
        i != null && (c.callback = i),
        Ag(a, c),
        Jg(a, s, o)
    },
    enqueueReplaceState: function(a, e, i) {
        a = a._reactInternals;
        var o = Hg()
          , s = Ig(a)
          , c = zg(o, s);
        c.tag = 1,
        c.payload = e,
        i != null && (c.callback = i),
        Ag(a, c),
        Jg(a, s, o)
    },
    enqueueForceUpdate: function(a, e) {
        a = a._reactInternals;
        var i = Hg()
          , o = Ig(a)
          , s = zg(i, o);
        s.tag = 2,
        e != null && (s.callback = e),
        Ag(a, s),
        Jg(a, o, i)
    }
};
function Lg(a, e, i, o, s, c, d) {
    return a = a.stateNode,
    typeof a.shouldComponentUpdate == "function" ? a.shouldComponentUpdate(o, c, d) : e.prototype && e.prototype.isPureReactComponent ? !Je(i, o) || !Je(s, c) : !0
}
function Mg(a, e, i) {
    var o = !1
      , s = Cf
      , c = e.contextType;
    return typeof c == "object" && c !== null ? c = vg(c) : (s = Ff(e) ? Df : M.current,
    o = e.contextTypes,
    c = (o = o != null) ? Ef(a, s) : Cf),
    e = new e(i,c),
    a.memoizedState = e.state !== null && e.state !== void 0 ? e.state : null,
    e.updater = Kg,
    a.stateNode = e,
    e._reactInternals = a,
    o && (a = a.stateNode,
    a.__reactInternalMemoizedUnmaskedChildContext = s,
    a.__reactInternalMemoizedMaskedChildContext = c),
    e
}
function Ng(a, e, i, o) {
    a = e.state,
    typeof e.componentWillReceiveProps == "function" && e.componentWillReceiveProps(i, o),
    typeof e.UNSAFE_componentWillReceiveProps == "function" && e.UNSAFE_componentWillReceiveProps(i, o),
    e.state !== a && Kg.enqueueReplaceState(e, e.state, null)
}
function Og(a, e, i, o) {
    var s = a.stateNode;
    s.props = i,
    s.state = a.memoizedState,
    s.refs = Fg,
    xg(a);
    var c = e.contextType;
    typeof c == "object" && c !== null ? s.context = vg(c) : (c = Ff(e) ? Df : M.current,
    s.context = Ef(a, c)),
    Cg(a, i, s, o),
    s.state = a.memoizedState,
    c = e.getDerivedStateFromProps,
    typeof c == "function" && (Gg(a, e, c, i),
    s.state = a.memoizedState),
    typeof e.getDerivedStateFromProps == "function" || typeof s.getSnapshotBeforeUpdate == "function" || typeof s.UNSAFE_componentWillMount != "function" && typeof s.componentWillMount != "function" || (e = s.state,
    typeof s.componentWillMount == "function" && s.componentWillMount(),
    typeof s.UNSAFE_componentWillMount == "function" && s.UNSAFE_componentWillMount(),
    e !== s.state && Kg.enqueueReplaceState(s, s.state, null),
    Cg(a, i, s, o),
    s.state = a.memoizedState),
    typeof s.componentDidMount == "function" && (a.flags |= 4)
}
var Pg = Array.isArray;
function Qg(a, e, i) {
    if (a = i.ref,
    a !== null && typeof a != "function" && typeof a != "object") {
        if (i._owner) {
            if (i = i._owner,
            i) {
                if (i.tag !== 1)
                    throw Error(y(309));
                var o = i.stateNode
            }
            if (!o)
                throw Error(y(147, a));
            var s = "" + a;
            return e !== null && e.ref !== null && typeof e.ref == "function" && e.ref._stringRef === s ? e.ref : (e = function(c) {
                var d = o.refs;
                d === Fg && (d = o.refs = {}),
                c === null ? delete d[s] : d[s] = c
            }
            ,
            e._stringRef = s,
            e)
        }
        if (typeof a != "string")
            throw Error(y(284));
        if (!i._owner)
            throw Error(y(290, a))
    }
    return a
}
function Rg(a, e) {
    if (a.type !== "textarea")
        throw Error(y(31, Object.prototype.toString.call(e) === "[object Object]" ? "object with keys {" + Object.keys(e).join(", ") + "}" : e))
}
function Sg(a) {
    function e(it, nt) {
        if (a) {
            var ot = it.lastEffect;
            ot !== null ? (ot.nextEffect = nt,
            it.lastEffect = nt) : it.firstEffect = it.lastEffect = nt,
            nt.nextEffect = null,
            nt.flags = 8
        }
    }
    function i(it, nt) {
        if (!a)
            return null;
        for (; nt !== null; )
            e(it, nt),
            nt = nt.sibling;
        return null
    }
    function o(it, nt) {
        for (it = new Map; nt !== null; )
            nt.key !== null ? it.set(nt.key, nt) : it.set(nt.index, nt),
            nt = nt.sibling;
        return it
    }
    function s(it, nt) {
        return it = Tg(it, nt),
        it.index = 0,
        it.sibling = null,
        it
    }
    function c(it, nt, ot) {
        return it.index = ot,
        a ? (ot = it.alternate,
        ot !== null ? (ot = ot.index,
        ot < nt ? (it.flags = 2,
        nt) : ot) : (it.flags = 2,
        nt)) : nt
    }
    function d(it) {
        return a && it.alternate === null && (it.flags = 2),
        it
    }
    function _(it, nt, ot, at) {
        return nt === null || nt.tag !== 6 ? (nt = Ug(ot, it.mode, at),
        nt.return = it,
        nt) : (nt = s(nt, ot),
        nt.return = it,
        nt)
    }
    function b(it, nt, ot, at) {
        return nt !== null && nt.elementType === ot.type ? (at = s(nt, ot.props),
        at.ref = Qg(it, nt, ot),
        at.return = it,
        at) : (at = Vg(ot.type, ot.key, ot.props, null, it.mode, at),
        at.ref = Qg(it, nt, ot),
        at.return = it,
        at)
    }
    function k(it, nt, ot, at) {
        return nt === null || nt.tag !== 4 || nt.stateNode.containerInfo !== ot.containerInfo || nt.stateNode.implementation !== ot.implementation ? (nt = Wg(ot, it.mode, at),
        nt.return = it,
        nt) : (nt = s(nt, ot.children || []),
        nt.return = it,
        nt)
    }
    function j(it, nt, ot, at, st) {
        return nt === null || nt.tag !== 7 ? (nt = Xg(ot, it.mode, at, st),
        nt.return = it,
        nt) : (nt = s(nt, ot),
        nt.return = it,
        nt)
    }
    function $(it, nt, ot) {
        if (typeof nt == "string" || typeof nt == "number")
            return nt = Ug("" + nt, it.mode, ot),
            nt.return = it,
            nt;
        if (typeof nt == "object" && nt !== null) {
            switch (nt.$$typeof) {
            case sa:
                return ot = Vg(nt.type, nt.key, nt.props, null, it.mode, ot),
                ot.ref = Qg(it, null, nt),
                ot.return = it,
                ot;
            case ta:
                return nt = Wg(nt, it.mode, ot),
                nt.return = it,
                nt
            }
            if (Pg(nt) || La(nt))
                return nt = Xg(nt, it.mode, ot, null),
                nt.return = it,
                nt;
            Rg(it, nt)
        }
        return null
    }
    function _e(it, nt, ot, at) {
        var st = nt !== null ? nt.key : null;
        if (typeof ot == "string" || typeof ot == "number")
            return st !== null ? null : _(it, nt, "" + ot, at);
        if (typeof ot == "object" && ot !== null) {
            switch (ot.$$typeof) {
            case sa:
                return ot.key === st ? ot.type === ua ? j(it, nt, ot.props.children, at, st) : b(it, nt, ot, at) : null;
            case ta:
                return ot.key === st ? k(it, nt, ot, at) : null
            }
            if (Pg(ot) || La(ot))
                return st !== null ? null : j(it, nt, ot, at, null);
            Rg(it, ot)
        }
        return null
    }
    function et(it, nt, ot, at, st) {
        if (typeof at == "string" || typeof at == "number")
            return it = it.get(ot) || null,
            _(nt, it, "" + at, st);
        if (typeof at == "object" && at !== null) {
            switch (at.$$typeof) {
            case sa:
                return it = it.get(at.key === null ? ot : at.key) || null,
                at.type === ua ? j(nt, it, at.props.children, st, at.key) : b(nt, it, at, st);
            case ta:
                return it = it.get(at.key === null ? ot : at.key) || null,
                k(nt, it, at, st)
            }
            if (Pg(at) || La(at))
                return it = it.get(ot) || null,
                j(nt, it, at, st, null);
            Rg(nt, at)
        }
        return null
    }
    function tt(it, nt, ot, at) {
        for (var st = null, ut = null, ct = nt, lt = nt = 0, ft = null; ct !== null && lt < ot.length; lt++) {
            ct.index > lt ? (ft = ct,
            ct = null) : ft = ct.sibling;
            var ht = _e(it, ct, ot[lt], at);
            if (ht === null) {
                ct === null && (ct = ft);
                break
            }
            a && ct && ht.alternate === null && e(it, ct),
            nt = c(ht, nt, lt),
            ut === null ? st = ht : ut.sibling = ht,
            ut = ht,
            ct = ft
        }
        if (lt === ot.length)
            return i(it, ct),
            st;
        if (ct === null) {
            for (; lt < ot.length; lt++)
                ct = $(it, ot[lt], at),
                ct !== null && (nt = c(ct, nt, lt),
                ut === null ? st = ct : ut.sibling = ct,
                ut = ct);
            return st
        }
        for (ct = o(it, ct); lt < ot.length; lt++)
            ft = et(ct, it, lt, ot[lt], at),
            ft !== null && (a && ft.alternate !== null && ct.delete(ft.key === null ? lt : ft.key),
            nt = c(ft, nt, lt),
            ut === null ? st = ft : ut.sibling = ft,
            ut = ft);
        return a && ct.forEach(function(pt) {
            return e(it, pt)
        }),
        st
    }
    function rt(it, nt, ot, at) {
        var st = La(ot);
        if (typeof st != "function")
            throw Error(y(150));
        if (ot = st.call(ot),
        ot == null)
            throw Error(y(151));
        for (var ut = st = null, ct = nt, lt = nt = 0, ft = null, ht = ot.next(); ct !== null && !ht.done; lt++,
        ht = ot.next()) {
            ct.index > lt ? (ft = ct,
            ct = null) : ft = ct.sibling;
            var pt = _e(it, ct, ht.value, at);
            if (pt === null) {
                ct === null && (ct = ft);
                break
            }
            a && ct && pt.alternate === null && e(it, ct),
            nt = c(pt, nt, lt),
            ut === null ? st = pt : ut.sibling = pt,
            ut = pt,
            ct = ft
        }
        if (ht.done)
            return i(it, ct),
            st;
        if (ct === null) {
            for (; !ht.done; lt++,
            ht = ot.next())
                ht = $(it, ht.value, at),
                ht !== null && (nt = c(ht, nt, lt),
                ut === null ? st = ht : ut.sibling = ht,
                ut = ht);
            return st
        }
        for (ct = o(it, ct); !ht.done; lt++,
        ht = ot.next())
            ht = et(ct, it, lt, ht.value, at),
            ht !== null && (a && ht.alternate !== null && ct.delete(ht.key === null ? lt : ht.key),
            nt = c(ht, nt, lt),
            ut === null ? st = ht : ut.sibling = ht,
            ut = ht);
        return a && ct.forEach(function(dt) {
            return e(it, dt)
        }),
        st
    }
    return function(it, nt, ot, at) {
        var st = typeof ot == "object" && ot !== null && ot.type === ua && ot.key === null;
        st && (ot = ot.props.children);
        var ut = typeof ot == "object" && ot !== null;
        if (ut)
            switch (ot.$$typeof) {
            case sa:
                e: {
                    for (ut = ot.key,
                    st = nt; st !== null; ) {
                        if (st.key === ut) {
                            switch (st.tag) {
                            case 7:
                                if (ot.type === ua) {
                                    i(it, st.sibling),
                                    nt = s(st, ot.props.children),
                                    nt.return = it,
                                    it = nt;
                                    break e
                                }
                                break;
                            default:
                                if (st.elementType === ot.type) {
                                    i(it, st.sibling),
                                    nt = s(st, ot.props),
                                    nt.ref = Qg(it, st, ot),
                                    nt.return = it,
                                    it = nt;
                                    break e
                                }
                            }
                            i(it, st);
                            break
                        } else
                            e(it, st);
                        st = st.sibling
                    }
                    ot.type === ua ? (nt = Xg(ot.props.children, it.mode, at, ot.key),
                    nt.return = it,
                    it = nt) : (at = Vg(ot.type, ot.key, ot.props, null, it.mode, at),
                    at.ref = Qg(it, nt, ot),
                    at.return = it,
                    it = at)
                }
                return d(it);
            case ta:
                e: {
                    for (st = ot.key; nt !== null; ) {
                        if (nt.key === st)
                            if (nt.tag === 4 && nt.stateNode.containerInfo === ot.containerInfo && nt.stateNode.implementation === ot.implementation) {
                                i(it, nt.sibling),
                                nt = s(nt, ot.children || []),
                                nt.return = it,
                                it = nt;
                                break e
                            } else {
                                i(it, nt);
                                break
                            }
                        else
                            e(it, nt);
                        nt = nt.sibling
                    }
                    nt = Wg(ot, it.mode, at),
                    nt.return = it,
                    it = nt
                }
                return d(it)
            }
        if (typeof ot == "string" || typeof ot == "number")
            return ot = "" + ot,
            nt !== null && nt.tag === 6 ? (i(it, nt.sibling),
            nt = s(nt, ot),
            nt.return = it,
            it = nt) : (i(it, nt),
            nt = Ug(ot, it.mode, at),
            nt.return = it,
            it = nt),
            d(it);
        if (Pg(ot))
            return tt(it, nt, ot, at);
        if (La(ot))
            return rt(it, nt, ot, at);
        if (ut && Rg(it, ot),
        typeof ot == "undefined" && !st)
            switch (it.tag) {
            case 1:
            case 22:
            case 0:
            case 11:
            case 15:
                throw Error(y(152, Ra(it.type) || "Component"))
            }
        return i(it, nt)
    }
}
var Yg = Sg(!0)
  , Zg = Sg(!1)
  , $g = {}
  , ah = Bf($g)
  , bh = Bf($g)
  , ch = Bf($g);
function dh(a) {
    if (a === $g)
        throw Error(y(174));
    return a
}
function eh(a, e) {
    switch (I(ch, e),
    I(bh, a),
    I(ah, $g),
    a = e.nodeType,
    a) {
    case 9:
    case 11:
        e = (e = e.documentElement) ? e.namespaceURI : mb(null, "");
        break;
    default:
        a = a === 8 ? e.parentNode : e,
        e = a.namespaceURI || null,
        a = a.tagName,
        e = mb(e, a)
    }
    H(ah),
    I(ah, e)
}
function fh() {
    H(ah),
    H(bh),
    H(ch)
}
function gh(a) {
    dh(ch.current);
    var e = dh(ah.current)
      , i = mb(e, a.type);
    e !== i && (I(bh, a),
    I(ah, i))
}
function hh(a) {
    bh.current === a && (H(ah),
    H(bh))
}
var P = Bf(0);
function ih(a) {
    for (var e = a; e !== null; ) {
        if (e.tag === 13) {
            var i = e.memoizedState;
            if (i !== null && (i = i.dehydrated,
            i === null || i.data === "$?" || i.data === "$!"))
                return e
        } else if (e.tag === 19 && e.memoizedProps.revealOrder !== void 0) {
            if ((e.flags & 64) !== 0)
                return e
        } else if (e.child !== null) {
            e.child.return = e,
            e = e.child;
            continue
        }
        if (e === a)
            break;
        for (; e.sibling === null; ) {
            if (e.return === null || e.return === a)
                return null;
            e = e.return
        }
        e.sibling.return = e.return,
        e = e.sibling
    }
    return null
}
var jh = null
  , kh = null
  , lh = !1;
function mh(a, e) {
    var i = nh(5, null, null, 0);
    i.elementType = "DELETED",
    i.type = "DELETED",
    i.stateNode = e,
    i.return = a,
    i.flags = 8,
    a.lastEffect !== null ? (a.lastEffect.nextEffect = i,
    a.lastEffect = i) : a.firstEffect = a.lastEffect = i
}
function oh(a, e) {
    switch (a.tag) {
    case 5:
        var i = a.type;
        return e = e.nodeType !== 1 || i.toLowerCase() !== e.nodeName.toLowerCase() ? null : e,
        e !== null ? (a.stateNode = e,
        !0) : !1;
    case 6:
        return e = a.pendingProps === "" || e.nodeType !== 3 ? null : e,
        e !== null ? (a.stateNode = e,
        !0) : !1;
    case 13:
        return !1;
    default:
        return !1
    }
}
function ph(a) {
    if (lh) {
        var e = kh;
        if (e) {
            var i = e;
            if (!oh(a, e)) {
                if (e = rf(i.nextSibling),
                !e || !oh(a, e)) {
                    a.flags = a.flags & -1025 | 2,
                    lh = !1,
                    jh = a;
                    return
                }
                mh(jh, i)
            }
            jh = a,
            kh = rf(e.firstChild)
        } else
            a.flags = a.flags & -1025 | 2,
            lh = !1,
            jh = a
    }
}
function qh(a) {
    for (a = a.return; a !== null && a.tag !== 5 && a.tag !== 3 && a.tag !== 13; )
        a = a.return;
    jh = a
}
function rh(a) {
    if (a !== jh)
        return !1;
    if (!lh)
        return qh(a),
        lh = !0,
        !1;
    var e = a.type;
    if (a.tag !== 5 || e !== "head" && e !== "body" && !nf(e, a.memoizedProps))
        for (e = kh; e; )
            mh(a, e),
            e = rf(e.nextSibling);
    if (qh(a),
    a.tag === 13) {
        if (a = a.memoizedState,
        a = a !== null ? a.dehydrated : null,
        !a)
            throw Error(y(317));
        e: {
            for (a = a.nextSibling,
            e = 0; a; ) {
                if (a.nodeType === 8) {
                    var i = a.data;
                    if (i === "/$") {
                        if (e === 0) {
                            kh = rf(a.nextSibling);
                            break e
                        }
                        e--
                    } else
                        i !== "$" && i !== "$!" && i !== "$?" || e++
                }
                a = a.nextSibling
            }
            kh = null
        }
    } else
        kh = jh ? rf(a.stateNode.nextSibling) : null;
    return !0
}
function sh() {
    kh = jh = null,
    lh = !1
}
var th = [];
function uh() {
    for (var a = 0; a < th.length; a++)
        th[a]._workInProgressVersionPrimary = null;
    th.length = 0
}
var vh = ra.ReactCurrentDispatcher
  , wh = ra.ReactCurrentBatchConfig
  , xh = 0
  , R = null
  , S = null
  , T = null
  , yh = !1
  , zh = !1;
function Ah() {
    throw Error(y(321))
}
function Bh(a, e) {
    if (e === null)
        return !1;
    for (var i = 0; i < e.length && i < a.length; i++)
        if (!He(a[i], e[i]))
            return !1;
    return !0
}
function Ch(a, e, i, o, s, c) {
    if (xh = c,
    R = e,
    e.memoizedState = null,
    e.updateQueue = null,
    e.lanes = 0,
    vh.current = a === null || a.memoizedState === null ? Dh : Eh,
    a = i(o, s),
    zh) {
        c = 0;
        do {
            if (zh = !1,
            !(25 > c))
                throw Error(y(301));
            c += 1,
            T = S = null,
            e.updateQueue = null,
            vh.current = Fh,
            a = i(o, s)
        } while (zh)
    }
    if (vh.current = Gh,
    e = S !== null && S.next !== null,
    xh = 0,
    T = S = R = null,
    yh = !1,
    e)
        throw Error(y(300));
    return a
}
function Hh() {
    var a = {
        memoizedState: null,
        baseState: null,
        baseQueue: null,
        queue: null,
        next: null
    };
    return T === null ? R.memoizedState = T = a : T = T.next = a,
    T
}
function Ih() {
    if (S === null) {
        var a = R.alternate;
        a = a !== null ? a.memoizedState : null
    } else
        a = S.next;
    var e = T === null ? R.memoizedState : T.next;
    if (e !== null)
        T = e,
        S = a;
    else {
        if (a === null)
            throw Error(y(310));
        S = a,
        a = {
            memoizedState: S.memoizedState,
            baseState: S.baseState,
            baseQueue: S.baseQueue,
            queue: S.queue,
            next: null
        },
        T === null ? R.memoizedState = T = a : T = T.next = a
    }
    return T
}
function Jh(a, e) {
    return typeof e == "function" ? e(a) : e
}
function Kh(a) {
    var e = Ih()
      , i = e.queue;
    if (i === null)
        throw Error(y(311));
    i.lastRenderedReducer = a;
    var o = S
      , s = o.baseQueue
      , c = i.pending;
    if (c !== null) {
        if (s !== null) {
            var d = s.next;
            s.next = c.next,
            c.next = d
        }
        o.baseQueue = s = c,
        i.pending = null
    }
    if (s !== null) {
        s = s.next,
        o = o.baseState;
        var _ = d = c = null
          , b = s;
        do {
            var k = b.lane;
            if ((xh & k) === k)
                _ !== null && (_ = _.next = {
                    lane: 0,
                    action: b.action,
                    eagerReducer: b.eagerReducer,
                    eagerState: b.eagerState,
                    next: null
                }),
                o = b.eagerReducer === a ? b.eagerState : a(o, b.action);
            else {
                var j = {
                    lane: k,
                    action: b.action,
                    eagerReducer: b.eagerReducer,
                    eagerState: b.eagerState,
                    next: null
                };
                _ === null ? (d = _ = j,
                c = o) : _ = _.next = j,
                R.lanes |= k,
                Dg |= k
            }
            b = b.next
        } while (b !== null && b !== s);
        _ === null ? c = o : _.next = d,
        He(o, e.memoizedState) || (ug = !0),
        e.memoizedState = o,
        e.baseState = c,
        e.baseQueue = _,
        i.lastRenderedState = o
    }
    return [e.memoizedState, i.dispatch]
}
function Lh(a) {
    var e = Ih()
      , i = e.queue;
    if (i === null)
        throw Error(y(311));
    i.lastRenderedReducer = a;
    var o = i.dispatch
      , s = i.pending
      , c = e.memoizedState;
    if (s !== null) {
        i.pending = null;
        var d = s = s.next;
        do
            c = a(c, d.action),
            d = d.next;
        while (d !== s);
        He(c, e.memoizedState) || (ug = !0),
        e.memoizedState = c,
        e.baseQueue === null && (e.baseState = c),
        i.lastRenderedState = c
    }
    return [c, o]
}
function Mh(a, e, i) {
    var o = e._getVersion;
    o = o(e._source);
    var s = e._workInProgressVersionPrimary;
    if (s !== null ? a = s === o : (a = a.mutableReadLanes,
    (a = (xh & a) === a) && (e._workInProgressVersionPrimary = o,
    th.push(e))),
    a)
        return i(e._source);
    throw th.push(e),
    Error(y(350))
}
function Nh(a, e, i, o) {
    var s = U;
    if (s === null)
        throw Error(y(349));
    var c = e._getVersion
      , d = c(e._source)
      , _ = vh.current
      , b = _.useState(function() {
        return Mh(s, e, i)
    })
      , k = b[1]
      , j = b[0];
    b = T;
    var $ = a.memoizedState
      , _e = $.refs
      , et = _e.getSnapshot
      , tt = $.source;
    $ = $.subscribe;
    var rt = R;
    return a.memoizedState = {
        refs: _e,
        source: e,
        subscribe: o
    },
    _.useEffect(function() {
        _e.getSnapshot = i,
        _e.setSnapshot = k;
        var it = c(e._source);
        if (!He(d, it)) {
            it = i(e._source),
            He(j, it) || (k(it),
            it = Ig(rt),
            s.mutableReadLanes |= it & s.pendingLanes),
            it = s.mutableReadLanes,
            s.entangledLanes |= it;
            for (var nt = s.entanglements, ot = it; 0 < ot; ) {
                var at = 31 - Vc(ot)
                  , st = 1 << at;
                nt[at] |= it,
                ot &= ~st
            }
        }
    }, [i, e, o]),
    _.useEffect(function() {
        return o(e._source, function() {
            var it = _e.getSnapshot
              , nt = _e.setSnapshot;
            try {
                nt(it(e._source));
                var ot = Ig(rt);
                s.mutableReadLanes |= ot & s.pendingLanes
            } catch (at) {
                nt(function() {
                    throw at
                })
            }
        })
    }, [e, o]),
    He(et, i) && He(tt, e) && He($, o) || (a = {
        pending: null,
        dispatch: null,
        lastRenderedReducer: Jh,
        lastRenderedState: j
    },
    a.dispatch = k = Oh.bind(null, R, a),
    b.queue = a,
    b.baseQueue = null,
    j = Mh(s, e, i),
    b.memoizedState = b.baseState = j),
    j
}
function Ph(a, e, i) {
    var o = Ih();
    return Nh(o, a, e, i)
}
function Qh(a) {
    var e = Hh();
    return typeof a == "function" && (a = a()),
    e.memoizedState = e.baseState = a,
    a = e.queue = {
        pending: null,
        dispatch: null,
        lastRenderedReducer: Jh,
        lastRenderedState: a
    },
    a = a.dispatch = Oh.bind(null, R, a),
    [e.memoizedState, a]
}
function Rh(a, e, i, o) {
    return a = {
        tag: a,
        create: e,
        destroy: i,
        deps: o,
        next: null
    },
    e = R.updateQueue,
    e === null ? (e = {
        lastEffect: null
    },
    R.updateQueue = e,
    e.lastEffect = a.next = a) : (i = e.lastEffect,
    i === null ? e.lastEffect = a.next = a : (o = i.next,
    i.next = a,
    a.next = o,
    e.lastEffect = a)),
    a
}
function Sh(a) {
    var e = Hh();
    return a = {
        current: a
    },
    e.memoizedState = a
}
function Th() {
    return Ih().memoizedState
}
function Uh(a, e, i, o) {
    var s = Hh();
    R.flags |= a,
    s.memoizedState = Rh(1 | e, i, void 0, o === void 0 ? null : o)
}
function Vh(a, e, i, o) {
    var s = Ih();
    o = o === void 0 ? null : o;
    var c = void 0;
    if (S !== null) {
        var d = S.memoizedState;
        if (c = d.destroy,
        o !== null && Bh(o, d.deps)) {
            Rh(e, i, c, o);
            return
        }
    }
    R.flags |= a,
    s.memoizedState = Rh(1 | e, i, c, o)
}
function Wh(a, e) {
    return Uh(516, 4, a, e)
}
function Xh(a, e) {
    return Vh(516, 4, a, e)
}
function Yh(a, e) {
    return Vh(4, 2, a, e)
}
function Zh(a, e) {
    if (typeof e == "function")
        return a = a(),
        e(a),
        function() {
            e(null)
        }
        ;
    if (e != null)
        return a = a(),
        e.current = a,
        function() {
            e.current = null
        }
}
function $h(a, e, i) {
    return i = i != null ? i.concat([a]) : null,
    Vh(4, 2, Zh.bind(null, e, a), i)
}
function ai() {}
function bi(a, e) {
    var i = Ih();
    e = e === void 0 ? null : e;
    var o = i.memoizedState;
    return o !== null && e !== null && Bh(e, o[1]) ? o[0] : (i.memoizedState = [a, e],
    a)
}
function ci(a, e) {
    var i = Ih();
    e = e === void 0 ? null : e;
    var o = i.memoizedState;
    return o !== null && e !== null && Bh(e, o[1]) ? o[0] : (a = a(),
    i.memoizedState = [a, e],
    a)
}
function di(a, e) {
    var i = eg();
    gg(98 > i ? 98 : i, function() {
        a(!0)
    }),
    gg(97 < i ? 97 : i, function() {
        var o = wh.transition;
        wh.transition = 1;
        try {
            a(!1),
            e()
        } finally {
            wh.transition = o
        }
    })
}
function Oh(a, e, i) {
    var o = Hg()
      , s = Ig(a)
      , c = {
        lane: s,
        action: i,
        eagerReducer: null,
        eagerState: null,
        next: null
    }
      , d = e.pending;
    if (d === null ? c.next = c : (c.next = d.next,
    d.next = c),
    e.pending = c,
    d = a.alternate,
    a === R || d !== null && d === R)
        zh = yh = !0;
    else {
        if (a.lanes === 0 && (d === null || d.lanes === 0) && (d = e.lastRenderedReducer,
        d !== null))
            try {
                var _ = e.lastRenderedState
                  , b = d(_, i);
                if (c.eagerReducer = d,
                c.eagerState = b,
                He(b, _))
                    return
            } catch {} finally {}
        Jg(a, s, o)
    }
}
var Gh = {
    readContext: vg,
    useCallback: Ah,
    useContext: Ah,
    useEffect: Ah,
    useImperativeHandle: Ah,
    useLayoutEffect: Ah,
    useMemo: Ah,
    useReducer: Ah,
    useRef: Ah,
    useState: Ah,
    useDebugValue: Ah,
    useDeferredValue: Ah,
    useTransition: Ah,
    useMutableSource: Ah,
    useOpaqueIdentifier: Ah,
    unstable_isNewReconciler: !1
}
  , Dh = {
    readContext: vg,
    useCallback: function(a, e) {
        return Hh().memoizedState = [a, e === void 0 ? null : e],
        a
    },
    useContext: vg,
    useEffect: Wh,
    useImperativeHandle: function(a, e, i) {
        return i = i != null ? i.concat([a]) : null,
        Uh(4, 2, Zh.bind(null, e, a), i)
    },
    useLayoutEffect: function(a, e) {
        return Uh(4, 2, a, e)
    },
    useMemo: function(a, e) {
        var i = Hh();
        return e = e === void 0 ? null : e,
        a = a(),
        i.memoizedState = [a, e],
        a
    },
    useReducer: function(a, e, i) {
        var o = Hh();
        return e = i !== void 0 ? i(e) : e,
        o.memoizedState = o.baseState = e,
        a = o.queue = {
            pending: null,
            dispatch: null,
            lastRenderedReducer: a,
            lastRenderedState: e
        },
        a = a.dispatch = Oh.bind(null, R, a),
        [o.memoizedState, a]
    },
    useRef: Sh,
    useState: Qh,
    useDebugValue: ai,
    useDeferredValue: function(a) {
        var e = Qh(a)
          , i = e[0]
          , o = e[1];
        return Wh(function() {
            var s = wh.transition;
            wh.transition = 1;
            try {
                o(a)
            } finally {
                wh.transition = s
            }
        }, [a]),
        i
    },
    useTransition: function() {
        var a = Qh(!1)
          , e = a[0];
        return a = di.bind(null, a[1]),
        Sh(a),
        [a, e]
    },
    useMutableSource: function(a, e, i) {
        var o = Hh();
        return o.memoizedState = {
            refs: {
                getSnapshot: e,
                setSnapshot: null
            },
            source: a,
            subscribe: i
        },
        Nh(o, a, e, i)
    },
    useOpaqueIdentifier: function() {
        if (lh) {
            var a = !1
              , e = uf(function() {
                throw a || (a = !0,
                i("r:" + (tf++).toString(36))),
                Error(y(355))
            })
              , i = Qh(e)[1];
            return (R.mode & 2) === 0 && (R.flags |= 516,
            Rh(5, function() {
                i("r:" + (tf++).toString(36))
            }, void 0, null)),
            e
        }
        return e = "r:" + (tf++).toString(36),
        Qh(e),
        e
    },
    unstable_isNewReconciler: !1
}
  , Eh = {
    readContext: vg,
    useCallback: bi,
    useContext: vg,
    useEffect: Xh,
    useImperativeHandle: $h,
    useLayoutEffect: Yh,
    useMemo: ci,
    useReducer: Kh,
    useRef: Th,
    useState: function() {
        return Kh(Jh)
    },
    useDebugValue: ai,
    useDeferredValue: function(a) {
        var e = Kh(Jh)
          , i = e[0]
          , o = e[1];
        return Xh(function() {
            var s = wh.transition;
            wh.transition = 1;
            try {
                o(a)
            } finally {
                wh.transition = s
            }
        }, [a]),
        i
    },
    useTransition: function() {
        var a = Kh(Jh)[0];
        return [Th().current, a]
    },
    useMutableSource: Ph,
    useOpaqueIdentifier: function() {
        return Kh(Jh)[0]
    },
    unstable_isNewReconciler: !1
}
  , Fh = {
    readContext: vg,
    useCallback: bi,
    useContext: vg,
    useEffect: Xh,
    useImperativeHandle: $h,
    useLayoutEffect: Yh,
    useMemo: ci,
    useReducer: Lh,
    useRef: Th,
    useState: function() {
        return Lh(Jh)
    },
    useDebugValue: ai,
    useDeferredValue: function(a) {
        var e = Lh(Jh)
          , i = e[0]
          , o = e[1];
        return Xh(function() {
            var s = wh.transition;
            wh.transition = 1;
            try {
                o(a)
            } finally {
                wh.transition = s
            }
        }, [a]),
        i
    },
    useTransition: function() {
        var a = Lh(Jh)[0];
        return [Th().current, a]
    },
    useMutableSource: Ph,
    useOpaqueIdentifier: function() {
        return Lh(Jh)[0]
    },
    unstable_isNewReconciler: !1
}
  , ei = ra.ReactCurrentOwner
  , ug = !1;
function fi(a, e, i, o) {
    e.child = a === null ? Zg(e, null, i, o) : Yg(e, a.child, i, o)
}
function gi(a, e, i, o, s) {
    i = i.render;
    var c = e.ref;
    return tg(e, s),
    o = Ch(a, e, i, o, c, s),
    a !== null && !ug ? (e.updateQueue = a.updateQueue,
    e.flags &= -517,
    a.lanes &= ~s,
    hi(a, e, s)) : (e.flags |= 1,
    fi(a, e, o, s),
    e.child)
}
function ii(a, e, i, o, s, c) {
    if (a === null) {
        var d = i.type;
        return typeof d == "function" && !ji(d) && d.defaultProps === void 0 && i.compare === null && i.defaultProps === void 0 ? (e.tag = 15,
        e.type = d,
        ki(a, e, d, o, s, c)) : (a = Vg(i.type, null, o, e, e.mode, c),
        a.ref = e.ref,
        a.return = e,
        e.child = a)
    }
    return d = a.child,
    (s & c) === 0 && (s = d.memoizedProps,
    i = i.compare,
    i = i !== null ? i : Je,
    i(s, o) && a.ref === e.ref) ? hi(a, e, c) : (e.flags |= 1,
    a = Tg(d, o),
    a.ref = e.ref,
    a.return = e,
    e.child = a)
}
function ki(a, e, i, o, s, c) {
    if (a !== null && Je(a.memoizedProps, o) && a.ref === e.ref)
        if (ug = !1,
        (c & s) !== 0)
            (a.flags & 16384) !== 0 && (ug = !0);
        else
            return e.lanes = a.lanes,
            hi(a, e, c);
    return li(a, e, i, o, c)
}
function mi(a, e, i) {
    var o = e.pendingProps
      , s = o.children
      , c = a !== null ? a.memoizedState : null;
    if (o.mode === "hidden" || o.mode === "unstable-defer-without-hiding")
        if ((e.mode & 4) === 0)
            e.memoizedState = {
                baseLanes: 0
            },
            ni(e, i);
        else if ((i & 1073741824) !== 0)
            e.memoizedState = {
                baseLanes: 0
            },
            ni(e, c !== null ? c.baseLanes : i);
        else
            return a = c !== null ? c.baseLanes | i : i,
            e.lanes = e.childLanes = 1073741824,
            e.memoizedState = {
                baseLanes: a
            },
            ni(e, a),
            null;
    else
        c !== null ? (o = c.baseLanes | i,
        e.memoizedState = null) : o = i,
        ni(e, o);
    return fi(a, e, s, i),
    e.child
}
function oi(a, e) {
    var i = e.ref;
    (a === null && i !== null || a !== null && a.ref !== i) && (e.flags |= 128)
}
function li(a, e, i, o, s) {
    var c = Ff(i) ? Df : M.current;
    return c = Ef(e, c),
    tg(e, s),
    i = Ch(a, e, i, o, c, s),
    a !== null && !ug ? (e.updateQueue = a.updateQueue,
    e.flags &= -517,
    a.lanes &= ~s,
    hi(a, e, s)) : (e.flags |= 1,
    fi(a, e, i, s),
    e.child)
}
function pi(a, e, i, o, s) {
    if (Ff(i)) {
        var c = !0;
        Jf(e)
    } else
        c = !1;
    if (tg(e, s),
    e.stateNode === null)
        a !== null && (a.alternate = null,
        e.alternate = null,
        e.flags |= 2),
        Mg(e, i, o),
        Og(e, i, o, s),
        o = !0;
    else if (a === null) {
        var d = e.stateNode
          , _ = e.memoizedProps;
        d.props = _;
        var b = d.context
          , k = i.contextType;
        typeof k == "object" && k !== null ? k = vg(k) : (k = Ff(i) ? Df : M.current,
        k = Ef(e, k));
        var j = i.getDerivedStateFromProps
          , $ = typeof j == "function" || typeof d.getSnapshotBeforeUpdate == "function";
        $ || typeof d.UNSAFE_componentWillReceiveProps != "function" && typeof d.componentWillReceiveProps != "function" || (_ !== o || b !== k) && Ng(e, d, o, k),
        wg = !1;
        var _e = e.memoizedState;
        d.state = _e,
        Cg(e, o, d, s),
        b = e.memoizedState,
        _ !== o || _e !== b || N.current || wg ? (typeof j == "function" && (Gg(e, i, j, o),
        b = e.memoizedState),
        (_ = wg || Lg(e, i, _, o, _e, b, k)) ? ($ || typeof d.UNSAFE_componentWillMount != "function" && typeof d.componentWillMount != "function" || (typeof d.componentWillMount == "function" && d.componentWillMount(),
        typeof d.UNSAFE_componentWillMount == "function" && d.UNSAFE_componentWillMount()),
        typeof d.componentDidMount == "function" && (e.flags |= 4)) : (typeof d.componentDidMount == "function" && (e.flags |= 4),
        e.memoizedProps = o,
        e.memoizedState = b),
        d.props = o,
        d.state = b,
        d.context = k,
        o = _) : (typeof d.componentDidMount == "function" && (e.flags |= 4),
        o = !1)
    } else {
        d = e.stateNode,
        yg(a, e),
        _ = e.memoizedProps,
        k = e.type === e.elementType ? _ : lg(e.type, _),
        d.props = k,
        $ = e.pendingProps,
        _e = d.context,
        b = i.contextType,
        typeof b == "object" && b !== null ? b = vg(b) : (b = Ff(i) ? Df : M.current,
        b = Ef(e, b));
        var et = i.getDerivedStateFromProps;
        (j = typeof et == "function" || typeof d.getSnapshotBeforeUpdate == "function") || typeof d.UNSAFE_componentWillReceiveProps != "function" && typeof d.componentWillReceiveProps != "function" || (_ !== $ || _e !== b) && Ng(e, d, o, b),
        wg = !1,
        _e = e.memoizedState,
        d.state = _e,
        Cg(e, o, d, s);
        var tt = e.memoizedState;
        _ !== $ || _e !== tt || N.current || wg ? (typeof et == "function" && (Gg(e, i, et, o),
        tt = e.memoizedState),
        (k = wg || Lg(e, i, k, o, _e, tt, b)) ? (j || typeof d.UNSAFE_componentWillUpdate != "function" && typeof d.componentWillUpdate != "function" || (typeof d.componentWillUpdate == "function" && d.componentWillUpdate(o, tt, b),
        typeof d.UNSAFE_componentWillUpdate == "function" && d.UNSAFE_componentWillUpdate(o, tt, b)),
        typeof d.componentDidUpdate == "function" && (e.flags |= 4),
        typeof d.getSnapshotBeforeUpdate == "function" && (e.flags |= 256)) : (typeof d.componentDidUpdate != "function" || _ === a.memoizedProps && _e === a.memoizedState || (e.flags |= 4),
        typeof d.getSnapshotBeforeUpdate != "function" || _ === a.memoizedProps && _e === a.memoizedState || (e.flags |= 256),
        e.memoizedProps = o,
        e.memoizedState = tt),
        d.props = o,
        d.state = tt,
        d.context = b,
        o = k) : (typeof d.componentDidUpdate != "function" || _ === a.memoizedProps && _e === a.memoizedState || (e.flags |= 4),
        typeof d.getSnapshotBeforeUpdate != "function" || _ === a.memoizedProps && _e === a.memoizedState || (e.flags |= 256),
        o = !1)
    }
    return qi(a, e, i, o, c, s)
}
function qi(a, e, i, o, s, c) {
    oi(a, e);
    var d = (e.flags & 64) !== 0;
    if (!o && !d)
        return s && Kf(e, i, !1),
        hi(a, e, c);
    o = e.stateNode,
    ei.current = e;
    var _ = d && typeof i.getDerivedStateFromError != "function" ? null : o.render();
    return e.flags |= 1,
    a !== null && d ? (e.child = Yg(e, a.child, null, c),
    e.child = Yg(e, null, _, c)) : fi(a, e, _, c),
    e.memoizedState = o.state,
    s && Kf(e, i, !0),
    e.child
}
function ri(a) {
    var e = a.stateNode;
    e.pendingContext ? Hf(a, e.pendingContext, e.pendingContext !== e.context) : e.context && Hf(a, e.context, !1),
    eh(a, e.containerInfo)
}
var si = {
    dehydrated: null,
    retryLane: 0
};
function ti(a, e, i) {
    var o = e.pendingProps, s = P.current, c = !1, d;
    return (d = (e.flags & 64) !== 0) || (d = a !== null && a.memoizedState === null ? !1 : (s & 2) !== 0),
    d ? (c = !0,
    e.flags &= -65) : a !== null && a.memoizedState === null || o.fallback === void 0 || o.unstable_avoidThisFallback === !0 || (s |= 1),
    I(P, s & 1),
    a === null ? (o.fallback !== void 0 && ph(e),
    a = o.children,
    s = o.fallback,
    c ? (a = ui(e, a, s, i),
    e.child.memoizedState = {
        baseLanes: i
    },
    e.memoizedState = si,
    a) : typeof o.unstable_expectedLoadTime == "number" ? (a = ui(e, a, s, i),
    e.child.memoizedState = {
        baseLanes: i
    },
    e.memoizedState = si,
    e.lanes = 33554432,
    a) : (i = vi({
        mode: "visible",
        children: a
    }, e.mode, i, null),
    i.return = e,
    e.child = i)) : a.memoizedState !== null ? c ? (o = wi(a, e, o.children, o.fallback, i),
    c = e.child,
    s = a.child.memoizedState,
    c.memoizedState = s === null ? {
        baseLanes: i
    } : {
        baseLanes: s.baseLanes | i
    },
    c.childLanes = a.childLanes & ~i,
    e.memoizedState = si,
    o) : (i = xi(a, e, o.children, i),
    e.memoizedState = null,
    i) : c ? (o = wi(a, e, o.children, o.fallback, i),
    c = e.child,
    s = a.child.memoizedState,
    c.memoizedState = s === null ? {
        baseLanes: i
    } : {
        baseLanes: s.baseLanes | i
    },
    c.childLanes = a.childLanes & ~i,
    e.memoizedState = si,
    o) : (i = xi(a, e, o.children, i),
    e.memoizedState = null,
    i)
}
function ui(a, e, i, o) {
    var s = a.mode
      , c = a.child;
    return e = {
        mode: "hidden",
        children: e
    },
    (s & 2) === 0 && c !== null ? (c.childLanes = 0,
    c.pendingProps = e) : c = vi(e, s, 0, null),
    i = Xg(i, s, o, null),
    c.return = a,
    i.return = a,
    c.sibling = i,
    a.child = c,
    i
}
function xi(a, e, i, o) {
    var s = a.child;
    return a = s.sibling,
    i = Tg(s, {
        mode: "visible",
        children: i
    }),
    (e.mode & 2) === 0 && (i.lanes = o),
    i.return = e,
    i.sibling = null,
    a !== null && (a.nextEffect = null,
    a.flags = 8,
    e.firstEffect = e.lastEffect = a),
    e.child = i
}
function wi(a, e, i, o, s) {
    var c = e.mode
      , d = a.child;
    a = d.sibling;
    var _ = {
        mode: "hidden",
        children: i
    };
    return (c & 2) === 0 && e.child !== d ? (i = e.child,
    i.childLanes = 0,
    i.pendingProps = _,
    d = i.lastEffect,
    d !== null ? (e.firstEffect = i.firstEffect,
    e.lastEffect = d,
    d.nextEffect = null) : e.firstEffect = e.lastEffect = null) : i = Tg(d, _),
    a !== null ? o = Tg(a, o) : (o = Xg(o, c, s, null),
    o.flags |= 2),
    o.return = e,
    i.return = e,
    i.sibling = o,
    e.child = i,
    o
}
function yi(a, e) {
    a.lanes |= e;
    var i = a.alternate;
    i !== null && (i.lanes |= e),
    sg(a.return, e)
}
function zi(a, e, i, o, s, c) {
    var d = a.memoizedState;
    d === null ? a.memoizedState = {
        isBackwards: e,
        rendering: null,
        renderingStartTime: 0,
        last: o,
        tail: i,
        tailMode: s,
        lastEffect: c
    } : (d.isBackwards = e,
    d.rendering = null,
    d.renderingStartTime = 0,
    d.last = o,
    d.tail = i,
    d.tailMode = s,
    d.lastEffect = c)
}
function Ai(a, e, i) {
    var o = e.pendingProps
      , s = o.revealOrder
      , c = o.tail;
    if (fi(a, e, o.children, i),
    o = P.current,
    (o & 2) !== 0)
        o = o & 1 | 2,
        e.flags |= 64;
    else {
        if (a !== null && (a.flags & 64) !== 0)
            e: for (a = e.child; a !== null; ) {
                if (a.tag === 13)
                    a.memoizedState !== null && yi(a, i);
                else if (a.tag === 19)
                    yi(a, i);
                else if (a.child !== null) {
                    a.child.return = a,
                    a = a.child;
                    continue
                }
                if (a === e)
                    break e;
                for (; a.sibling === null; ) {
                    if (a.return === null || a.return === e)
                        break e;
                    a = a.return
                }
                a.sibling.return = a.return,
                a = a.sibling
            }
        o &= 1
    }
    if (I(P, o),
    (e.mode & 2) === 0)
        e.memoizedState = null;
    else
        switch (s) {
        case "forwards":
            for (i = e.child,
            s = null; i !== null; )
                a = i.alternate,
                a !== null && ih(a) === null && (s = i),
                i = i.sibling;
            i = s,
            i === null ? (s = e.child,
            e.child = null) : (s = i.sibling,
            i.sibling = null),
            zi(e, !1, s, i, c, e.lastEffect);
            break;
        case "backwards":
            for (i = null,
            s = e.child,
            e.child = null; s !== null; ) {
                if (a = s.alternate,
                a !== null && ih(a) === null) {
                    e.child = s;
                    break
                }
                a = s.sibling,
                s.sibling = i,
                i = s,
                s = a
            }
            zi(e, !0, i, null, c, e.lastEffect);
            break;
        case "together":
            zi(e, !1, null, null, void 0, e.lastEffect);
            break;
        default:
            e.memoizedState = null
        }
    return e.child
}
function hi(a, e, i) {
    if (a !== null && (e.dependencies = a.dependencies),
    Dg |= e.lanes,
    (i & e.childLanes) !== 0) {
        if (a !== null && e.child !== a.child)
            throw Error(y(153));
        if (e.child !== null) {
            for (a = e.child,
            i = Tg(a, a.pendingProps),
            e.child = i,
            i.return = e; a.sibling !== null; )
                a = a.sibling,
                i = i.sibling = Tg(a, a.pendingProps),
                i.return = e;
            i.sibling = null
        }
        return e.child
    }
    return null
}
var Bi, Ci, Di, Ei;
Bi = function(a, e) {
    for (var i = e.child; i !== null; ) {
        if (i.tag === 5 || i.tag === 6)
            a.appendChild(i.stateNode);
        else if (i.tag !== 4 && i.child !== null) {
            i.child.return = i,
            i = i.child;
            continue
        }
        if (i === e)
            break;
        for (; i.sibling === null; ) {
            if (i.return === null || i.return === e)
                return;
            i = i.return
        }
        i.sibling.return = i.return,
        i = i.sibling
    }
}
;
Ci = function() {}
;
Di = function(a, e, i, o) {
    var s = a.memoizedProps;
    if (s !== o) {
        a = e.stateNode,
        dh(ah.current);
        var c = null;
        switch (i) {
        case "input":
            s = Ya(a, s),
            o = Ya(a, o),
            c = [];
            break;
        case "option":
            s = eb(a, s),
            o = eb(a, o),
            c = [];
            break;
        case "select":
            s = m$1({}, s, {
                value: void 0
            }),
            o = m$1({}, o, {
                value: void 0
            }),
            c = [];
            break;
        case "textarea":
            s = gb(a, s),
            o = gb(a, o),
            c = [];
            break;
        default:
            typeof s.onClick != "function" && typeof o.onClick == "function" && (a.onclick = jf)
        }
        vb(i, o);
        var d;
        i = null;
        for (k in s)
            if (!o.hasOwnProperty(k) && s.hasOwnProperty(k) && s[k] != null)
                if (k === "style") {
                    var _ = s[k];
                    for (d in _)
                        _.hasOwnProperty(d) && (i || (i = {}),
                        i[d] = "")
                } else
                    k !== "dangerouslySetInnerHTML" && k !== "children" && k !== "suppressContentEditableWarning" && k !== "suppressHydrationWarning" && k !== "autoFocus" && (ca.hasOwnProperty(k) ? c || (c = []) : (c = c || []).push(k, null));
        for (k in o) {
            var b = o[k];
            if (_ = s != null ? s[k] : void 0,
            o.hasOwnProperty(k) && b !== _ && (b != null || _ != null))
                if (k === "style")
                    if (_) {
                        for (d in _)
                            !_.hasOwnProperty(d) || b && b.hasOwnProperty(d) || (i || (i = {}),
                            i[d] = "");
                        for (d in b)
                            b.hasOwnProperty(d) && _[d] !== b[d] && (i || (i = {}),
                            i[d] = b[d])
                    } else
                        i || (c || (c = []),
                        c.push(k, i)),
                        i = b;
                else
                    k === "dangerouslySetInnerHTML" ? (b = b ? b.__html : void 0,
                    _ = _ ? _.__html : void 0,
                    b != null && _ !== b && (c = c || []).push(k, b)) : k === "children" ? typeof b != "string" && typeof b != "number" || (c = c || []).push(k, "" + b) : k !== "suppressContentEditableWarning" && k !== "suppressHydrationWarning" && (ca.hasOwnProperty(k) ? (b != null && k === "onScroll" && G("scroll", a),
                    c || _ === b || (c = [])) : typeof b == "object" && b !== null && b.$$typeof === Ga ? b.toString() : (c = c || []).push(k, b))
        }
        i && (c = c || []).push("style", i);
        var k = c;
        (e.updateQueue = k) && (e.flags |= 4)
    }
}
;
Ei = function(a, e, i, o) {
    i !== o && (e.flags |= 4)
}
;
function Fi(a, e) {
    if (!lh)
        switch (a.tailMode) {
        case "hidden":
            e = a.tail;
            for (var i = null; e !== null; )
                e.alternate !== null && (i = e),
                e = e.sibling;
            i === null ? a.tail = null : i.sibling = null;
            break;
        case "collapsed":
            i = a.tail;
            for (var o = null; i !== null; )
                i.alternate !== null && (o = i),
                i = i.sibling;
            o === null ? e || a.tail === null ? a.tail = null : a.tail.sibling = null : o.sibling = null
        }
}
function Gi(a, e, i) {
    var o = e.pendingProps;
    switch (e.tag) {
    case 2:
    case 16:
    case 15:
    case 0:
    case 11:
    case 7:
    case 8:
    case 12:
    case 9:
    case 14:
        return null;
    case 1:
        return Ff(e.type) && Gf(),
        null;
    case 3:
        return fh(),
        H(N),
        H(M),
        uh(),
        o = e.stateNode,
        o.pendingContext && (o.context = o.pendingContext,
        o.pendingContext = null),
        (a === null || a.child === null) && (rh(e) ? e.flags |= 4 : o.hydrate || (e.flags |= 256)),
        Ci(e),
        null;
    case 5:
        hh(e);
        var s = dh(ch.current);
        if (i = e.type,
        a !== null && e.stateNode != null)
            Di(a, e, i, o, s),
            a.ref !== e.ref && (e.flags |= 128);
        else {
            if (!o) {
                if (e.stateNode === null)
                    throw Error(y(166));
                return null
            }
            if (a = dh(ah.current),
            rh(e)) {
                o = e.stateNode,
                i = e.type;
                var c = e.memoizedProps;
                switch (o[wf] = e,
                o[xf] = c,
                i) {
                case "dialog":
                    G("cancel", o),
                    G("close", o);
                    break;
                case "iframe":
                case "object":
                case "embed":
                    G("load", o);
                    break;
                case "video":
                case "audio":
                    for (a = 0; a < Xe.length; a++)
                        G(Xe[a], o);
                    break;
                case "source":
                    G("error", o);
                    break;
                case "img":
                case "image":
                case "link":
                    G("error", o),
                    G("load", o);
                    break;
                case "details":
                    G("toggle", o);
                    break;
                case "input":
                    Za(o, c),
                    G("invalid", o);
                    break;
                case "select":
                    o._wrapperState = {
                        wasMultiple: !!c.multiple
                    },
                    G("invalid", o);
                    break;
                case "textarea":
                    hb(o, c),
                    G("invalid", o)
                }
                vb(i, c),
                a = null;
                for (var d in c)
                    c.hasOwnProperty(d) && (s = c[d],
                    d === "children" ? typeof s == "string" ? o.textContent !== s && (a = ["children", s]) : typeof s == "number" && o.textContent !== "" + s && (a = ["children", "" + s]) : ca.hasOwnProperty(d) && s != null && d === "onScroll" && G("scroll", o));
                switch (i) {
                case "input":
                    Va(o),
                    cb(o, c, !0);
                    break;
                case "textarea":
                    Va(o),
                    jb(o);
                    break;
                case "select":
                case "option":
                    break;
                default:
                    typeof c.onClick == "function" && (o.onclick = jf)
                }
                o = a,
                e.updateQueue = o,
                o !== null && (e.flags |= 4)
            } else {
                switch (d = s.nodeType === 9 ? s : s.ownerDocument,
                a === kb.html && (a = lb(i)),
                a === kb.html ? i === "script" ? (a = d.createElement("div"),
                a.innerHTML = "<script><\/script>",
                a = a.removeChild(a.firstChild)) : typeof o.is == "string" ? a = d.createElement(i, {
                    is: o.is
                }) : (a = d.createElement(i),
                i === "select" && (d = a,
                o.multiple ? d.multiple = !0 : o.size && (d.size = o.size))) : a = d.createElementNS(a, i),
                a[wf] = e,
                a[xf] = o,
                Bi(a, e, !1, !1),
                e.stateNode = a,
                d = wb(i, o),
                i) {
                case "dialog":
                    G("cancel", a),
                    G("close", a),
                    s = o;
                    break;
                case "iframe":
                case "object":
                case "embed":
                    G("load", a),
                    s = o;
                    break;
                case "video":
                case "audio":
                    for (s = 0; s < Xe.length; s++)
                        G(Xe[s], a);
                    s = o;
                    break;
                case "source":
                    G("error", a),
                    s = o;
                    break;
                case "img":
                case "image":
                case "link":
                    G("error", a),
                    G("load", a),
                    s = o;
                    break;
                case "details":
                    G("toggle", a),
                    s = o;
                    break;
                case "input":
                    Za(a, o),
                    s = Ya(a, o),
                    G("invalid", a);
                    break;
                case "option":
                    s = eb(a, o);
                    break;
                case "select":
                    a._wrapperState = {
                        wasMultiple: !!o.multiple
                    },
                    s = m$1({}, o, {
                        value: void 0
                    }),
                    G("invalid", a);
                    break;
                case "textarea":
                    hb(a, o),
                    s = gb(a, o),
                    G("invalid", a);
                    break;
                default:
                    s = o
                }
                vb(i, s);
                var _ = s;
                for (c in _)
                    if (_.hasOwnProperty(c)) {
                        var b = _[c];
                        c === "style" ? tb(a, b) : c === "dangerouslySetInnerHTML" ? (b = b ? b.__html : void 0,
                        b != null && ob(a, b)) : c === "children" ? typeof b == "string" ? (i !== "textarea" || b !== "") && pb(a, b) : typeof b == "number" && pb(a, "" + b) : c !== "suppressContentEditableWarning" && c !== "suppressHydrationWarning" && c !== "autoFocus" && (ca.hasOwnProperty(c) ? b != null && c === "onScroll" && G("scroll", a) : b != null && qa(a, c, b, d))
                    }
                switch (i) {
                case "input":
                    Va(a),
                    cb(a, o, !1);
                    break;
                case "textarea":
                    Va(a),
                    jb(a);
                    break;
                case "option":
                    o.value != null && a.setAttribute("value", "" + Sa(o.value));
                    break;
                case "select":
                    a.multiple = !!o.multiple,
                    c = o.value,
                    c != null ? fb(a, !!o.multiple, c, !1) : o.defaultValue != null && fb(a, !!o.multiple, o.defaultValue, !0);
                    break;
                default:
                    typeof s.onClick == "function" && (a.onclick = jf)
                }
                mf(i, o) && (e.flags |= 4)
            }
            e.ref !== null && (e.flags |= 128)
        }
        return null;
    case 6:
        if (a && e.stateNode != null)
            Ei(a, e, a.memoizedProps, o);
        else {
            if (typeof o != "string" && e.stateNode === null)
                throw Error(y(166));
            i = dh(ch.current),
            dh(ah.current),
            rh(e) ? (o = e.stateNode,
            i = e.memoizedProps,
            o[wf] = e,
            o.nodeValue !== i && (e.flags |= 4)) : (o = (i.nodeType === 9 ? i : i.ownerDocument).createTextNode(o),
            o[wf] = e,
            e.stateNode = o)
        }
        return null;
    case 13:
        return H(P),
        o = e.memoizedState,
        (e.flags & 64) !== 0 ? (e.lanes = i,
        e) : (o = o !== null,
        i = !1,
        a === null ? e.memoizedProps.fallback !== void 0 && rh(e) : i = a.memoizedState !== null,
        o && !i && (e.mode & 2) !== 0 && (a === null && e.memoizedProps.unstable_avoidThisFallback !== !0 || (P.current & 1) !== 0 ? V === 0 && (V = 3) : ((V === 0 || V === 3) && (V = 4),
        U === null || (Dg & 134217727) === 0 && (Hi & 134217727) === 0 || Ii(U, W))),
        (o || i) && (e.flags |= 4),
        null);
    case 4:
        return fh(),
        Ci(e),
        a === null && cf(e.stateNode.containerInfo),
        null;
    case 10:
        return rg(e),
        null;
    case 17:
        return Ff(e.type) && Gf(),
        null;
    case 19:
        if (H(P),
        o = e.memoizedState,
        o === null)
            return null;
        if (c = (e.flags & 64) !== 0,
        d = o.rendering,
        d === null)
            if (c)
                Fi(o, !1);
            else {
                if (V !== 0 || a !== null && (a.flags & 64) !== 0)
                    for (a = e.child; a !== null; ) {
                        if (d = ih(a),
                        d !== null) {
                            for (e.flags |= 64,
                            Fi(o, !1),
                            c = d.updateQueue,
                            c !== null && (e.updateQueue = c,
                            e.flags |= 4),
                            o.lastEffect === null && (e.firstEffect = null),
                            e.lastEffect = o.lastEffect,
                            o = i,
                            i = e.child; i !== null; )
                                c = i,
                                a = o,
                                c.flags &= 2,
                                c.nextEffect = null,
                                c.firstEffect = null,
                                c.lastEffect = null,
                                d = c.alternate,
                                d === null ? (c.childLanes = 0,
                                c.lanes = a,
                                c.child = null,
                                c.memoizedProps = null,
                                c.memoizedState = null,
                                c.updateQueue = null,
                                c.dependencies = null,
                                c.stateNode = null) : (c.childLanes = d.childLanes,
                                c.lanes = d.lanes,
                                c.child = d.child,
                                c.memoizedProps = d.memoizedProps,
                                c.memoizedState = d.memoizedState,
                                c.updateQueue = d.updateQueue,
                                c.type = d.type,
                                a = d.dependencies,
                                c.dependencies = a === null ? null : {
                                    lanes: a.lanes,
                                    firstContext: a.firstContext
                                }),
                                i = i.sibling;
                            return I(P, P.current & 1 | 2),
                            e.child
                        }
                        a = a.sibling
                    }
                o.tail !== null && O() > Ji && (e.flags |= 64,
                c = !0,
                Fi(o, !1),
                e.lanes = 33554432)
            }
        else {
            if (!c)
                if (a = ih(d),
                a !== null) {
                    if (e.flags |= 64,
                    c = !0,
                    i = a.updateQueue,
                    i !== null && (e.updateQueue = i,
                    e.flags |= 4),
                    Fi(o, !0),
                    o.tail === null && o.tailMode === "hidden" && !d.alternate && !lh)
                        return e = e.lastEffect = o.lastEffect,
                        e !== null && (e.nextEffect = null),
                        null
                } else
                    2 * O() - o.renderingStartTime > Ji && i !== 1073741824 && (e.flags |= 64,
                    c = !0,
                    Fi(o, !1),
                    e.lanes = 33554432);
            o.isBackwards ? (d.sibling = e.child,
            e.child = d) : (i = o.last,
            i !== null ? i.sibling = d : e.child = d,
            o.last = d)
        }
        return o.tail !== null ? (i = o.tail,
        o.rendering = i,
        o.tail = i.sibling,
        o.lastEffect = e.lastEffect,
        o.renderingStartTime = O(),
        i.sibling = null,
        e = P.current,
        I(P, c ? e & 1 | 2 : e & 1),
        i) : null;
    case 23:
    case 24:
        return Ki(),
        a !== null && a.memoizedState !== null != (e.memoizedState !== null) && o.mode !== "unstable-defer-without-hiding" && (e.flags |= 4),
        null
    }
    throw Error(y(156, e.tag))
}
function Li(a) {
    switch (a.tag) {
    case 1:
        Ff(a.type) && Gf();
        var e = a.flags;
        return e & 4096 ? (a.flags = e & -4097 | 64,
        a) : null;
    case 3:
        if (fh(),
        H(N),
        H(M),
        uh(),
        e = a.flags,
        (e & 64) !== 0)
            throw Error(y(285));
        return a.flags = e & -4097 | 64,
        a;
    case 5:
        return hh(a),
        null;
    case 13:
        return H(P),
        e = a.flags,
        e & 4096 ? (a.flags = e & -4097 | 64,
        a) : null;
    case 19:
        return H(P),
        null;
    case 4:
        return fh(),
        null;
    case 10:
        return rg(a),
        null;
    case 23:
    case 24:
        return Ki(),
        null;
    default:
        return null
    }
}
function Mi(a, e) {
    try {
        var i = ""
          , o = e;
        do
            i += Qa(o),
            o = o.return;
        while (o);
        var s = i
    } catch (c) {
        s = `
Error generating stack: ` + c.message + `
` + c.stack
    }
    return {
        value: a,
        source: e,
        stack: s
    }
}
function Ni(a, e) {
    try {
        console.error(e.value)
    } catch (i) {
        setTimeout(function() {
            throw i
        })
    }
}
var Oi = typeof WeakMap == "function" ? WeakMap : Map;
function Pi(a, e, i) {
    i = zg(-1, i),
    i.tag = 3,
    i.payload = {
        element: null
    };
    var o = e.value;
    return i.callback = function() {
        Qi || (Qi = !0,
        Ri = o),
        Ni(a, e)
    }
    ,
    i
}
function Si(a, e, i) {
    i = zg(-1, i),
    i.tag = 3;
    var o = a.type.getDerivedStateFromError;
    if (typeof o == "function") {
        var s = e.value;
        i.payload = function() {
            return Ni(a, e),
            o(s)
        }
    }
    var c = a.stateNode;
    return c !== null && typeof c.componentDidCatch == "function" && (i.callback = function() {
        typeof o != "function" && (Ti === null ? Ti = new Set([this]) : Ti.add(this),
        Ni(a, e));
        var d = e.stack;
        this.componentDidCatch(e.value, {
            componentStack: d !== null ? d : ""
        })
    }
    ),
    i
}
var Ui = typeof WeakSet == "function" ? WeakSet : Set;
function Vi(a) {
    var e = a.ref;
    if (e !== null)
        if (typeof e == "function")
            try {
                e(null)
            } catch (i) {
                Wi(a, i)
            }
        else
            e.current = null
}
function Xi(a, e) {
    switch (e.tag) {
    case 0:
    case 11:
    case 15:
    case 22:
        return;
    case 1:
        if (e.flags & 256 && a !== null) {
            var i = a.memoizedProps
              , o = a.memoizedState;
            a = e.stateNode,
            e = a.getSnapshotBeforeUpdate(e.elementType === e.type ? i : lg(e.type, i), o),
            a.__reactInternalSnapshotBeforeUpdate = e
        }
        return;
    case 3:
        e.flags & 256 && qf(e.stateNode.containerInfo);
        return;
    case 5:
    case 6:
    case 4:
    case 17:
        return
    }
    throw Error(y(163))
}
function Yi(a, e, i) {
    switch (i.tag) {
    case 0:
    case 11:
    case 15:
    case 22:
        if (e = i.updateQueue,
        e = e !== null ? e.lastEffect : null,
        e !== null) {
            a = e = e.next;
            do {
                if ((a.tag & 3) === 3) {
                    var o = a.create;
                    a.destroy = o()
                }
                a = a.next
            } while (a !== e)
        }
        if (e = i.updateQueue,
        e = e !== null ? e.lastEffect : null,
        e !== null) {
            a = e = e.next;
            do {
                var s = a;
                o = s.next,
                s = s.tag,
                (s & 4) !== 0 && (s & 1) !== 0 && (Zi(i, a),
                $i(i, a)),
                a = o
            } while (a !== e)
        }
        return;
    case 1:
        a = i.stateNode,
        i.flags & 4 && (e === null ? a.componentDidMount() : (o = i.elementType === i.type ? e.memoizedProps : lg(i.type, e.memoizedProps),
        a.componentDidUpdate(o, e.memoizedState, a.__reactInternalSnapshotBeforeUpdate))),
        e = i.updateQueue,
        e !== null && Eg(i, e, a);
        return;
    case 3:
        if (e = i.updateQueue,
        e !== null) {
            if (a = null,
            i.child !== null)
                switch (i.child.tag) {
                case 5:
                    a = i.child.stateNode;
                    break;
                case 1:
                    a = i.child.stateNode
                }
            Eg(i, e, a)
        }
        return;
    case 5:
        a = i.stateNode,
        e === null && i.flags & 4 && mf(i.type, i.memoizedProps) && a.focus();
        return;
    case 6:
        return;
    case 4:
        return;
    case 12:
        return;
    case 13:
        i.memoizedState === null && (i = i.alternate,
        i !== null && (i = i.memoizedState,
        i !== null && (i = i.dehydrated,
        i !== null && Cc(i))));
        return;
    case 19:
    case 17:
    case 20:
    case 21:
    case 23:
    case 24:
        return
    }
    throw Error(y(163))
}
function aj(a, e) {
    for (var i = a; ; ) {
        if (i.tag === 5) {
            var o = i.stateNode;
            if (e)
                o = o.style,
                typeof o.setProperty == "function" ? o.setProperty("display", "none", "important") : o.display = "none";
            else {
                o = i.stateNode;
                var s = i.memoizedProps.style;
                s = s != null && s.hasOwnProperty("display") ? s.display : null,
                o.style.display = sb("display", s)
            }
        } else if (i.tag === 6)
            i.stateNode.nodeValue = e ? "" : i.memoizedProps;
        else if ((i.tag !== 23 && i.tag !== 24 || i.memoizedState === null || i === a) && i.child !== null) {
            i.child.return = i,
            i = i.child;
            continue
        }
        if (i === a)
            break;
        for (; i.sibling === null; ) {
            if (i.return === null || i.return === a)
                return;
            i = i.return
        }
        i.sibling.return = i.return,
        i = i.sibling
    }
}
function bj(a, e) {
    if (Mf && typeof Mf.onCommitFiberUnmount == "function")
        try {
            Mf.onCommitFiberUnmount(Lf, e)
        } catch {}
    switch (e.tag) {
    case 0:
    case 11:
    case 14:
    case 15:
    case 22:
        if (a = e.updateQueue,
        a !== null && (a = a.lastEffect,
        a !== null)) {
            var i = a = a.next;
            do {
                var o = i
                  , s = o.destroy;
                if (o = o.tag,
                s !== void 0)
                    if ((o & 4) !== 0)
                        Zi(e, i);
                    else {
                        o = e;
                        try {
                            s()
                        } catch (c) {
                            Wi(o, c)
                        }
                    }
                i = i.next
            } while (i !== a)
        }
        break;
    case 1:
        if (Vi(e),
        a = e.stateNode,
        typeof a.componentWillUnmount == "function")
            try {
                a.props = e.memoizedProps,
                a.state = e.memoizedState,
                a.componentWillUnmount()
            } catch (c) {
                Wi(e, c)
            }
        break;
    case 5:
        Vi(e);
        break;
    case 4:
        cj(a, e)
    }
}
function dj(a) {
    a.alternate = null,
    a.child = null,
    a.dependencies = null,
    a.firstEffect = null,
    a.lastEffect = null,
    a.memoizedProps = null,
    a.memoizedState = null,
    a.pendingProps = null,
    a.return = null,
    a.updateQueue = null
}
function ej(a) {
    return a.tag === 5 || a.tag === 3 || a.tag === 4
}
function fj(a) {
    e: {
        for (var e = a.return; e !== null; ) {
            if (ej(e))
                break e;
            e = e.return
        }
        throw Error(y(160))
    }
    var i = e;
    switch (e = i.stateNode,
    i.tag) {
    case 5:
        var o = !1;
        break;
    case 3:
        e = e.containerInfo,
        o = !0;
        break;
    case 4:
        e = e.containerInfo,
        o = !0;
        break;
    default:
        throw Error(y(161))
    }
    i.flags & 16 && (pb(e, ""),
    i.flags &= -17);
    e: t: for (i = a; ; ) {
        for (; i.sibling === null; ) {
            if (i.return === null || ej(i.return)) {
                i = null;
                break e
            }
            i = i.return
        }
        for (i.sibling.return = i.return,
        i = i.sibling; i.tag !== 5 && i.tag !== 6 && i.tag !== 18; ) {
            if (i.flags & 2 || i.child === null || i.tag === 4)
                continue t;
            i.child.return = i,
            i = i.child
        }
        if (!(i.flags & 2)) {
            i = i.stateNode;
            break e
        }
    }
    o ? gj(a, i, e) : hj(a, i, e)
}
function gj(a, e, i) {
    var o = a.tag
      , s = o === 5 || o === 6;
    if (s)
        a = s ? a.stateNode : a.stateNode.instance,
        e ? i.nodeType === 8 ? i.parentNode.insertBefore(a, e) : i.insertBefore(a, e) : (i.nodeType === 8 ? (e = i.parentNode,
        e.insertBefore(a, i)) : (e = i,
        e.appendChild(a)),
        i = i._reactRootContainer,
        i != null || e.onclick !== null || (e.onclick = jf));
    else if (o !== 4 && (a = a.child,
    a !== null))
        for (gj(a, e, i),
        a = a.sibling; a !== null; )
            gj(a, e, i),
            a = a.sibling
}
function hj(a, e, i) {
    var o = a.tag
      , s = o === 5 || o === 6;
    if (s)
        a = s ? a.stateNode : a.stateNode.instance,
        e ? i.insertBefore(a, e) : i.appendChild(a);
    else if (o !== 4 && (a = a.child,
    a !== null))
        for (hj(a, e, i),
        a = a.sibling; a !== null; )
            hj(a, e, i),
            a = a.sibling
}
function cj(a, e) {
    for (var i = e, o = !1, s, c; ; ) {
        if (!o) {
            o = i.return;
            e: for (; ; ) {
                if (o === null)
                    throw Error(y(160));
                switch (s = o.stateNode,
                o.tag) {
                case 5:
                    c = !1;
                    break e;
                case 3:
                    s = s.containerInfo,
                    c = !0;
                    break e;
                case 4:
                    s = s.containerInfo,
                    c = !0;
                    break e
                }
                o = o.return
            }
            o = !0
        }
        if (i.tag === 5 || i.tag === 6) {
            e: for (var d = a, _ = i, b = _; ; )
                if (bj(d, b),
                b.child !== null && b.tag !== 4)
                    b.child.return = b,
                    b = b.child;
                else {
                    if (b === _)
                        break e;
                    for (; b.sibling === null; ) {
                        if (b.return === null || b.return === _)
                            break e;
                        b = b.return
                    }
                    b.sibling.return = b.return,
                    b = b.sibling
                }
            c ? (d = s,
            _ = i.stateNode,
            d.nodeType === 8 ? d.parentNode.removeChild(_) : d.removeChild(_)) : s.removeChild(i.stateNode)
        } else if (i.tag === 4) {
            if (i.child !== null) {
                s = i.stateNode.containerInfo,
                c = !0,
                i.child.return = i,
                i = i.child;
                continue
            }
        } else if (bj(a, i),
        i.child !== null) {
            i.child.return = i,
            i = i.child;
            continue
        }
        if (i === e)
            break;
        for (; i.sibling === null; ) {
            if (i.return === null || i.return === e)
                return;
            i = i.return,
            i.tag === 4 && (o = !1)
        }
        i.sibling.return = i.return,
        i = i.sibling
    }
}
function ij(a, e) {
    switch (e.tag) {
    case 0:
    case 11:
    case 14:
    case 15:
    case 22:
        var i = e.updateQueue;
        if (i = i !== null ? i.lastEffect : null,
        i !== null) {
            var o = i = i.next;
            do
                (o.tag & 3) === 3 && (a = o.destroy,
                o.destroy = void 0,
                a !== void 0 && a()),
                o = o.next;
            while (o !== i)
        }
        return;
    case 1:
        return;
    case 5:
        if (i = e.stateNode,
        i != null) {
            o = e.memoizedProps;
            var s = a !== null ? a.memoizedProps : o;
            a = e.type;
            var c = e.updateQueue;
            if (e.updateQueue = null,
            c !== null) {
                for (i[xf] = o,
                a === "input" && o.type === "radio" && o.name != null && $a(i, o),
                wb(a, s),
                e = wb(a, o),
                s = 0; s < c.length; s += 2) {
                    var d = c[s]
                      , _ = c[s + 1];
                    d === "style" ? tb(i, _) : d === "dangerouslySetInnerHTML" ? ob(i, _) : d === "children" ? pb(i, _) : qa(i, d, _, e)
                }
                switch (a) {
                case "input":
                    ab(i, o);
                    break;
                case "textarea":
                    ib(i, o);
                    break;
                case "select":
                    a = i._wrapperState.wasMultiple,
                    i._wrapperState.wasMultiple = !!o.multiple,
                    c = o.value,
                    c != null ? fb(i, !!o.multiple, c, !1) : a !== !!o.multiple && (o.defaultValue != null ? fb(i, !!o.multiple, o.defaultValue, !0) : fb(i, !!o.multiple, o.multiple ? [] : "", !1))
                }
            }
        }
        return;
    case 6:
        if (e.stateNode === null)
            throw Error(y(162));
        e.stateNode.nodeValue = e.memoizedProps;
        return;
    case 3:
        i = e.stateNode,
        i.hydrate && (i.hydrate = !1,
        Cc(i.containerInfo));
        return;
    case 12:
        return;
    case 13:
        e.memoizedState !== null && (jj = O(),
        aj(e.child, !0)),
        kj(e);
        return;
    case 19:
        kj(e);
        return;
    case 17:
        return;
    case 23:
    case 24:
        aj(e, e.memoizedState !== null);
        return
    }
    throw Error(y(163))
}
function kj(a) {
    var e = a.updateQueue;
    if (e !== null) {
        a.updateQueue = null;
        var i = a.stateNode;
        i === null && (i = a.stateNode = new Ui),
        e.forEach(function(o) {
            var s = lj.bind(null, a, o);
            i.has(o) || (i.add(o),
            o.then(s, s))
        })
    }
}
function mj(a, e) {
    return a !== null && (a = a.memoizedState,
    a === null || a.dehydrated !== null) ? (e = e.memoizedState,
    e !== null && e.dehydrated === null) : !1
}
var nj = Math.ceil
  , oj = ra.ReactCurrentDispatcher
  , pj = ra.ReactCurrentOwner
  , X = 0
  , U = null
  , Y = null
  , W = 0
  , qj = 0
  , rj = Bf(0)
  , V = 0
  , sj = null
  , tj = 0
  , Dg = 0
  , Hi = 0
  , uj = 0
  , vj = null
  , jj = 0
  , Ji = 1 / 0;
function wj() {
    Ji = O() + 500
}
var Z = null
  , Qi = !1
  , Ri = null
  , Ti = null
  , xj = !1
  , yj = null
  , zj = 90
  , Aj = []
  , Bj = []
  , Cj = null
  , Dj = 0
  , Ej = null
  , Fj = -1
  , Gj = 0
  , Hj = 0
  , Ij = null
  , Jj = !1;
function Hg() {
    return (X & 48) !== 0 ? O() : Fj !== -1 ? Fj : Fj = O()
}
function Ig(a) {
    if (a = a.mode,
    (a & 2) === 0)
        return 1;
    if ((a & 4) === 0)
        return eg() === 99 ? 1 : 2;
    if (Gj === 0 && (Gj = tj),
    kg.transition !== 0) {
        Hj !== 0 && (Hj = vj !== null ? vj.pendingLanes : 0),
        a = Gj;
        var e = 4186112 & ~Hj;
        return e &= -e,
        e === 0 && (a = 4186112 & ~a,
        e = a & -a,
        e === 0 && (e = 8192)),
        e
    }
    return a = eg(),
    (X & 4) !== 0 && a === 98 ? a = Xc(12, Gj) : (a = Sc(a),
    a = Xc(a, Gj)),
    a
}
function Jg(a, e, i) {
    if (50 < Dj)
        throw Dj = 0,
        Ej = null,
        Error(y(185));
    if (a = Kj(a, e),
    a === null)
        return null;
    $c(a, e, i),
    a === U && (Hi |= e,
    V === 4 && Ii(a, W));
    var o = eg();
    e === 1 ? (X & 8) !== 0 && (X & 48) === 0 ? Lj(a) : (Mj(a, i),
    X === 0 && (wj(),
    ig())) : ((X & 4) === 0 || o !== 98 && o !== 99 || (Cj === null ? Cj = new Set([a]) : Cj.add(a)),
    Mj(a, i)),
    vj = a
}
function Kj(a, e) {
    a.lanes |= e;
    var i = a.alternate;
    for (i !== null && (i.lanes |= e),
    i = a,
    a = a.return; a !== null; )
        a.childLanes |= e,
        i = a.alternate,
        i !== null && (i.childLanes |= e),
        i = a,
        a = a.return;
    return i.tag === 3 ? i.stateNode : null
}
function Mj(a, e) {
    for (var i = a.callbackNode, o = a.suspendedLanes, s = a.pingedLanes, c = a.expirationTimes, d = a.pendingLanes; 0 < d; ) {
        var _ = 31 - Vc(d)
          , b = 1 << _
          , k = c[_];
        if (k === -1) {
            if ((b & o) === 0 || (b & s) !== 0) {
                k = e,
                Rc(b);
                var j = F;
                c[_] = 10 <= j ? k + 250 : 6 <= j ? k + 5e3 : -1
            }
        } else
            k <= e && (a.expiredLanes |= b);
        d &= ~b
    }
    if (o = Uc(a, a === U ? W : 0),
    e = F,
    o === 0)
        i !== null && (i !== Zf && Pf(i),
        a.callbackNode = null,
        a.callbackPriority = 0);
    else {
        if (i !== null) {
            if (a.callbackPriority === e)
                return;
            i !== Zf && Pf(i)
        }
        e === 15 ? (i = Lj.bind(null, a),
        ag === null ? (ag = [i],
        bg = Of(Uf, jg)) : ag.push(i),
        i = Zf) : e === 14 ? i = hg(99, Lj.bind(null, a)) : (i = Tc(e),
        i = hg(i, Nj.bind(null, a))),
        a.callbackPriority = e,
        a.callbackNode = i
    }
}
function Nj(a) {
    if (Fj = -1,
    Hj = Gj = 0,
    (X & 48) !== 0)
        throw Error(y(327));
    var e = a.callbackNode;
    if (Oj() && a.callbackNode !== e)
        return null;
    var i = Uc(a, a === U ? W : 0);
    if (i === 0)
        return null;
    var o = i
      , s = X;
    X |= 16;
    var c = Pj();
    (U !== a || W !== o) && (wj(),
    Qj(a, o));
    do
        try {
            Rj();
            break
        } catch (_) {
            Sj(a, _)
        }
    while (1);
    if (qg(),
    oj.current = c,
    X = s,
    Y !== null ? o = 0 : (U = null,
    W = 0,
    o = V),
    (tj & Hi) !== 0)
        Qj(a, 0);
    else if (o !== 0) {
        if (o === 2 && (X |= 64,
        a.hydrate && (a.hydrate = !1,
        qf(a.containerInfo)),
        i = Wc(a),
        i !== 0 && (o = Tj(a, i))),
        o === 1)
            throw e = sj,
            Qj(a, 0),
            Ii(a, i),
            Mj(a, O()),
            e;
        switch (a.finishedWork = a.current.alternate,
        a.finishedLanes = i,
        o) {
        case 0:
        case 1:
            throw Error(y(345));
        case 2:
            Uj(a);
            break;
        case 3:
            if (Ii(a, i),
            (i & 62914560) === i && (o = jj + 500 - O(),
            10 < o)) {
                if (Uc(a, 0) !== 0)
                    break;
                if (s = a.suspendedLanes,
                (s & i) !== i) {
                    Hg(),
                    a.pingedLanes |= a.suspendedLanes & s;
                    break
                }
                a.timeoutHandle = of(Uj.bind(null, a), o);
                break
            }
            Uj(a);
            break;
        case 4:
            if (Ii(a, i),
            (i & 4186112) === i)
                break;
            for (o = a.eventTimes,
            s = -1; 0 < i; ) {
                var d = 31 - Vc(i);
                c = 1 << d,
                d = o[d],
                d > s && (s = d),
                i &= ~c
            }
            if (i = s,
            i = O() - i,
            i = (120 > i ? 120 : 480 > i ? 480 : 1080 > i ? 1080 : 1920 > i ? 1920 : 3e3 > i ? 3e3 : 4320 > i ? 4320 : 1960 * nj(i / 1960)) - i,
            10 < i) {
                a.timeoutHandle = of(Uj.bind(null, a), i);
                break
            }
            Uj(a);
            break;
        case 5:
            Uj(a);
            break;
        default:
            throw Error(y(329))
        }
    }
    return Mj(a, O()),
    a.callbackNode === e ? Nj.bind(null, a) : null
}
function Ii(a, e) {
    for (e &= ~uj,
    e &= ~Hi,
    a.suspendedLanes |= e,
    a.pingedLanes &= ~e,
    a = a.expirationTimes; 0 < e; ) {
        var i = 31 - Vc(e)
          , o = 1 << i;
        a[i] = -1,
        e &= ~o
    }
}
function Lj(a) {
    if ((X & 48) !== 0)
        throw Error(y(327));
    if (Oj(),
    a === U && (a.expiredLanes & W) !== 0) {
        var e = W
          , i = Tj(a, e);
        (tj & Hi) !== 0 && (e = Uc(a, e),
        i = Tj(a, e))
    } else
        e = Uc(a, 0),
        i = Tj(a, e);
    if (a.tag !== 0 && i === 2 && (X |= 64,
    a.hydrate && (a.hydrate = !1,
    qf(a.containerInfo)),
    e = Wc(a),
    e !== 0 && (i = Tj(a, e))),
    i === 1)
        throw i = sj,
        Qj(a, 0),
        Ii(a, e),
        Mj(a, O()),
        i;
    return a.finishedWork = a.current.alternate,
    a.finishedLanes = e,
    Uj(a),
    Mj(a, O()),
    null
}
function Vj() {
    if (Cj !== null) {
        var a = Cj;
        Cj = null,
        a.forEach(function(e) {
            e.expiredLanes |= 24 & e.pendingLanes,
            Mj(e, O())
        })
    }
    ig()
}
function Wj(a, e) {
    var i = X;
    X |= 1;
    try {
        return a(e)
    } finally {
        X = i,
        X === 0 && (wj(),
        ig())
    }
}
function Xj(a, e) {
    var i = X;
    X &= -2,
    X |= 8;
    try {
        return a(e)
    } finally {
        X = i,
        X === 0 && (wj(),
        ig())
    }
}
function ni(a, e) {
    I(rj, qj),
    qj |= e,
    tj |= e
}
function Ki() {
    qj = rj.current,
    H(rj)
}
function Qj(a, e) {
    a.finishedWork = null,
    a.finishedLanes = 0;
    var i = a.timeoutHandle;
    if (i !== -1 && (a.timeoutHandle = -1,
    pf(i)),
    Y !== null)
        for (i = Y.return; i !== null; ) {
            var o = i;
            switch (o.tag) {
            case 1:
                o = o.type.childContextTypes,
                o != null && Gf();
                break;
            case 3:
                fh(),
                H(N),
                H(M),
                uh();
                break;
            case 5:
                hh(o);
                break;
            case 4:
                fh();
                break;
            case 13:
                H(P);
                break;
            case 19:
                H(P);
                break;
            case 10:
                rg(o);
                break;
            case 23:
            case 24:
                Ki()
            }
            i = i.return
        }
    U = a,
    Y = Tg(a.current, null),
    W = qj = tj = e,
    V = 0,
    sj = null,
    uj = Hi = Dg = 0
}
function Sj(a, e) {
    do {
        var i = Y;
        try {
            if (qg(),
            vh.current = Gh,
            yh) {
                for (var o = R.memoizedState; o !== null; ) {
                    var s = o.queue;
                    s !== null && (s.pending = null),
                    o = o.next
                }
                yh = !1
            }
            if (xh = 0,
            T = S = R = null,
            zh = !1,
            pj.current = null,
            i === null || i.return === null) {
                V = 1,
                sj = e,
                Y = null;
                break
            }
            e: {
                var c = a
                  , d = i.return
                  , _ = i
                  , b = e;
                if (e = W,
                _.flags |= 2048,
                _.firstEffect = _.lastEffect = null,
                b !== null && typeof b == "object" && typeof b.then == "function") {
                    var k = b;
                    if ((_.mode & 2) === 0) {
                        var j = _.alternate;
                        j ? (_.updateQueue = j.updateQueue,
                        _.memoizedState = j.memoizedState,
                        _.lanes = j.lanes) : (_.updateQueue = null,
                        _.memoizedState = null)
                    }
                    var $ = (P.current & 1) !== 0
                      , _e = d;
                    do {
                        var et;
                        if (et = _e.tag === 13) {
                            var tt = _e.memoizedState;
                            if (tt !== null)
                                et = tt.dehydrated !== null;
                            else {
                                var rt = _e.memoizedProps;
                                et = rt.fallback === void 0 ? !1 : rt.unstable_avoidThisFallback !== !0 ? !0 : !$
                            }
                        }
                        if (et) {
                            var it = _e.updateQueue;
                            if (it === null) {
                                var nt = new Set;
                                nt.add(k),
                                _e.updateQueue = nt
                            } else
                                it.add(k);
                            if ((_e.mode & 2) === 0) {
                                if (_e.flags |= 64,
                                _.flags |= 16384,
                                _.flags &= -2981,
                                _.tag === 1)
                                    if (_.alternate === null)
                                        _.tag = 17;
                                    else {
                                        var ot = zg(-1, 1);
                                        ot.tag = 2,
                                        Ag(_, ot)
                                    }
                                _.lanes |= 1;
                                break e
                            }
                            b = void 0,
                            _ = e;
                            var at = c.pingCache;
                            if (at === null ? (at = c.pingCache = new Oi,
                            b = new Set,
                            at.set(k, b)) : (b = at.get(k),
                            b === void 0 && (b = new Set,
                            at.set(k, b))),
                            !b.has(_)) {
                                b.add(_);
                                var st = Yj.bind(null, c, k, _);
                                k.then(st, st)
                            }
                            _e.flags |= 4096,
                            _e.lanes = e;
                            break e
                        }
                        _e = _e.return
                    } while (_e !== null);
                    b = Error((Ra(_.type) || "A React component") + ` suspended while rendering, but no fallback UI was specified.

Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.`)
                }
                V !== 5 && (V = 2),
                b = Mi(b, _),
                _e = d;
                do {
                    switch (_e.tag) {
                    case 3:
                        c = b,
                        _e.flags |= 4096,
                        e &= -e,
                        _e.lanes |= e;
                        var ut = Pi(_e, c, e);
                        Bg(_e, ut);
                        break e;
                    case 1:
                        c = b;
                        var ct = _e.type
                          , lt = _e.stateNode;
                        if ((_e.flags & 64) === 0 && (typeof ct.getDerivedStateFromError == "function" || lt !== null && typeof lt.componentDidCatch == "function" && (Ti === null || !Ti.has(lt)))) {
                            _e.flags |= 4096,
                            e &= -e,
                            _e.lanes |= e;
                            var ft = Si(_e, c, e);
                            Bg(_e, ft);
                            break e
                        }
                    }
                    _e = _e.return
                } while (_e !== null)
            }
            Zj(i)
        } catch (ht) {
            e = ht,
            Y === i && i !== null && (Y = i = i.return);
            continue
        }
        break
    } while (1)
}
function Pj() {
    var a = oj.current;
    return oj.current = Gh,
    a === null ? Gh : a
}
function Tj(a, e) {
    var i = X;
    X |= 16;
    var o = Pj();
    U === a && W === e || Qj(a, e);
    do
        try {
            ak();
            break
        } catch (s) {
            Sj(a, s)
        }
    while (1);
    if (qg(),
    X = i,
    oj.current = o,
    Y !== null)
        throw Error(y(261));
    return U = null,
    W = 0,
    V
}
function ak() {
    for (; Y !== null; )
        bk(Y)
}
function Rj() {
    for (; Y !== null && !Qf(); )
        bk(Y)
}
function bk(a) {
    var e = ck(a.alternate, a, qj);
    a.memoizedProps = a.pendingProps,
    e === null ? Zj(a) : Y = e,
    pj.current = null
}
function Zj(a) {
    var e = a;
    do {
        var i = e.alternate;
        if (a = e.return,
        (e.flags & 2048) === 0) {
            if (i = Gi(i, e, qj),
            i !== null) {
                Y = i;
                return
            }
            if (i = e,
            i.tag !== 24 && i.tag !== 23 || i.memoizedState === null || (qj & 1073741824) !== 0 || (i.mode & 4) === 0) {
                for (var o = 0, s = i.child; s !== null; )
                    o |= s.lanes | s.childLanes,
                    s = s.sibling;
                i.childLanes = o
            }
            a !== null && (a.flags & 2048) === 0 && (a.firstEffect === null && (a.firstEffect = e.firstEffect),
            e.lastEffect !== null && (a.lastEffect !== null && (a.lastEffect.nextEffect = e.firstEffect),
            a.lastEffect = e.lastEffect),
            1 < e.flags && (a.lastEffect !== null ? a.lastEffect.nextEffect = e : a.firstEffect = e,
            a.lastEffect = e))
        } else {
            if (i = Li(e),
            i !== null) {
                i.flags &= 2047,
                Y = i;
                return
            }
            a !== null && (a.firstEffect = a.lastEffect = null,
            a.flags |= 2048)
        }
        if (e = e.sibling,
        e !== null) {
            Y = e;
            return
        }
        Y = e = a
    } while (e !== null);
    V === 0 && (V = 5)
}
function Uj(a) {
    var e = eg();
    return gg(99, dk.bind(null, a, e)),
    null
}
function dk(a, e) {
    do
        Oj();
    while (yj !== null);
    if ((X & 48) !== 0)
        throw Error(y(327));
    var i = a.finishedWork;
    if (i === null)
        return null;
    if (a.finishedWork = null,
    a.finishedLanes = 0,
    i === a.current)
        throw Error(y(177));
    a.callbackNode = null;
    var o = i.lanes | i.childLanes
      , s = o
      , c = a.pendingLanes & ~s;
    a.pendingLanes = s,
    a.suspendedLanes = 0,
    a.pingedLanes = 0,
    a.expiredLanes &= s,
    a.mutableReadLanes &= s,
    a.entangledLanes &= s,
    s = a.entanglements;
    for (var d = a.eventTimes, _ = a.expirationTimes; 0 < c; ) {
        var b = 31 - Vc(c)
          , k = 1 << b;
        s[b] = 0,
        d[b] = -1,
        _[b] = -1,
        c &= ~k
    }
    if (Cj !== null && (o & 24) === 0 && Cj.has(a) && Cj.delete(a),
    a === U && (Y = U = null,
    W = 0),
    1 < i.flags ? i.lastEffect !== null ? (i.lastEffect.nextEffect = i,
    o = i.firstEffect) : o = i : o = i.firstEffect,
    o !== null) {
        if (s = X,
        X |= 32,
        pj.current = null,
        kf = fd,
        d = Ne(),
        Oe(d)) {
            if ("selectionStart"in d)
                _ = {
                    start: d.selectionStart,
                    end: d.selectionEnd
                };
            else
                e: if (_ = (_ = d.ownerDocument) && _.defaultView || window,
                (k = _.getSelection && _.getSelection()) && k.rangeCount !== 0) {
                    _ = k.anchorNode,
                    c = k.anchorOffset,
                    b = k.focusNode,
                    k = k.focusOffset;
                    try {
                        _.nodeType,
                        b.nodeType
                    } catch {
                        _ = null;
                        break e
                    }
                    var j = 0
                      , $ = -1
                      , _e = -1
                      , et = 0
                      , tt = 0
                      , rt = d
                      , it = null;
                    t: for (; ; ) {
                        for (var nt; rt !== _ || c !== 0 && rt.nodeType !== 3 || ($ = j + c),
                        rt !== b || k !== 0 && rt.nodeType !== 3 || (_e = j + k),
                        rt.nodeType === 3 && (j += rt.nodeValue.length),
                        (nt = rt.firstChild) !== null; )
                            it = rt,
                            rt = nt;
                        for (; ; ) {
                            if (rt === d)
                                break t;
                            if (it === _ && ++et === c && ($ = j),
                            it === b && ++tt === k && (_e = j),
                            (nt = rt.nextSibling) !== null)
                                break;
                            rt = it,
                            it = rt.parentNode
                        }
                        rt = nt
                    }
                    _ = $ === -1 || _e === -1 ? null : {
                        start: $,
                        end: _e
                    }
                } else
                    _ = null;
            _ = _ || {
                start: 0,
                end: 0
            }
        } else
            _ = null;
        lf = {
            focusedElem: d,
            selectionRange: _
        },
        fd = !1,
        Ij = null,
        Jj = !1,
        Z = o;
        do
            try {
                ek()
            } catch (ht) {
                if (Z === null)
                    throw Error(y(330));
                Wi(Z, ht),
                Z = Z.nextEffect
            }
        while (Z !== null);
        Ij = null,
        Z = o;
        do
            try {
                for (d = a; Z !== null; ) {
                    var ot = Z.flags;
                    if (ot & 16 && pb(Z.stateNode, ""),
                    ot & 128) {
                        var at = Z.alternate;
                        if (at !== null) {
                            var st = at.ref;
                            st !== null && (typeof st == "function" ? st(null) : st.current = null)
                        }
                    }
                    switch (ot & 1038) {
                    case 2:
                        fj(Z),
                        Z.flags &= -3;
                        break;
                    case 6:
                        fj(Z),
                        Z.flags &= -3,
                        ij(Z.alternate, Z);
                        break;
                    case 1024:
                        Z.flags &= -1025;
                        break;
                    case 1028:
                        Z.flags &= -1025,
                        ij(Z.alternate, Z);
                        break;
                    case 4:
                        ij(Z.alternate, Z);
                        break;
                    case 8:
                        _ = Z,
                        cj(d, _);
                        var ut = _.alternate;
                        dj(_),
                        ut !== null && dj(ut)
                    }
                    Z = Z.nextEffect
                }
            } catch (ht) {
                if (Z === null)
                    throw Error(y(330));
                Wi(Z, ht),
                Z = Z.nextEffect
            }
        while (Z !== null);
        if (st = lf,
        at = Ne(),
        ot = st.focusedElem,
        d = st.selectionRange,
        at !== ot && ot && ot.ownerDocument && Me(ot.ownerDocument.documentElement, ot)) {
            for (d !== null && Oe(ot) && (at = d.start,
            st = d.end,
            st === void 0 && (st = at),
            "selectionStart"in ot ? (ot.selectionStart = at,
            ot.selectionEnd = Math.min(st, ot.value.length)) : (st = (at = ot.ownerDocument || document) && at.defaultView || window,
            st.getSelection && (st = st.getSelection(),
            _ = ot.textContent.length,
            ut = Math.min(d.start, _),
            d = d.end === void 0 ? ut : Math.min(d.end, _),
            !st.extend && ut > d && (_ = d,
            d = ut,
            ut = _),
            _ = Le(ot, ut),
            c = Le(ot, d),
            _ && c && (st.rangeCount !== 1 || st.anchorNode !== _.node || st.anchorOffset !== _.offset || st.focusNode !== c.node || st.focusOffset !== c.offset) && (at = at.createRange(),
            at.setStart(_.node, _.offset),
            st.removeAllRanges(),
            ut > d ? (st.addRange(at),
            st.extend(c.node, c.offset)) : (at.setEnd(c.node, c.offset),
            st.addRange(at)))))),
            at = [],
            st = ot; st = st.parentNode; )
                st.nodeType === 1 && at.push({
                    element: st,
                    left: st.scrollLeft,
                    top: st.scrollTop
                });
            for (typeof ot.focus == "function" && ot.focus(),
            ot = 0; ot < at.length; ot++)
                st = at[ot],
                st.element.scrollLeft = st.left,
                st.element.scrollTop = st.top
        }
        fd = !!kf,
        lf = kf = null,
        a.current = i,
        Z = o;
        do
            try {
                for (ot = a; Z !== null; ) {
                    var ct = Z.flags;
                    if (ct & 36 && Yi(ot, Z.alternate, Z),
                    ct & 128) {
                        at = void 0;
                        var lt = Z.ref;
                        if (lt !== null) {
                            var ft = Z.stateNode;
                            switch (Z.tag) {
                            case 5:
                                at = ft;
                                break;
                            default:
                                at = ft
                            }
                            typeof lt == "function" ? lt(at) : lt.current = at
                        }
                    }
                    Z = Z.nextEffect
                }
            } catch (ht) {
                if (Z === null)
                    throw Error(y(330));
                Wi(Z, ht),
                Z = Z.nextEffect
            }
        while (Z !== null);
        Z = null,
        $f(),
        X = s
    } else
        a.current = i;
    if (xj)
        xj = !1,
        yj = a,
        zj = e;
    else
        for (Z = o; Z !== null; )
            e = Z.nextEffect,
            Z.nextEffect = null,
            Z.flags & 8 && (ct = Z,
            ct.sibling = null,
            ct.stateNode = null),
            Z = e;
    if (o = a.pendingLanes,
    o === 0 && (Ti = null),
    o === 1 ? a === Ej ? Dj++ : (Dj = 0,
    Ej = a) : Dj = 0,
    i = i.stateNode,
    Mf && typeof Mf.onCommitFiberRoot == "function")
        try {
            Mf.onCommitFiberRoot(Lf, i, void 0, (i.current.flags & 64) === 64)
        } catch {}
    if (Mj(a, O()),
    Qi)
        throw Qi = !1,
        a = Ri,
        Ri = null,
        a;
    return (X & 8) !== 0 || ig(),
    null
}
function ek() {
    for (; Z !== null; ) {
        var a = Z.alternate;
        Jj || Ij === null || ((Z.flags & 8) !== 0 ? dc(Z, Ij) && (Jj = !0) : Z.tag === 13 && mj(a, Z) && dc(Z, Ij) && (Jj = !0));
        var e = Z.flags;
        (e & 256) !== 0 && Xi(a, Z),
        (e & 512) === 0 || xj || (xj = !0,
        hg(97, function() {
            return Oj(),
            null
        })),
        Z = Z.nextEffect
    }
}
function Oj() {
    if (zj !== 90) {
        var a = 97 < zj ? 97 : zj;
        return zj = 90,
        gg(a, fk)
    }
    return !1
}
function $i(a, e) {
    Aj.push(e, a),
    xj || (xj = !0,
    hg(97, function() {
        return Oj(),
        null
    }))
}
function Zi(a, e) {
    Bj.push(e, a),
    xj || (xj = !0,
    hg(97, function() {
        return Oj(),
        null
    }))
}
function fk() {
    if (yj === null)
        return !1;
    var a = yj;
    if (yj = null,
    (X & 48) !== 0)
        throw Error(y(331));
    var e = X;
    X |= 32;
    var i = Bj;
    Bj = [];
    for (var o = 0; o < i.length; o += 2) {
        var s = i[o]
          , c = i[o + 1]
          , d = s.destroy;
        if (s.destroy = void 0,
        typeof d == "function")
            try {
                d()
            } catch (b) {
                if (c === null)
                    throw Error(y(330));
                Wi(c, b)
            }
    }
    for (i = Aj,
    Aj = [],
    o = 0; o < i.length; o += 2) {
        s = i[o],
        c = i[o + 1];
        try {
            var _ = s.create;
            s.destroy = _()
        } catch (b) {
            if (c === null)
                throw Error(y(330));
            Wi(c, b)
        }
    }
    for (_ = a.current.firstEffect; _ !== null; )
        a = _.nextEffect,
        _.nextEffect = null,
        _.flags & 8 && (_.sibling = null,
        _.stateNode = null),
        _ = a;
    return X = e,
    ig(),
    !0
}
function gk(a, e, i) {
    e = Mi(i, e),
    e = Pi(a, e, 1),
    Ag(a, e),
    e = Hg(),
    a = Kj(a, 1),
    a !== null && ($c(a, 1, e),
    Mj(a, e))
}
function Wi(a, e) {
    if (a.tag === 3)
        gk(a, a, e);
    else
        for (var i = a.return; i !== null; ) {
            if (i.tag === 3) {
                gk(i, a, e);
                break
            } else if (i.tag === 1) {
                var o = i.stateNode;
                if (typeof i.type.getDerivedStateFromError == "function" || typeof o.componentDidCatch == "function" && (Ti === null || !Ti.has(o))) {
                    a = Mi(e, a);
                    var s = Si(i, a, 1);
                    if (Ag(i, s),
                    s = Hg(),
                    i = Kj(i, 1),
                    i !== null)
                        $c(i, 1, s),
                        Mj(i, s);
                    else if (typeof o.componentDidCatch == "function" && (Ti === null || !Ti.has(o)))
                        try {
                            o.componentDidCatch(e, a)
                        } catch {}
                    break
                }
            }
            i = i.return
        }
}
function Yj(a, e, i) {
    var o = a.pingCache;
    o !== null && o.delete(e),
    e = Hg(),
    a.pingedLanes |= a.suspendedLanes & i,
    U === a && (W & i) === i && (V === 4 || V === 3 && (W & 62914560) === W && 500 > O() - jj ? Qj(a, 0) : uj |= i),
    Mj(a, e)
}
function lj(a, e) {
    var i = a.stateNode;
    i !== null && i.delete(e),
    e = 0,
    e === 0 && (e = a.mode,
    (e & 2) === 0 ? e = 1 : (e & 4) === 0 ? e = eg() === 99 ? 1 : 2 : (Gj === 0 && (Gj = tj),
    e = Yc(62914560 & ~Gj),
    e === 0 && (e = 4194304))),
    i = Hg(),
    a = Kj(a, e),
    a !== null && ($c(a, e, i),
    Mj(a, i))
}
var ck;
ck = function(a, e, i) {
    var o = e.lanes;
    if (a !== null)
        if (a.memoizedProps !== e.pendingProps || N.current)
            ug = !0;
        else if ((i & o) !== 0)
            ug = (a.flags & 16384) !== 0;
        else {
            switch (ug = !1,
            e.tag) {
            case 3:
                ri(e),
                sh();
                break;
            case 5:
                gh(e);
                break;
            case 1:
                Ff(e.type) && Jf(e);
                break;
            case 4:
                eh(e, e.stateNode.containerInfo);
                break;
            case 10:
                o = e.memoizedProps.value;
                var s = e.type._context;
                I(mg, s._currentValue),
                s._currentValue = o;
                break;
            case 13:
                if (e.memoizedState !== null)
                    return (i & e.child.childLanes) !== 0 ? ti(a, e, i) : (I(P, P.current & 1),
                    e = hi(a, e, i),
                    e !== null ? e.sibling : null);
                I(P, P.current & 1);
                break;
            case 19:
                if (o = (i & e.childLanes) !== 0,
                (a.flags & 64) !== 0) {
                    if (o)
                        return Ai(a, e, i);
                    e.flags |= 64
                }
                if (s = e.memoizedState,
                s !== null && (s.rendering = null,
                s.tail = null,
                s.lastEffect = null),
                I(P, P.current),
                o)
                    break;
                return null;
            case 23:
            case 24:
                return e.lanes = 0,
                mi(a, e, i)
            }
            return hi(a, e, i)
        }
    else
        ug = !1;
    switch (e.lanes = 0,
    e.tag) {
    case 2:
        if (o = e.type,
        a !== null && (a.alternate = null,
        e.alternate = null,
        e.flags |= 2),
        a = e.pendingProps,
        s = Ef(e, M.current),
        tg(e, i),
        s = Ch(null, e, o, a, s, i),
        e.flags |= 1,
        typeof s == "object" && s !== null && typeof s.render == "function" && s.$$typeof === void 0) {
            if (e.tag = 1,
            e.memoizedState = null,
            e.updateQueue = null,
            Ff(o)) {
                var c = !0;
                Jf(e)
            } else
                c = !1;
            e.memoizedState = s.state !== null && s.state !== void 0 ? s.state : null,
            xg(e);
            var d = o.getDerivedStateFromProps;
            typeof d == "function" && Gg(e, o, d, a),
            s.updater = Kg,
            e.stateNode = s,
            s._reactInternals = e,
            Og(e, o, a, i),
            e = qi(null, e, o, !0, c, i)
        } else
            e.tag = 0,
            fi(null, e, s, i),
            e = e.child;
        return e;
    case 16:
        s = e.elementType;
        e: {
            switch (a !== null && (a.alternate = null,
            e.alternate = null,
            e.flags |= 2),
            a = e.pendingProps,
            c = s._init,
            s = c(s._payload),
            e.type = s,
            c = e.tag = hk(s),
            a = lg(s, a),
            c) {
            case 0:
                e = li(null, e, s, a, i);
                break e;
            case 1:
                e = pi(null, e, s, a, i);
                break e;
            case 11:
                e = gi(null, e, s, a, i);
                break e;
            case 14:
                e = ii(null, e, s, lg(s.type, a), o, i);
                break e
            }
            throw Error(y(306, s, ""))
        }
        return e;
    case 0:
        return o = e.type,
        s = e.pendingProps,
        s = e.elementType === o ? s : lg(o, s),
        li(a, e, o, s, i);
    case 1:
        return o = e.type,
        s = e.pendingProps,
        s = e.elementType === o ? s : lg(o, s),
        pi(a, e, o, s, i);
    case 3:
        if (ri(e),
        o = e.updateQueue,
        a === null || o === null)
            throw Error(y(282));
        if (o = e.pendingProps,
        s = e.memoizedState,
        s = s !== null ? s.element : null,
        yg(a, e),
        Cg(e, o, null, i),
        o = e.memoizedState.element,
        o === s)
            sh(),
            e = hi(a, e, i);
        else {
            if (s = e.stateNode,
            (c = s.hydrate) && (kh = rf(e.stateNode.containerInfo.firstChild),
            jh = e,
            c = lh = !0),
            c) {
                if (a = s.mutableSourceEagerHydrationData,
                a != null)
                    for (s = 0; s < a.length; s += 2)
                        c = a[s],
                        c._workInProgressVersionPrimary = a[s + 1],
                        th.push(c);
                for (i = Zg(e, null, o, i),
                e.child = i; i; )
                    i.flags = i.flags & -3 | 1024,
                    i = i.sibling
            } else
                fi(a, e, o, i),
                sh();
            e = e.child
        }
        return e;
    case 5:
        return gh(e),
        a === null && ph(e),
        o = e.type,
        s = e.pendingProps,
        c = a !== null ? a.memoizedProps : null,
        d = s.children,
        nf(o, s) ? d = null : c !== null && nf(o, c) && (e.flags |= 16),
        oi(a, e),
        fi(a, e, d, i),
        e.child;
    case 6:
        return a === null && ph(e),
        null;
    case 13:
        return ti(a, e, i);
    case 4:
        return eh(e, e.stateNode.containerInfo),
        o = e.pendingProps,
        a === null ? e.child = Yg(e, null, o, i) : fi(a, e, o, i),
        e.child;
    case 11:
        return o = e.type,
        s = e.pendingProps,
        s = e.elementType === o ? s : lg(o, s),
        gi(a, e, o, s, i);
    case 7:
        return fi(a, e, e.pendingProps, i),
        e.child;
    case 8:
        return fi(a, e, e.pendingProps.children, i),
        e.child;
    case 12:
        return fi(a, e, e.pendingProps.children, i),
        e.child;
    case 10:
        e: {
            o = e.type._context,
            s = e.pendingProps,
            d = e.memoizedProps,
            c = s.value;
            var _ = e.type._context;
            if (I(mg, _._currentValue),
            _._currentValue = c,
            d !== null)
                if (_ = d.value,
                c = He(_, c) ? 0 : (typeof o._calculateChangedBits == "function" ? o._calculateChangedBits(_, c) : 1073741823) | 0,
                c === 0) {
                    if (d.children === s.children && !N.current) {
                        e = hi(a, e, i);
                        break e
                    }
                } else
                    for (_ = e.child,
                    _ !== null && (_.return = e); _ !== null; ) {
                        var b = _.dependencies;
                        if (b !== null) {
                            d = _.child;
                            for (var k = b.firstContext; k !== null; ) {
                                if (k.context === o && (k.observedBits & c) !== 0) {
                                    _.tag === 1 && (k = zg(-1, i & -i),
                                    k.tag = 2,
                                    Ag(_, k)),
                                    _.lanes |= i,
                                    k = _.alternate,
                                    k !== null && (k.lanes |= i),
                                    sg(_.return, i),
                                    b.lanes |= i;
                                    break
                                }
                                k = k.next
                            }
                        } else
                            d = _.tag === 10 && _.type === e.type ? null : _.child;
                        if (d !== null)
                            d.return = _;
                        else
                            for (d = _; d !== null; ) {
                                if (d === e) {
                                    d = null;
                                    break
                                }
                                if (_ = d.sibling,
                                _ !== null) {
                                    _.return = d.return,
                                    d = _;
                                    break
                                }
                                d = d.return
                            }
                        _ = d
                    }
            fi(a, e, s.children, i),
            e = e.child
        }
        return e;
    case 9:
        return s = e.type,
        c = e.pendingProps,
        o = c.children,
        tg(e, i),
        s = vg(s, c.unstable_observedBits),
        o = o(s),
        e.flags |= 1,
        fi(a, e, o, i),
        e.child;
    case 14:
        return s = e.type,
        c = lg(s, e.pendingProps),
        c = lg(s.type, c),
        ii(a, e, s, c, o, i);
    case 15:
        return ki(a, e, e.type, e.pendingProps, o, i);
    case 17:
        return o = e.type,
        s = e.pendingProps,
        s = e.elementType === o ? s : lg(o, s),
        a !== null && (a.alternate = null,
        e.alternate = null,
        e.flags |= 2),
        e.tag = 1,
        Ff(o) ? (a = !0,
        Jf(e)) : a = !1,
        tg(e, i),
        Mg(e, o, s),
        Og(e, o, s, i),
        qi(null, e, o, !0, a, i);
    case 19:
        return Ai(a, e, i);
    case 23:
        return mi(a, e, i);
    case 24:
        return mi(a, e, i)
    }
    throw Error(y(156, e.tag))
}
;
function ik(a, e, i, o) {
    this.tag = a,
    this.key = i,
    this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null,
    this.index = 0,
    this.ref = null,
    this.pendingProps = e,
    this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null,
    this.mode = o,
    this.flags = 0,
    this.lastEffect = this.firstEffect = this.nextEffect = null,
    this.childLanes = this.lanes = 0,
    this.alternate = null
}
function nh(a, e, i, o) {
    return new ik(a,e,i,o)
}
function ji(a) {
    return a = a.prototype,
    !(!a || !a.isReactComponent)
}
function hk(a) {
    if (typeof a == "function")
        return ji(a) ? 1 : 0;
    if (a != null) {
        if (a = a.$$typeof,
        a === Aa)
            return 11;
        if (a === Da)
            return 14
    }
    return 2
}
function Tg(a, e) {
    var i = a.alternate;
    return i === null ? (i = nh(a.tag, e, a.key, a.mode),
    i.elementType = a.elementType,
    i.type = a.type,
    i.stateNode = a.stateNode,
    i.alternate = a,
    a.alternate = i) : (i.pendingProps = e,
    i.type = a.type,
    i.flags = 0,
    i.nextEffect = null,
    i.firstEffect = null,
    i.lastEffect = null),
    i.childLanes = a.childLanes,
    i.lanes = a.lanes,
    i.child = a.child,
    i.memoizedProps = a.memoizedProps,
    i.memoizedState = a.memoizedState,
    i.updateQueue = a.updateQueue,
    e = a.dependencies,
    i.dependencies = e === null ? null : {
        lanes: e.lanes,
        firstContext: e.firstContext
    },
    i.sibling = a.sibling,
    i.index = a.index,
    i.ref = a.ref,
    i
}
function Vg(a, e, i, o, s, c) {
    var d = 2;
    if (o = a,
    typeof a == "function")
        ji(a) && (d = 1);
    else if (typeof a == "string")
        d = 5;
    else
        e: switch (a) {
        case ua:
            return Xg(i.children, s, c, e);
        case Ha:
            d = 8,
            s |= 16;
            break;
        case wa:
            d = 8,
            s |= 1;
            break;
        case xa:
            return a = nh(12, i, e, s | 8),
            a.elementType = xa,
            a.type = xa,
            a.lanes = c,
            a;
        case Ba:
            return a = nh(13, i, e, s),
            a.type = Ba,
            a.elementType = Ba,
            a.lanes = c,
            a;
        case Ca:
            return a = nh(19, i, e, s),
            a.elementType = Ca,
            a.lanes = c,
            a;
        case Ia:
            return vi(i, s, c, e);
        case Ja:
            return a = nh(24, i, e, s),
            a.elementType = Ja,
            a.lanes = c,
            a;
        default:
            if (typeof a == "object" && a !== null)
                switch (a.$$typeof) {
                case ya:
                    d = 10;
                    break e;
                case za:
                    d = 9;
                    break e;
                case Aa:
                    d = 11;
                    break e;
                case Da:
                    d = 14;
                    break e;
                case Ea:
                    d = 16,
                    o = null;
                    break e;
                case Fa:
                    d = 22;
                    break e
                }
            throw Error(y(130, a == null ? a : typeof a, ""))
        }
    return e = nh(d, i, e, s),
    e.elementType = a,
    e.type = o,
    e.lanes = c,
    e
}
function Xg(a, e, i, o) {
    return a = nh(7, a, o, e),
    a.lanes = i,
    a
}
function vi(a, e, i, o) {
    return a = nh(23, a, o, e),
    a.elementType = Ia,
    a.lanes = i,
    a
}
function Ug(a, e, i) {
    return a = nh(6, a, null, e),
    a.lanes = i,
    a
}
function Wg(a, e, i) {
    return e = nh(4, a.children !== null ? a.children : [], a.key, e),
    e.lanes = i,
    e.stateNode = {
        containerInfo: a.containerInfo,
        pendingChildren: null,
        implementation: a.implementation
    },
    e
}
function jk(a, e, i) {
    this.tag = e,
    this.containerInfo = a,
    this.finishedWork = this.pingCache = this.current = this.pendingChildren = null,
    this.timeoutHandle = -1,
    this.pendingContext = this.context = null,
    this.hydrate = i,
    this.callbackNode = null,
    this.callbackPriority = 0,
    this.eventTimes = Zc(0),
    this.expirationTimes = Zc(-1),
    this.entangledLanes = this.finishedLanes = this.mutableReadLanes = this.expiredLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0,
    this.entanglements = Zc(0),
    this.mutableSourceEagerHydrationData = null
}
function kk(a, e, i) {
    var o = 3 < arguments.length && arguments[3] !== void 0 ? arguments[3] : null;
    return {
        $$typeof: ta,
        key: o == null ? null : "" + o,
        children: a,
        containerInfo: e,
        implementation: i
    }
}
function lk(a, e, i, o) {
    var s = e.current
      , c = Hg()
      , d = Ig(s);
    e: if (i) {
        i = i._reactInternals;
        t: {
            if (Zb(i) !== i || i.tag !== 1)
                throw Error(y(170));
            var _ = i;
            do {
                switch (_.tag) {
                case 3:
                    _ = _.stateNode.context;
                    break t;
                case 1:
                    if (Ff(_.type)) {
                        _ = _.stateNode.__reactInternalMemoizedMergedChildContext;
                        break t
                    }
                }
                _ = _.return
            } while (_ !== null);
            throw Error(y(171))
        }
        if (i.tag === 1) {
            var b = i.type;
            if (Ff(b)) {
                i = If(i, b, _);
                break e
            }
        }
        i = _
    } else
        i = Cf;
    return e.context === null ? e.context = i : e.pendingContext = i,
    e = zg(c, d),
    e.payload = {
        element: a
    },
    o = o === void 0 ? null : o,
    o !== null && (e.callback = o),
    Ag(s, e),
    Jg(s, d, c),
    d
}
function mk(a) {
    if (a = a.current,
    !a.child)
        return null;
    switch (a.child.tag) {
    case 5:
        return a.child.stateNode;
    default:
        return a.child.stateNode
    }
}
function nk(a, e) {
    if (a = a.memoizedState,
    a !== null && a.dehydrated !== null) {
        var i = a.retryLane;
        a.retryLane = i !== 0 && i < e ? i : e
    }
}
function ok(a, e) {
    nk(a, e),
    (a = a.alternate) && nk(a, e)
}
function pk() {
    return null
}
function qk(a, e, i) {
    var o = i != null && i.hydrationOptions != null && i.hydrationOptions.mutableSources || null;
    if (i = new jk(a,e,i != null && i.hydrate === !0),
    e = nh(3, null, null, e === 2 ? 7 : e === 1 ? 3 : 0),
    i.current = e,
    e.stateNode = i,
    xg(e),
    a[ff] = i.current,
    cf(a.nodeType === 8 ? a.parentNode : a),
    o)
        for (a = 0; a < o.length; a++) {
            e = o[a];
            var s = e._getVersion;
            s = s(e._source),
            i.mutableSourceEagerHydrationData == null ? i.mutableSourceEagerHydrationData = [e, s] : i.mutableSourceEagerHydrationData.push(e, s)
        }
    this._internalRoot = i
}
qk.prototype.render = function(a) {
    lk(a, this._internalRoot, null, null)
}
;
qk.prototype.unmount = function() {
    var a = this._internalRoot
      , e = a.containerInfo;
    lk(null, a, null, function() {
        e[ff] = null
    })
}
;
function rk(a) {
    return !(!a || a.nodeType !== 1 && a.nodeType !== 9 && a.nodeType !== 11 && (a.nodeType !== 8 || a.nodeValue !== " react-mount-point-unstable "))
}
function sk(a, e) {
    if (e || (e = a ? a.nodeType === 9 ? a.documentElement : a.firstChild : null,
    e = !(!e || e.nodeType !== 1 || !e.hasAttribute("data-reactroot"))),
    !e)
        for (var i; i = a.lastChild; )
            a.removeChild(i);
    return new qk(a,0,e ? {
        hydrate: !0
    } : void 0)
}
function tk(a, e, i, o, s) {
    var c = i._reactRootContainer;
    if (c) {
        var d = c._internalRoot;
        if (typeof s == "function") {
            var _ = s;
            s = function() {
                var k = mk(d);
                _.call(k)
            }
        }
        lk(e, d, a, s)
    } else {
        if (c = i._reactRootContainer = sk(i, o),
        d = c._internalRoot,
        typeof s == "function") {
            var b = s;
            s = function() {
                var k = mk(d);
                b.call(k)
            }
        }
        Xj(function() {
            lk(e, d, a, s)
        })
    }
    return mk(d)
}
ec = function(a) {
    if (a.tag === 13) {
        var e = Hg();
        Jg(a, 4, e),
        ok(a, 4)
    }
}
;
fc = function(a) {
    if (a.tag === 13) {
        var e = Hg();
        Jg(a, 67108864, e),
        ok(a, 67108864)
    }
}
;
gc = function(a) {
    if (a.tag === 13) {
        var e = Hg()
          , i = Ig(a);
        Jg(a, i, e),
        ok(a, i)
    }
}
;
hc = function(a, e) {
    return e()
}
;
yb = function(a, e, i) {
    switch (e) {
    case "input":
        if (ab(a, i),
        e = i.name,
        i.type === "radio" && e != null) {
            for (i = a; i.parentNode; )
                i = i.parentNode;
            for (i = i.querySelectorAll("input[name=" + JSON.stringify("" + e) + '][type="radio"]'),
            e = 0; e < i.length; e++) {
                var o = i[e];
                if (o !== a && o.form === a.form) {
                    var s = Db(o);
                    if (!s)
                        throw Error(y(90));
                    Wa(o),
                    ab(o, s)
                }
            }
        }
        break;
    case "textarea":
        ib(a, i);
        break;
    case "select":
        e = i.value,
        e != null && fb(a, !!i.multiple, e, !1)
    }
}
;
Gb = Wj;
Hb = function(a, e, i, o, s) {
    var c = X;
    X |= 4;
    try {
        return gg(98, a.bind(null, e, i, o, s))
    } finally {
        X = c,
        X === 0 && (wj(),
        ig())
    }
}
;
Ib = function() {
    (X & 49) === 0 && (Vj(),
    Oj())
}
;
Jb = function(a, e) {
    var i = X;
    X |= 2;
    try {
        return a(e)
    } finally {
        X = i,
        X === 0 && (wj(),
        ig())
    }
}
;
function uk(a, e) {
    var i = 2 < arguments.length && arguments[2] !== void 0 ? arguments[2] : null;
    if (!rk(e))
        throw Error(y(200));
    return kk(a, e, null, i)
}
var vk = {
    Events: [Cb, ue, Db, Eb, Fb, Oj, {
        current: !1
    }]
}
  , wk = {
    findFiberByHostInstance: wc,
    bundleType: 0,
    version: "17.0.2",
    rendererPackageName: "react-dom"
}
  , xk = {
    bundleType: wk.bundleType,
    version: wk.version,
    rendererPackageName: wk.rendererPackageName,
    rendererConfig: wk.rendererConfig,
    overrideHookState: null,
    overrideHookStateDeletePath: null,
    overrideHookStateRenamePath: null,
    overrideProps: null,
    overridePropsDeletePath: null,
    overridePropsRenamePath: null,
    setSuspenseHandler: null,
    scheduleUpdate: null,
    currentDispatcherRef: ra.ReactCurrentDispatcher,
    findHostInstanceByFiber: function(a) {
        return a = cc(a),
        a === null ? null : a.stateNode
    },
    findFiberByHostInstance: wk.findFiberByHostInstance || pk,
    findHostInstancesForRefresh: null,
    scheduleRefresh: null,
    scheduleRoot: null,
    setRefreshHandler: null,
    getCurrentFiber: null
};
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ != "undefined") {
    var yk = __REACT_DEVTOOLS_GLOBAL_HOOK__;
    if (!yk.isDisabled && yk.supportsFiber)
        try {
            Lf = yk.inject(xk),
            Mf = yk
        } catch {}
}
reactDom_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = vk;
reactDom_production_min.createPortal = uk;
reactDom_production_min.findDOMNode = function(a) {
    if (a == null)
        return null;
    if (a.nodeType === 1)
        return a;
    var e = a._reactInternals;
    if (e === void 0)
        throw typeof a.render == "function" ? Error(y(188)) : Error(y(268, Object.keys(a)));
    return a = cc(e),
    a = a === null ? null : a.stateNode,
    a
}
;
reactDom_production_min.flushSync = function(a, e) {
    var i = X;
    if ((i & 48) !== 0)
        return a(e);
    X |= 1;
    try {
        if (a)
            return gg(99, a.bind(null, e))
    } finally {
        X = i,
        ig()
    }
}
;
reactDom_production_min.hydrate = function(a, e, i) {
    if (!rk(e))
        throw Error(y(200));
    return tk(null, a, e, !0, i)
}
;
reactDom_production_min.render = function(a, e, i) {
    if (!rk(e))
        throw Error(y(200));
    return tk(null, a, e, !1, i)
}
;
reactDom_production_min.unmountComponentAtNode = function(a) {
    if (!rk(a))
        throw Error(y(40));
    return a._reactRootContainer ? (Xj(function() {
        tk(null, null, a, !1, function() {
            a._reactRootContainer = null,
            a[ff] = null
        })
    }),
    !0) : !1
}
;
reactDom_production_min.unstable_batchedUpdates = Wj;
reactDom_production_min.unstable_createPortal = function(a, e) {
    return uk(a, e, 2 < arguments.length && arguments[2] !== void 0 ? arguments[2] : null)
}
;
reactDom_production_min.unstable_renderSubtreeIntoContainer = function(a, e, i, o) {
    if (!rk(i))
        throw Error(y(200));
    if (a == null || a._reactInternals === void 0)
        throw Error(y(38));
    return tk(a, e, i, !1, o)
}
;
reactDom_production_min.version = "17.0.2";
function checkDCE() {
    if (!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ == "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE != "function"))
        try {
            __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)
        } catch (a) {
            console.error(a)
        }
}
checkDCE(),
reactDom.exports = reactDom_production_min;
var ReactDOM = reactDom.exports;
let logDisabled_ = !0
  , deprecationWarnings_ = !0;
function extractVersion(a, e, i) {
    const o = a.match(e);
    return o && o.length >= i && parseInt(o[i], 10)
}
function wrapPeerConnectionEvent(a, e, i) {
    if (!a.RTCPeerConnection)
        return;
    const o = a.RTCPeerConnection.prototype
      , s = o.addEventListener;
    o.addEventListener = function(d, _) {
        if (d !== e)
            return s.apply(this, arguments);
        const b = k=>{
            const j = i(k);
            j && (_.handleEvent ? _.handleEvent(j) : _(j))
        }
        ;
        return this._eventMap = this._eventMap || {},
        this._eventMap[e] || (this._eventMap[e] = new Map),
        this._eventMap[e].set(_, b),
        s.apply(this, [d, b])
    }
    ;
    const c = o.removeEventListener;
    o.removeEventListener = function(d, _) {
        if (d !== e || !this._eventMap || !this._eventMap[e])
            return c.apply(this, arguments);
        if (!this._eventMap[e].has(_))
            return c.apply(this, arguments);
        const b = this._eventMap[e].get(_);
        return this._eventMap[e].delete(_),
        this._eventMap[e].size === 0 && delete this._eventMap[e],
        Object.keys(this._eventMap).length === 0 && delete this._eventMap,
        c.apply(this, [d, b])
    }
    ,
    Object.defineProperty(o, "on" + e, {
        get() {
            return this["_on" + e]
        },
        set(d) {
            this["_on" + e] && (this.removeEventListener(e, this["_on" + e]),
            delete this["_on" + e]),
            d && this.addEventListener(e, this["_on" + e] = d)
        },
        enumerable: !0,
        configurable: !0
    })
}
function disableLog(a) {
    return typeof a != "boolean" ? new Error("Argument type: " + typeof a + ". Please use a boolean.") : (logDisabled_ = a,
    a ? "adapter.js logging disabled" : "adapter.js logging enabled")
}
function disableWarnings(a) {
    return typeof a != "boolean" ? new Error("Argument type: " + typeof a + ". Please use a boolean.") : (deprecationWarnings_ = !a,
    "adapter.js deprecation warnings " + (a ? "disabled" : "enabled"))
}
function log$L() {
    if (typeof window == "object") {
        if (logDisabled_)
            return;
        typeof console != "undefined" && typeof console.log == "function" && console.log.apply(console, arguments)
    }
}
function deprecated(a, e) {
    !deprecationWarnings_ || console.warn(a + " is deprecated, please use " + e + " instead.")
}
function detectBrowser(a) {
    const e = {
        browser: null,
        version: null
    };
    if (typeof a == "undefined" || !a.navigator)
        return e.browser = "Not a browser.",
        e;
    const {navigator: i} = a;
    if (i.mozGetUserMedia)
        e.browser = "firefox",
        e.version = extractVersion(i.userAgent, /Firefox\/(\d+)\./, 1);
    else if (i.webkitGetUserMedia || a.isSecureContext === !1 && a.webkitRTCPeerConnection && !a.RTCIceGatherer)
        e.browser = "chrome",
        e.version = extractVersion(i.userAgent, /Chrom(e|ium)\/(\d+)\./, 2);
    else if (a.RTCPeerConnection && i.userAgent.match(/AppleWebKit\/(\d+)\./))
        e.browser = "safari",
        e.version = extractVersion(i.userAgent, /AppleWebKit\/(\d+)\./, 1),
        e.supportsUnifiedPlan = a.RTCRtpTransceiver && "currentDirection"in a.RTCRtpTransceiver.prototype;
    else
        return e.browser = "Not a supported browser.",
        e;
    return e
}
function isObject$1(a) {
    return Object.prototype.toString.call(a) === "[object Object]"
}
function compactObject(a) {
    return isObject$1(a) ? Object.keys(a).reduce(function(e, i) {
        const o = isObject$1(a[i])
          , s = o ? compactObject(a[i]) : a[i]
          , c = o && !Object.keys(s).length;
        return s === void 0 || c ? e : Object.assign(e, {
            [i]: s
        })
    }, {}) : a
}
function walkStats(a, e, i) {
    !e || i.has(e.id) || (i.set(e.id, e),
    Object.keys(e).forEach(o=>{
        o.endsWith("Id") ? walkStats(a, a.get(e[o]), i) : o.endsWith("Ids") && e[o].forEach(s=>{
            walkStats(a, a.get(s), i)
        }
        )
    }
    ))
}
function filterStats(a, e, i) {
    const o = i ? "outbound-rtp" : "inbound-rtp"
      , s = new Map;
    if (e === null)
        return s;
    const c = [];
    return a.forEach(d=>{
        d.type === "track" && d.trackIdentifier === e.id && c.push(d)
    }
    ),
    c.forEach(d=>{
        a.forEach(_=>{
            _.type === o && _.trackId === d.id && walkStats(a, _, s)
        }
        )
    }
    ),
    s
}
const logging = log$L;
function shimGetUserMedia$2(a, e) {
    const i = a && a.navigator;
    if (!i.mediaDevices)
        return;
    const o = function(_) {
        if (typeof _ != "object" || _.mandatory || _.optional)
            return _;
        const b = {};
        return Object.keys(_).forEach(k=>{
            if (k === "require" || k === "advanced" || k === "mediaSource")
                return;
            const j = typeof _[k] == "object" ? _[k] : {
                ideal: _[k]
            };
            j.exact !== void 0 && typeof j.exact == "number" && (j.min = j.max = j.exact);
            const $ = function(_e, et) {
                return _e ? _e + et.charAt(0).toUpperCase() + et.slice(1) : et === "deviceId" ? "sourceId" : et
            };
            if (j.ideal !== void 0) {
                b.optional = b.optional || [];
                let _e = {};
                typeof j.ideal == "number" ? (_e[$("min", k)] = j.ideal,
                b.optional.push(_e),
                _e = {},
                _e[$("max", k)] = j.ideal,
                b.optional.push(_e)) : (_e[$("", k)] = j.ideal,
                b.optional.push(_e))
            }
            j.exact !== void 0 && typeof j.exact != "number" ? (b.mandatory = b.mandatory || {},
            b.mandatory[$("", k)] = j.exact) : ["min", "max"].forEach(_e=>{
                j[_e] !== void 0 && (b.mandatory = b.mandatory || {},
                b.mandatory[$(_e, k)] = j[_e])
            }
            )
        }
        ),
        _.advanced && (b.optional = (b.optional || []).concat(_.advanced)),
        b
    }
      , s = function(_, b) {
        if (e.version >= 61)
            return b(_);
        if (_ = JSON.parse(JSON.stringify(_)),
        _ && typeof _.audio == "object") {
            const k = function(j, $, _e) {
                $in j && !(_e in j) && (j[_e] = j[$],
                delete j[$])
            };
            _ = JSON.parse(JSON.stringify(_)),
            k(_.audio, "autoGainControl", "googAutoGainControl"),
            k(_.audio, "noiseSuppression", "googNoiseSuppression"),
            _.audio = o(_.audio)
        }
        if (_ && typeof _.video == "object") {
            let k = _.video.facingMode;
            k = k && (typeof k == "object" ? k : {
                ideal: k
            });
            const j = e.version < 66;
            if (k && (k.exact === "user" || k.exact === "environment" || k.ideal === "user" || k.ideal === "environment") && !(i.mediaDevices.getSupportedConstraints && i.mediaDevices.getSupportedConstraints().facingMode && !j)) {
                delete _.video.facingMode;
                let$;
                if (k.exact === "environment" || k.ideal === "environment" ? $ = ["back", "rear"] : (k.exact === "user" || k.ideal === "user") && ($ = ["front"]),
                $)
                    return i.mediaDevices.enumerateDevices().then(_e=>{
                        _e = _e.filter(tt=>tt.kind === "videoinput");
                        let et = _e.find(tt=>$.some(rt=>tt.label.toLowerCase().includes(rt)));
                        return !et && _e.length && $.includes("back") && (et = _e[_e.length - 1]),
                        et && (_.video.deviceId = k.exact ? {
                            exact: et.deviceId
                        } : {
                            ideal: et.deviceId
                        }),
                        _.video = o(_.video),
                        logging("chrome: " + JSON.stringify(_)),
                        b(_)
                    }
                    )
            }
            _.video = o(_.video)
        }
        return logging("chrome: " + JSON.stringify(_)),
        b(_)
    }
      , c = function(_) {
        return e.version >= 64 ? _ : {
            name: {
                PermissionDeniedError: "NotAllowedError",
                PermissionDismissedError: "NotAllowedError",
                InvalidStateError: "NotAllowedError",
                DevicesNotFoundError: "NotFoundError",
                ConstraintNotSatisfiedError: "OverconstrainedError",
                TrackStartError: "NotReadableError",
                MediaDeviceFailedDueToShutdown: "NotAllowedError",
                MediaDeviceKillSwitchOn: "NotAllowedError",
                TabCaptureError: "AbortError",
                ScreenCaptureError: "AbortError",
                DeviceCaptureError: "AbortError"
            }[_.name] || _.name,
            message: _.message,
            constraint: _.constraint || _.constraintName,
            toString() {
                return this.name + (this.message && ": ") + this.message
            }
        }
    }
      , d = function(_, b, k) {
        s(_, j=>{
            i.webkitGetUserMedia(j, b, $=>{
                k && k(c($))
            }
            )
        }
        )
    };
    if (i.getUserMedia = d.bind(i),
    i.mediaDevices.getUserMedia) {
        const _ = i.mediaDevices.getUserMedia.bind(i.mediaDevices);
        i.mediaDevices.getUserMedia = function(b) {
            return s(b, k=>_(k).then(j=>{
                if (k.audio && !j.getAudioTracks().length || k.video && !j.getVideoTracks().length)
                    throw j.getTracks().forEach($=>{
                        $.stop()
                    }
                    ),
                    new DOMException("","NotFoundError");
                return j
            }
            , j=>Promise.reject(c(j))))
        }
    }
}
function shimGetDisplayMedia$1(a, e) {
    if (!(a.navigator.mediaDevices && "getDisplayMedia"in a.navigator.mediaDevices) && !!a.navigator.mediaDevices) {
        if (typeof e != "function") {
            console.error("shimGetDisplayMedia: getSourceId argument is not a function");
            return
        }
        a.navigator.mediaDevices.getDisplayMedia = function(o) {
            return e(o).then(s=>{
                const c = o.video && o.video.width
                  , d = o.video && o.video.height
                  , _ = o.video && o.video.frameRate;
                return o.video = {
                    mandatory: {
                        chromeMediaSource: "desktop",
                        chromeMediaSourceId: s,
                        maxFrameRate: _ || 3
                    }
                },
                c && (o.video.mandatory.maxWidth = c),
                d && (o.video.mandatory.maxHeight = d),
                a.navigator.mediaDevices.getUserMedia(o)
            }
            )
        }
    }
}
function shimMediaStream(a) {
    a.MediaStream = a.MediaStream || a.webkitMediaStream
}
function shimOnTrack$1(a) {
    if (typeof a == "object" && a.RTCPeerConnection && !("ontrack"in a.RTCPeerConnection.prototype)) {
        Object.defineProperty(a.RTCPeerConnection.prototype, "ontrack", {
            get() {
                return this._ontrack
            },
            set(i) {
                this._ontrack && this.removeEventListener("track", this._ontrack),
                this.addEventListener("track", this._ontrack = i)
            },
            enumerable: !0,
            configurable: !0
        });
        const e = a.RTCPeerConnection.prototype.setRemoteDescription;
        a.RTCPeerConnection.prototype.setRemoteDescription = function() {
            return this._ontrackpoly || (this._ontrackpoly = o=>{
                o.stream.addEventListener("addtrack", s=>{
                    let c;
                    a.RTCPeerConnection.prototype.getReceivers ? c = this.getReceivers().find(_=>_.track && _.track.id === s.track.id) : c = {
                        track: s.track
                    };
                    const d = new Event("track");
                    d.track = s.track,
                    d.receiver = c,
                    d.transceiver = {
                        receiver: c
                    },
                    d.streams = [o.stream],
                    this.dispatchEvent(d)
                }
                ),
                o.stream.getTracks().forEach(s=>{
                    let c;
                    a.RTCPeerConnection.prototype.getReceivers ? c = this.getReceivers().find(_=>_.track && _.track.id === s.id) : c = {
                        track: s
                    };
                    const d = new Event("track");
                    d.track = s,
                    d.receiver = c,
                    d.transceiver = {
                        receiver: c
                    },
                    d.streams = [o.stream],
                    this.dispatchEvent(d)
                }
                )
            }
            ,
            this.addEventListener("addstream", this._ontrackpoly)),
            e.apply(this, arguments)
        }
    } else
        wrapPeerConnectionEvent(a, "track", e=>(e.transceiver || Object.defineProperty(e, "transceiver", {
            value: {
                receiver: e.receiver
            }
        }),
        e))
}
function shimGetSendersWithDtmf(a) {
    if (typeof a == "object" && a.RTCPeerConnection && !("getSenders"in a.RTCPeerConnection.prototype) && "createDTMFSender"in a.RTCPeerConnection.prototype) {
        const e = function(s, c) {
            return {
                track: c,
                get dtmf() {
                    return this._dtmf === void 0 && (c.kind === "audio" ? this._dtmf = s.createDTMFSender(c) : this._dtmf = null),
                    this._dtmf
                },
                _pc: s
            }
        };
        if (!a.RTCPeerConnection.prototype.getSenders) {
            a.RTCPeerConnection.prototype.getSenders = function() {
                return this._senders = this._senders || [],
                this._senders.slice()
            }
            ;
            const s = a.RTCPeerConnection.prototype.addTrack;
            a.RTCPeerConnection.prototype.addTrack = function(_, b) {
                let k = s.apply(this, arguments);
                return k || (k = e(this, _),
                this._senders.push(k)),
                k
            }
            ;
            const c = a.RTCPeerConnection.prototype.removeTrack;
            a.RTCPeerConnection.prototype.removeTrack = function(_) {
                c.apply(this, arguments);
                const b = this._senders.indexOf(_);
                b !== -1 && this._senders.splice(b, 1)
            }
        }
        const i = a.RTCPeerConnection.prototype.addStream;
        a.RTCPeerConnection.prototype.addStream = function(c) {
            this._senders = this._senders || [],
            i.apply(this, [c]),
            c.getTracks().forEach(d=>{
                this._senders.push(e(this, d))
            }
            )
        }
        ;
        const o = a.RTCPeerConnection.prototype.removeStream;
        a.RTCPeerConnection.prototype.removeStream = function(c) {
            this._senders = this._senders || [],
            o.apply(this, [c]),
            c.getTracks().forEach(d=>{
                const _ = this._senders.find(b=>b.track === d);
                _ && this._senders.splice(this._senders.indexOf(_), 1)
            }
            )
        }
    } else if (typeof a == "object" && a.RTCPeerConnection && "getSenders"in a.RTCPeerConnection.prototype && "createDTMFSender"in a.RTCPeerConnection.prototype && a.RTCRtpSender && !("dtmf"in a.RTCRtpSender.prototype)) {
        const e = a.RTCPeerConnection.prototype.getSenders;
        a.RTCPeerConnection.prototype.getSenders = function() {
            const o = e.apply(this, []);
            return o.forEach(s=>s._pc = this),
            o
        }
        ,
        Object.defineProperty(a.RTCRtpSender.prototype, "dtmf", {
            get() {
                return this._dtmf === void 0 && (this.track.kind === "audio" ? this._dtmf = this._pc.createDTMFSender(this.track) : this._dtmf = null),
                this._dtmf
            }
        })
    }
}
function shimGetStats(a) {
    if (!a.RTCPeerConnection)
        return;
    const e = a.RTCPeerConnection.prototype.getStats;
    a.RTCPeerConnection.prototype.getStats = function() {
        const [o,s,c] = arguments;
        if (arguments.length > 0 && typeof o == "function")
            return e.apply(this, arguments);
        if (e.length === 0 && (arguments.length === 0 || typeof o != "function"))
            return e.apply(this, []);
        const d = function(b) {
            const k = {};
            return b.result().forEach($=>{
                const _e = {
                    id: $.id,
                    timestamp: $.timestamp,
                    type: {
                        localcandidate: "local-candidate",
                        remotecandidate: "remote-candidate"
                    }[$.type] || $.type
                };
                $.names().forEach(et=>{
                    _e[et] = $.stat(et)
                }
                ),
                k[_e.id] = _e
            }
            ),
            k
        }
          , _ = function(b) {
            return new Map(Object.keys(b).map(k=>[k, b[k]]))
        };
        if (arguments.length >= 2) {
            const b = function(k) {
                s(_(d(k)))
            };
            return e.apply(this, [b, o])
        }
        return new Promise((b,k)=>{
            e.apply(this, [function(j) {
                b(_(d(j)))
            }
            , k])
        }
        ).then(s, c)
    }
}
function shimSenderReceiverGetStats(a) {
    if (!(typeof a == "object" && a.RTCPeerConnection && a.RTCRtpSender && a.RTCRtpReceiver))
        return;
    if (!("getStats"in a.RTCRtpSender.prototype)) {
        const i = a.RTCPeerConnection.prototype.getSenders;
        i && (a.RTCPeerConnection.prototype.getSenders = function() {
            const c = i.apply(this, []);
            return c.forEach(d=>d._pc = this),
            c
        }
        );
        const o = a.RTCPeerConnection.prototype.addTrack;
        o && (a.RTCPeerConnection.prototype.addTrack = function() {
            const c = o.apply(this, arguments);
            return c._pc = this,
            c
        }
        ),
        a.RTCRtpSender.prototype.getStats = function() {
            const c = this;
            return this._pc.getStats().then(d=>filterStats(d, c.track, !0))
        }
    }
    if (!("getStats"in a.RTCRtpReceiver.prototype)) {
        const i = a.RTCPeerConnection.prototype.getReceivers;
        i && (a.RTCPeerConnection.prototype.getReceivers = function() {
            const s = i.apply(this, []);
            return s.forEach(c=>c._pc = this),
            s
        }
        ),
        wrapPeerConnectionEvent(a, "track", o=>(o.receiver._pc = o.srcElement,
        o)),
        a.RTCRtpReceiver.prototype.getStats = function() {
            const s = this;
            return this._pc.getStats().then(c=>filterStats(c, s.track, !1))
        }
    }
    if (!("getStats"in a.RTCRtpSender.prototype && "getStats"in a.RTCRtpReceiver.prototype))
        return;
    const e = a.RTCPeerConnection.prototype.getStats;
    a.RTCPeerConnection.prototype.getStats = function() {
        if (arguments.length > 0 && arguments[0]instanceof a.MediaStreamTrack) {
            const o = arguments[0];
            let s, c, d;
            return this.getSenders().forEach(_=>{
                _.track === o && (s ? d = !0 : s = _)
            }
            ),
            this.getReceivers().forEach(_=>(_.track === o && (c ? d = !0 : c = _),
            _.track === o)),
            d || s && c ? Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")) : s ? s.getStats() : c ? c.getStats() : Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))
        }
        return e.apply(this, arguments)
    }
}
function shimAddTrackRemoveTrackWithNative(a) {
    a.RTCPeerConnection.prototype.getLocalStreams = function() {
        return this._shimmedLocalStreams = this._shimmedLocalStreams || {},
        Object.keys(this._shimmedLocalStreams).map(d=>this._shimmedLocalStreams[d][0])
    }
    ;
    const e = a.RTCPeerConnection.prototype.addTrack;
    a.RTCPeerConnection.prototype.addTrack = function(d, _) {
        if (!_)
            return e.apply(this, arguments);
        this._shimmedLocalStreams = this._shimmedLocalStreams || {};
        const b = e.apply(this, arguments);
        return this._shimmedLocalStreams[_.id] ? this._shimmedLocalStreams[_.id].indexOf(b) === -1 && this._shimmedLocalStreams[_.id].push(b) : this._shimmedLocalStreams[_.id] = [_, b],
        b
    }
    ;
    const i = a.RTCPeerConnection.prototype.addStream;
    a.RTCPeerConnection.prototype.addStream = function(d) {
        this._shimmedLocalStreams = this._shimmedLocalStreams || {},
        d.getTracks().forEach(k=>{
            if (this.getSenders().find($=>$.track === k))
                throw new DOMException("Track already exists.","InvalidAccessError")
        }
        );
        const _ = this.getSenders();
        i.apply(this, arguments);
        const b = this.getSenders().filter(k=>_.indexOf(k) === -1);
        this._shimmedLocalStreams[d.id] = [d].concat(b)
    }
    ;
    const o = a.RTCPeerConnection.prototype.removeStream;
    a.RTCPeerConnection.prototype.removeStream = function(d) {
        return this._shimmedLocalStreams = this._shimmedLocalStreams || {},
        delete this._shimmedLocalStreams[d.id],
        o.apply(this, arguments)
    }
    ;
    const s = a.RTCPeerConnection.prototype.removeTrack;
    a.RTCPeerConnection.prototype.removeTrack = function(d) {
        return this._shimmedLocalStreams = this._shimmedLocalStreams || {},
        d && Object.keys(this._shimmedLocalStreams).forEach(_=>{
            const b = this._shimmedLocalStreams[_].indexOf(d);
            b !== -1 && this._shimmedLocalStreams[_].splice(b, 1),
            this._shimmedLocalStreams[_].length === 1 && delete this._shimmedLocalStreams[_]
        }
        ),
        s.apply(this, arguments)
    }
}
function shimAddTrackRemoveTrack(a, e) {
    if (!a.RTCPeerConnection)
        return;
    if (a.RTCPeerConnection.prototype.addTrack && e.version >= 65)
        return shimAddTrackRemoveTrackWithNative(a);
    const i = a.RTCPeerConnection.prototype.getLocalStreams;
    a.RTCPeerConnection.prototype.getLocalStreams = function() {
        const j = i.apply(this);
        return this._reverseStreams = this._reverseStreams || {},
        j.map($=>this._reverseStreams[$.id])
    }
    ;
    const o = a.RTCPeerConnection.prototype.addStream;
    a.RTCPeerConnection.prototype.addStream = function(j) {
        if (this._streams = this._streams || {},
        this._reverseStreams = this._reverseStreams || {},
        j.getTracks().forEach($=>{
            if (this.getSenders().find(et=>et.track === $))
                throw new DOMException("Track already exists.","InvalidAccessError")
        }
        ),
        !this._reverseStreams[j.id]) {
            const $ = new a.MediaStream(j.getTracks());
            this._streams[j.id] = $,
            this._reverseStreams[$.id] = j,
            j = $
        }
        o.apply(this, [j])
    }
    ;
    const s = a.RTCPeerConnection.prototype.removeStream;
    a.RTCPeerConnection.prototype.removeStream = function(j) {
        this._streams = this._streams || {},
        this._reverseStreams = this._reverseStreams || {},
        s.apply(this, [this._streams[j.id] || j]),
        delete this._reverseStreams[this._streams[j.id] ? this._streams[j.id].id : j.id],
        delete this._streams[j.id]
    }
    ,
    a.RTCPeerConnection.prototype.addTrack = function(j, $) {
        if (this.signalingState === "closed")
            throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");
        const _e = [].slice.call(arguments, 1);
        if (_e.length !== 1 || !_e[0].getTracks().find(rt=>rt === j))
            throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");
        if (this.getSenders().find(rt=>rt.track === j))
            throw new DOMException("Track already exists.","InvalidAccessError");
        this._streams = this._streams || {},
        this._reverseStreams = this._reverseStreams || {};
        const tt = this._streams[$.id];
        if (tt)
            tt.addTrack(j),
            Promise.resolve().then(()=>{
                this.dispatchEvent(new Event("negotiationneeded"))
            }
            );
        else {
            const rt = new a.MediaStream([j]);
            this._streams[$.id] = rt,
            this._reverseStreams[rt.id] = $,
            this.addStream(rt)
        }
        return this.getSenders().find(rt=>rt.track === j)
    }
    ;
    function c(k, j) {
        let$ = j.sdp;
        return Object.keys(k._reverseStreams || []).forEach(_e=>{
            const et = k._reverseStreams[_e]
              , tt = k._streams[et.id];
            $ = $.replace(new RegExp(tt.id,"g"), et.id)
        }
        ),
        new RTCSessionDescription({
            type: j.type,
            sdp: $
        })
    }
    function d(k, j) {
        let$ = j.sdp;
        return Object.keys(k._reverseStreams || []).forEach(_e=>{
            const et = k._reverseStreams[_e]
              , tt = k._streams[et.id];
            $ = $.replace(new RegExp(et.id,"g"), tt.id)
        }
        ),
        new RTCSessionDescription({
            type: j.type,
            sdp: $
        })
    }
    ["createOffer", "createAnswer"].forEach(function(k) {
        const j = a.RTCPeerConnection.prototype[k]
          , $ = {
            [k]() {
                const _e = arguments;
                return arguments.length && typeof arguments[0] == "function" ? j.apply(this, [tt=>{
                    const rt = c(this, tt);
                    _e[0].apply(null, [rt])
                }
                , tt=>{
                    _e[1] && _e[1].apply(null, tt)
                }
                , arguments[2]]) : j.apply(this, arguments).then(tt=>c(this, tt))
            }
        };
        a.RTCPeerConnection.prototype[k] = $[k]
    });
    const _ = a.RTCPeerConnection.prototype.setLocalDescription;
    a.RTCPeerConnection.prototype.setLocalDescription = function() {
        return !arguments.length || !arguments[0].type ? _.apply(this, arguments) : (arguments[0] = d(this, arguments[0]),
        _.apply(this, arguments))
    }
    ;
    const b = Object.getOwnPropertyDescriptor(a.RTCPeerConnection.prototype, "localDescription");
    Object.defineProperty(a.RTCPeerConnection.prototype, "localDescription", {
        get() {
            const k = b.get.apply(this);
            return k.type === "" ? k : c(this, k)
        }
    }),
    a.RTCPeerConnection.prototype.removeTrack = function(j) {
        if (this.signalingState === "closed")
            throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");
        if (!j._pc)
            throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");
        if (!(j._pc === this))
            throw new DOMException("Sender was not created by this connection.","InvalidAccessError");
        this._streams = this._streams || {};
        let _e;
        Object.keys(this._streams).forEach(et=>{
            this._streams[et].getTracks().find(rt=>j.track === rt) && (_e = this._streams[et])
        }
        ),
        _e && (_e.getTracks().length === 1 ? this.removeStream(this._reverseStreams[_e.id]) : _e.removeTrack(j.track),
        this.dispatchEvent(new Event("negotiationneeded")))
    }
}
function shimPeerConnection$1(a, e) {
    !a.RTCPeerConnection && a.webkitRTCPeerConnection && (a.RTCPeerConnection = a.webkitRTCPeerConnection),
    !!a.RTCPeerConnection && e.version < 53 && ["setLocalDescription", "setRemoteDescription", "addIceCandidate"].forEach(function(i) {
        const o = a.RTCPeerConnection.prototype[i]
          , s = {
            [i]() {
                return arguments[0] = new (i === "addIceCandidate" ? a.RTCIceCandidate : a.RTCSessionDescription)(arguments[0]),
                o.apply(this, arguments)
            }
        };
        a.RTCPeerConnection.prototype[i] = s[i]
    })
}
function fixNegotiationNeeded(a, e) {
    wrapPeerConnectionEvent(a, "negotiationneeded", i=>{
        const o = i.target;
        if (!((e.version < 72 || o.getConfiguration && o.getConfiguration().sdpSemantics === "plan-b") && o.signalingState !== "stable"))
            return i
    }
    )
}
var chromeShim = Object.freeze(Object.defineProperty({
    __proto__: null,
    shimMediaStream,
    shimOnTrack: shimOnTrack$1,
    shimGetSendersWithDtmf,
    shimGetStats,
    shimSenderReceiverGetStats,
    shimAddTrackRemoveTrackWithNative,
    shimAddTrackRemoveTrack,
    shimPeerConnection: shimPeerConnection$1,
    fixNegotiationNeeded,
    shimGetUserMedia: shimGetUserMedia$2,
    shimGetDisplayMedia: shimGetDisplayMedia$1
}, Symbol.toStringTag, {
    value: "Module"
}));
function shimGetUserMedia$1(a, e) {
    const i = a && a.navigator
      , o = a && a.MediaStreamTrack;
    if (i.getUserMedia = function(s, c, d) {
        deprecated("navigator.getUserMedia", "navigator.mediaDevices.getUserMedia"),
        i.mediaDevices.getUserMedia(s).then(c, d)
    }
    ,
    !(e.version > 55 && "autoGainControl"in i.mediaDevices.getSupportedConstraints())) {
        const s = function(d, _, b) {
            _ in d && !(b in d) && (d[b] = d[_],
            delete d[_])
        }
          , c = i.mediaDevices.getUserMedia.bind(i.mediaDevices);
        if (i.mediaDevices.getUserMedia = function(d) {
            return typeof d == "object" && typeof d.audio == "object" && (d = JSON.parse(JSON.stringify(d)),
            s(d.audio, "autoGainControl", "mozAutoGainControl"),
            s(d.audio, "noiseSuppression", "mozNoiseSuppression")),
            c(d)
        }
        ,
        o && o.prototype.getSettings) {
            const d = o.prototype.getSettings;
            o.prototype.getSettings = function() {
                const _ = d.apply(this, arguments);
                return s(_, "mozAutoGainControl", "autoGainControl"),
                s(_, "mozNoiseSuppression", "noiseSuppression"),
                _
            }
        }
        if (o && o.prototype.applyConstraints) {
            const d = o.prototype.applyConstraints;
            o.prototype.applyConstraints = function(_) {
                return this.kind === "audio" && typeof _ == "object" && (_ = JSON.parse(JSON.stringify(_)),
                s(_, "autoGainControl", "mozAutoGainControl"),
                s(_, "noiseSuppression", "mozNoiseSuppression")),
                d.apply(this, [_])
            }
        }
    }
}
function shimGetDisplayMedia(a, e) {
    a.navigator.mediaDevices && "getDisplayMedia"in a.navigator.mediaDevices || !a.navigator.mediaDevices || (a.navigator.mediaDevices.getDisplayMedia = function(o) {
        if (!(o && o.video)) {
            const s = new DOMException("getDisplayMedia without video constraints is undefined");
            return s.name = "NotFoundError",
            s.code = 8,
            Promise.reject(s)
        }
        return o.video === !0 ? o.video = {
            mediaSource: e
        } : o.video.mediaSource = e,
        a.navigator.mediaDevices.getUserMedia(o)
    }
    )
}
function shimOnTrack(a) {
    typeof a == "object" && a.RTCTrackEvent && "receiver"in a.RTCTrackEvent.prototype && !("transceiver"in a.RTCTrackEvent.prototype) && Object.defineProperty(a.RTCTrackEvent.prototype, "transceiver", {
        get() {
            return {
                receiver: this.receiver
            }
        }
    })
}
function shimPeerConnection(a, e) {
    if (typeof a != "object" || !(a.RTCPeerConnection || a.mozRTCPeerConnection))
        return;
    !a.RTCPeerConnection && a.mozRTCPeerConnection && (a.RTCPeerConnection = a.mozRTCPeerConnection),
    e.version < 53 && ["setLocalDescription", "setRemoteDescription", "addIceCandidate"].forEach(function(s) {
        const c = a.RTCPeerConnection.prototype[s]
          , d = {
            [s]() {
                return arguments[0] = new (s === "addIceCandidate" ? a.RTCIceCandidate : a.RTCSessionDescription)(arguments[0]),
                c.apply(this, arguments)
            }
        };
        a.RTCPeerConnection.prototype[s] = d[s]
    });
    const i = {
        inboundrtp: "inbound-rtp",
        outboundrtp: "outbound-rtp",
        candidatepair: "candidate-pair",
        localcandidate: "local-candidate",
        remotecandidate: "remote-candidate"
    }
      , o = a.RTCPeerConnection.prototype.getStats;
    a.RTCPeerConnection.prototype.getStats = function() {
        const [c,d,_] = arguments;
        return o.apply(this, [c || null]).then(b=>{
            if (e.version < 53 && !d)
                try {
                    b.forEach(k=>{
                        k.type = i[k.type] || k.type
                    }
                    )
                } catch (k) {
                    if (k.name !== "TypeError")
                        throw k;
                    b.forEach((j,$)=>{
                        b.set($, Object.assign({}, j, {
                            type: i[j.type] || j.type
                        }))
                    }
                    )
                }
            return b
        }
        ).then(d, _)
    }
}
function shimSenderGetStats(a) {
    if (!(typeof a == "object" && a.RTCPeerConnection && a.RTCRtpSender) || a.RTCRtpSender && "getStats"in a.RTCRtpSender.prototype)
        return;
    const e = a.RTCPeerConnection.prototype.getSenders;
    e && (a.RTCPeerConnection.prototype.getSenders = function() {
        const s = e.apply(this, []);
        return s.forEach(c=>c._pc = this),
        s
    }
    );
    const i = a.RTCPeerConnection.prototype.addTrack;
    i && (a.RTCPeerConnection.prototype.addTrack = function() {
        const s = i.apply(this, arguments);
        return s._pc = this,
        s
    }
    ),
    a.RTCRtpSender.prototype.getStats = function() {
        return this.track ? this._pc.getStats(this.track) : Promise.resolve(new Map)
    }
}
function shimReceiverGetStats(a) {
    if (!(typeof a == "object" && a.RTCPeerConnection && a.RTCRtpSender) || a.RTCRtpSender && "getStats"in a.RTCRtpReceiver.prototype)
        return;
    const e = a.RTCPeerConnection.prototype.getReceivers;
    e && (a.RTCPeerConnection.prototype.getReceivers = function() {
        const o = e.apply(this, []);
        return o.forEach(s=>s._pc = this),
        o
    }
    ),
    wrapPeerConnectionEvent(a, "track", i=>(i.receiver._pc = i.srcElement,
    i)),
    a.RTCRtpReceiver.prototype.getStats = function() {
        return this._pc.getStats(this.track)
    }
}
function shimRemoveStream(a) {
    !a.RTCPeerConnection || "removeStream"in a.RTCPeerConnection.prototype || (a.RTCPeerConnection.prototype.removeStream = function(i) {
        deprecated("removeStream", "removeTrack"),
        this.getSenders().forEach(o=>{
            o.track && i.getTracks().includes(o.track) && this.removeTrack(o)
        }
        )
    }
    )
}
function shimRTCDataChannel(a) {
    a.DataChannel && !a.RTCDataChannel && (a.RTCDataChannel = a.DataChannel)
}
function shimAddTransceiver(a) {
    if (!(typeof a == "object" && a.RTCPeerConnection))
        return;
    const e = a.RTCPeerConnection.prototype.addTransceiver;
    e && (a.RTCPeerConnection.prototype.addTransceiver = function() {
        this.setParametersPromises = [];
        const o = arguments[1]
          , s = o && "sendEncodings"in o;
        s && o.sendEncodings.forEach(d=>{
            if ("rid"in d && !/^[a-z0-9]{0,16}$/i.test(d.rid))
                throw new TypeError("Invalid RID value provided.");
            if ("scaleResolutionDownBy"in d && !(parseFloat(d.scaleResolutionDownBy) >= 1))
                throw new RangeError("scale_resolution_down_by must be >= 1.0");
            if ("maxFramerate"in d && !(parseFloat(d.maxFramerate) >= 0))
                throw new RangeError("max_framerate must be >= 0.0")
        }
        );
        const c = e.apply(this, arguments);
        if (s) {
            const {sender: d} = c
              , _ = d.getParameters();
            (!("encodings"in _) || _.encodings.length === 1 && Object.keys(_.encodings[0]).length === 0) && (_.encodings = o.sendEncodings,
            d.sendEncodings = o.sendEncodings,
            this.setParametersPromises.push(d.setParameters(_).then(()=>{
                delete d.sendEncodings
            }
            ).catch(()=>{
                delete d.sendEncodings
            }
            )))
        }
        return c
    }
    )
}
function shimGetParameters(a) {
    if (!(typeof a == "object" && a.RTCRtpSender))
        return;
    const e = a.RTCRtpSender.prototype.getParameters;
    e && (a.RTCRtpSender.prototype.getParameters = function() {
        const o = e.apply(this, arguments);
        return "encodings"in o || (o.encodings = [].concat(this.sendEncodings || [{}])),
        o
    }
    )
}
function shimCreateOffer(a) {
    if (!(typeof a == "object" && a.RTCPeerConnection))
        return;
    const e = a.RTCPeerConnection.prototype.createOffer;
    a.RTCPeerConnection.prototype.createOffer = function() {
        return this.setParametersPromises && this.setParametersPromises.length ? Promise.all(this.setParametersPromises).then(()=>e.apply(this, arguments)).finally(()=>{
            this.setParametersPromises = []
        }
        ) : e.apply(this, arguments)
    }
}
function shimCreateAnswer(a) {
    if (!(typeof a == "object" && a.RTCPeerConnection))
        return;
    const e = a.RTCPeerConnection.prototype.createAnswer;
    a.RTCPeerConnection.prototype.createAnswer = function() {
        return this.setParametersPromises && this.setParametersPromises.length ? Promise.all(this.setParametersPromises).then(()=>e.apply(this, arguments)).finally(()=>{
            this.setParametersPromises = []
        }
        ) : e.apply(this, arguments)
    }
}
var firefoxShim = Object.freeze(Object.defineProperty({
    __proto__: null,
    shimOnTrack,
    shimPeerConnection,
    shimSenderGetStats,
    shimReceiverGetStats,
    shimRemoveStream,
    shimRTCDataChannel,
    shimAddTransceiver,
    shimGetParameters,
    shimCreateOffer,
    shimCreateAnswer,
    shimGetUserMedia: shimGetUserMedia$1,
    shimGetDisplayMedia
}, Symbol.toStringTag, {
    value: "Module"
}));
function shimLocalStreamsAPI(a) {
    if (!(typeof a != "object" || !a.RTCPeerConnection)) {
        if ("getLocalStreams"in a.RTCPeerConnection.prototype || (a.RTCPeerConnection.prototype.getLocalStreams = function() {
            return this._localStreams || (this._localStreams = []),
            this._localStreams
        }
        ),
        !("addStream"in a.RTCPeerConnection.prototype)) {
            const e = a.RTCPeerConnection.prototype.addTrack;
            a.RTCPeerConnection.prototype.addStream = function(o) {
                this._localStreams || (this._localStreams = []),
                this._localStreams.includes(o) || this._localStreams.push(o),
                o.getAudioTracks().forEach(s=>e.call(this, s, o)),
                o.getVideoTracks().forEach(s=>e.call(this, s, o))
            }
            ,
            a.RTCPeerConnection.prototype.addTrack = function(o, ...s) {
                return s && s.forEach(c=>{
                    this._localStreams ? this._localStreams.includes(c) || this._localStreams.push(c) : this._localStreams = [c]
                }
                ),
                e.apply(this, arguments)
            }
        }
        "removeStream"in a.RTCPeerConnection.prototype || (a.RTCPeerConnection.prototype.removeStream = function(i) {
            this._localStreams || (this._localStreams = []);
            const o = this._localStreams.indexOf(i);
            if (o === -1)
                return;
            this._localStreams.splice(o, 1);
            const s = i.getTracks();
            this.getSenders().forEach(c=>{
                s.includes(c.track) && this.removeTrack(c)
            }
            )
        }
        )
    }
}
function shimRemoteStreamsAPI(a) {
    if (!(typeof a != "object" || !a.RTCPeerConnection) && ("getRemoteStreams"in a.RTCPeerConnection.prototype || (a.RTCPeerConnection.prototype.getRemoteStreams = function() {
        return this._remoteStreams ? this._remoteStreams : []
    }
    ),
    !("onaddstream"in a.RTCPeerConnection.prototype))) {
        Object.defineProperty(a.RTCPeerConnection.prototype, "onaddstream", {
            get() {
                return this._onaddstream
            },
            set(i) {
                this._onaddstream && (this.removeEventListener("addstream", this._onaddstream),
                this.removeEventListener("track", this._onaddstreampoly)),
                this.addEventListener("addstream", this._onaddstream = i),
                this.addEventListener("track", this._onaddstreampoly = o=>{
                    o.streams.forEach(s=>{
                        if (this._remoteStreams || (this._remoteStreams = []),
                        this._remoteStreams.includes(s))
                            return;
                        this._remoteStreams.push(s);
                        const c = new Event("addstream");
                        c.stream = s,
                        this.dispatchEvent(c)
                    }
                    )
                }
                )
            }
        });
        const e = a.RTCPeerConnection.prototype.setRemoteDescription;
        a.RTCPeerConnection.prototype.setRemoteDescription = function() {
            const o = this;
            return this._onaddstreampoly || this.addEventListener("track", this._onaddstreampoly = function(s) {
                s.streams.forEach(c=>{
                    if (o._remoteStreams || (o._remoteStreams = []),
                    o._remoteStreams.indexOf(c) >= 0)
                        return;
                    o._remoteStreams.push(c);
                    const d = new Event("addstream");
                    d.stream = c,
                    o.dispatchEvent(d)
                }
                )
            }
            ),
            e.apply(o, arguments)
        }
    }
}
function shimCallbacksAPI(a) {
    if (typeof a != "object" || !a.RTCPeerConnection)
        return;
    const e = a.RTCPeerConnection.prototype
      , i = e.createOffer
      , o = e.createAnswer
      , s = e.setLocalDescription
      , c = e.setRemoteDescription
      , d = e.addIceCandidate;
    e.createOffer = function(k, j) {
        const $ = arguments.length >= 2 ? arguments[2] : arguments[0]
          , _e = i.apply(this, [$]);
        return j ? (_e.then(k, j),
        Promise.resolve()) : _e
    }
    ,
    e.createAnswer = function(k, j) {
        const $ = arguments.length >= 2 ? arguments[2] : arguments[0]
          , _e = o.apply(this, [$]);
        return j ? (_e.then(k, j),
        Promise.resolve()) : _e
    }
    ;
    let _ = function(b, k, j) {
        const $ = s.apply(this, [b]);
        return j ? ($.then(k, j),
        Promise.resolve()) : $
    };
    e.setLocalDescription = _,
    _ = function(b, k, j) {
        const $ = c.apply(this, [b]);
        return j ? ($.then(k, j),
        Promise.resolve()) : $
    }
    ,
    e.setRemoteDescription = _,
    _ = function(b, k, j) {
        const $ = d.apply(this, [b]);
        return j ? ($.then(k, j),
        Promise.resolve()) : $
    }
    ,
    e.addIceCandidate = _
}
function shimGetUserMedia(a) {
    const e = a && a.navigator;
    if (e.mediaDevices && e.mediaDevices.getUserMedia) {
        const i = e.mediaDevices
          , o = i.getUserMedia.bind(i);
        e.mediaDevices.getUserMedia = s=>o(shimConstraints(s))
    }
    !e.getUserMedia && e.mediaDevices && e.mediaDevices.getUserMedia && (e.getUserMedia = function(o, s, c) {
        e.mediaDevices.getUserMedia(o).then(s, c)
    }
    .bind(e))
}
function shimConstraints(a) {
    return a && a.video !== void 0 ? Object.assign({}, a, {
        video: compactObject(a.video)
    }) : a
}
function shimRTCIceServerUrls(a) {
    if (!a.RTCPeerConnection)
        return;
    const e = a.RTCPeerConnection;
    a.RTCPeerConnection = function(o, s) {
        if (o && o.iceServers) {
            const c = [];
            for (let d = 0; d < o.iceServers.length; d++) {
                let _ = o.iceServers[d];
                !_.hasOwnProperty("urls") && _.hasOwnProperty("url") ? (deprecated("RTCIceServer.url", "RTCIceServer.urls"),
                _ = JSON.parse(JSON.stringify(_)),
                _.urls = _.url,
                delete _.url,
                c.push(_)) : c.push(o.iceServers[d])
            }
            o.iceServers = c
        }
        return new e(o,s)
    }
    ,
    a.RTCPeerConnection.prototype = e.prototype,
    "generateCertificate"in e && Object.defineProperty(a.RTCPeerConnection, "generateCertificate", {
        get() {
            return e.generateCertificate
        }
    })
}
function shimTrackEventTransceiver(a) {
    typeof a == "object" && a.RTCTrackEvent && "receiver"in a.RTCTrackEvent.prototype && !("transceiver"in a.RTCTrackEvent.prototype) && Object.defineProperty(a.RTCTrackEvent.prototype, "transceiver", {
        get() {
            return {
                receiver: this.receiver
            }
        }
    })
}
function shimCreateOfferLegacy(a) {
    const e = a.RTCPeerConnection.prototype.createOffer;
    a.RTCPeerConnection.prototype.createOffer = function(o) {
        if (o) {
            typeof o.offerToReceiveAudio != "undefined" && (o.offerToReceiveAudio = !!o.offerToReceiveAudio);
            const s = this.getTransceivers().find(d=>d.receiver.track.kind === "audio");
            o.offerToReceiveAudio === !1 && s ? s.direction === "sendrecv" ? s.setDirection ? s.setDirection("sendonly") : s.direction = "sendonly" : s.direction === "recvonly" && (s.setDirection ? s.setDirection("inactive") : s.direction = "inactive") : o.offerToReceiveAudio === !0 && !s && this.addTransceiver("audio", {
                direction: "recvonly"
            }),
            typeof o.offerToReceiveVideo != "undefined" && (o.offerToReceiveVideo = !!o.offerToReceiveVideo);
            const c = this.getTransceivers().find(d=>d.receiver.track.kind === "video");
            o.offerToReceiveVideo === !1 && c ? c.direction === "sendrecv" ? c.setDirection ? c.setDirection("sendonly") : c.direction = "sendonly" : c.direction === "recvonly" && (c.setDirection ? c.setDirection("inactive") : c.direction = "inactive") : o.offerToReceiveVideo === !0 && !c && this.addTransceiver("video", {
                direction: "recvonly"
            })
        }
        return e.apply(this, arguments)
    }
}
function shimAudioContext(a) {
    typeof a != "object" || a.AudioContext || (a.AudioContext = a.webkitAudioContext)
}
var safariShim = Object.freeze(Object.defineProperty({
    __proto__: null,
    shimLocalStreamsAPI,
    shimRemoteStreamsAPI,
    shimCallbacksAPI,
    shimGetUserMedia,
    shimConstraints,
    shimRTCIceServerUrls,
    shimTrackEventTransceiver,
    shimCreateOfferLegacy,
    shimAudioContext
}, Symbol.toStringTag, {
    value: "Module"
}))
  , sdp$1 = {
    exports: {}
};
(function(a) {
    const e = {};
    e.generateIdentifier = function() {
        return Math.random().toString(36).substr(2, 10)
    }
    ,
    e.localCName = e.generateIdentifier(),
    e.splitLines = function(i) {
        return i.trim().split(`
`).map(o=>o.trim())
    }
    ,
    e.splitSections = function(i) {
        return i.split(`
m=`).map((s,c)=>(c > 0 ? "m=" + s : s).trim() + `\r
`)
    }
    ,
    e.getDescription = function(i) {
        const o = e.splitSections(i);
        return o && o[0]
    }
    ,
    e.getMediaSections = function(i) {
        const o = e.splitSections(i);
        return o.shift(),
        o
    }
    ,
    e.matchPrefix = function(i, o) {
        return e.splitLines(i).filter(s=>s.indexOf(o) === 0)
    }
    ,
    e.parseCandidate = function(i) {
        let o;
        i.indexOf("a=candidate:") === 0 ? o = i.substring(12).split(" ") : o = i.substring(10).split(" ");
        const s = {
            foundation: o[0],
            component: {
                1: "rtp",
                2: "rtcp"
            }[o[1]] || o[1],
            protocol: o[2].toLowerCase(),
            priority: parseInt(o[3], 10),
            ip: o[4],
            address: o[4],
            port: parseInt(o[5], 10),
            type: o[7]
        };
        for (let c = 8; c < o.length; c += 2)
            switch (o[c]) {
            case "raddr":
                s.relatedAddress = o[c + 1];
                break;
            case "rport":
                s.relatedPort = parseInt(o[c + 1], 10);
                break;
            case "tcptype":
                s.tcpType = o[c + 1];
                break;
            case "ufrag":
                s.ufrag = o[c + 1],
                s.usernameFragment = o[c + 1];
                break;
            default:
                s[o[c]] === void 0 && (s[o[c]] = o[c + 1]);
                break
            }
        return s
    }
    ,
    e.writeCandidate = function(i) {
        const o = [];
        o.push(i.foundation);
        const s = i.component;
        s === "rtp" ? o.push(1) : s === "rtcp" ? o.push(2) : o.push(s),
        o.push(i.protocol.toUpperCase()),
        o.push(i.priority),
        o.push(i.address || i.ip),
        o.push(i.port);
        const c = i.type;
        return o.push("typ"),
        o.push(c),
        c !== "host" && i.relatedAddress && i.relatedPort && (o.push("raddr"),
        o.push(i.relatedAddress),
        o.push("rport"),
        o.push(i.relatedPort)),
        i.tcpType && i.protocol.toLowerCase() === "tcp" && (o.push("tcptype"),
        o.push(i.tcpType)),
        (i.usernameFragment || i.ufrag) && (o.push("ufrag"),
        o.push(i.usernameFragment || i.ufrag)),
        "candidate:" + o.join(" ")
    }
    ,
    e.parseIceOptions = function(i) {
        return i.substr(14).split(" ")
    }
    ,
    e.parseRtpMap = function(i) {
        let o = i.substr(9).split(" ");
        const s = {
            payloadType: parseInt(o.shift(), 10)
        };
        return o = o[0].split("/"),
        s.name = o[0],
        s.clockRate = parseInt(o[1], 10),
        s.channels = o.length === 3 ? parseInt(o[2], 10) : 1,
        s.numChannels = s.channels,
        s
    }
    ,
    e.writeRtpMap = function(i) {
        let o = i.payloadType;
        i.preferredPayloadType !== void 0 && (o = i.preferredPayloadType);
        const s = i.channels || i.numChannels || 1;
        return "a=rtpmap:" + o + " " + i.name + "/" + i.clockRate + (s !== 1 ? "/" + s : "") + `\r
`
    }
    ,
    e.parseExtmap = function(i) {
        const o = i.substr(9).split(" ");
        return {
            id: parseInt(o[0], 10),
            direction: o[0].indexOf("/") > 0 ? o[0].split("/")[1] : "sendrecv",
            uri: o[1]
        }
    }
    ,
    e.writeExtmap = function(i) {
        return "a=extmap:" + (i.id || i.preferredId) + (i.direction && i.direction !== "sendrecv" ? "/" + i.direction : "") + " " + i.uri + `\r
`
    }
    ,
    e.parseFmtp = function(i) {
        const o = {};
        let s;
        const c = i.substr(i.indexOf(" ") + 1).split(";");
        for (let d = 0; d < c.length; d++)
            s = c[d].trim().split("="),
            o[s[0].trim()] = s[1];
        return o
    }
    ,
    e.writeFmtp = function(i) {
        let o = ""
          , s = i.payloadType;
        if (i.preferredPayloadType !== void 0 && (s = i.preferredPayloadType),
        i.parameters && Object.keys(i.parameters).length) {
            const c = [];
            Object.keys(i.parameters).forEach(d=>{
                i.parameters[d] !== void 0 ? c.push(d + "=" + i.parameters[d]) : c.push(d)
            }
            ),
            o += "a=fmtp:" + s + " " + c.join(";") + `\r
`
        }
        return o
    }
    ,
    e.parseRtcpFb = function(i) {
        const o = i.substr(i.indexOf(" ") + 1).split(" ");
        return {
            type: o.shift(),
            parameter: o.join(" ")
        }
    }
    ,
    e.writeRtcpFb = function(i) {
        let o = ""
          , s = i.payloadType;
        return i.preferredPayloadType !== void 0 && (s = i.preferredPayloadType),
        i.rtcpFeedback && i.rtcpFeedback.length && i.rtcpFeedback.forEach(c=>{
            o += "a=rtcp-fb:" + s + " " + c.type + (c.parameter && c.parameter.length ? " " + c.parameter : "") + `\r
`
        }
        ),
        o
    }
    ,
    e.parseSsrcMedia = function(i) {
        const o = i.indexOf(" ")
          , s = {
            ssrc: parseInt(i.substr(7, o - 7), 10)
        }
          , c = i.indexOf(":", o);
        return c > -1 ? (s.attribute = i.substr(o + 1, c - o - 1),
        s.value = i.substr(c + 1)) : s.attribute = i.substr(o + 1),
        s
    }
    ,
    e.parseSsrcGroup = function(i) {
        const o = i.substr(13).split(" ");
        return {
            semantics: o.shift(),
            ssrcs: o.map(s=>parseInt(s, 10))
        }
    }
    ,
    e.getMid = function(i) {
        const o = e.matchPrefix(i, "a=mid:")[0];
        if (o)
            return o.substr(6)
    }
    ,
    e.parseFingerprint = function(i) {
        const o = i.substr(14).split(" ");
        return {
            algorithm: o[0].toLowerCase(),
            value: o[1].toUpperCase()
        }
    }
    ,
    e.getDtlsParameters = function(i, o) {
        const s = e.matchPrefix(i + o, "a=fingerprint:");
        return {
            role: "auto",
            fingerprints: s.map(e.parseFingerprint)
        }
    }
    ,
    e.writeDtlsParameters = function(i, o) {
        let s = "a=setup:" + o + `\r
`;
        return i.fingerprints.forEach(c=>{
            s += "a=fingerprint:" + c.algorithm + " " + c.value + `\r
`
        }
        ),
        s
    }
    ,
    e.parseCryptoLine = function(i) {
        const o = i.substr(9).split(" ");
        return {
            tag: parseInt(o[0], 10),
            cryptoSuite: o[1],
            keyParams: o[2],
            sessionParams: o.slice(3)
        }
    }
    ,
    e.writeCryptoLine = function(i) {
        return "a=crypto:" + i.tag + " " + i.cryptoSuite + " " + (typeof i.keyParams == "object" ? e.writeCryptoKeyParams(i.keyParams) : i.keyParams) + (i.sessionParams ? " " + i.sessionParams.join(" ") : "") + `\r
`
    }
    ,
    e.parseCryptoKeyParams = function(i) {
        if (i.indexOf("inline:") !== 0)
            return null;
        const o = i.substr(7).split("|");
        return {
            keyMethod: "inline",
            keySalt: o[0],
            lifeTime: o[1],
            mkiValue: o[2] ? o[2].split(":")[0] : void 0,
            mkiLength: o[2] ? o[2].split(":")[1] : void 0
        }
    }
    ,
    e.writeCryptoKeyParams = function(i) {
        return i.keyMethod + ":" + i.keySalt + (i.lifeTime ? "|" + i.lifeTime : "") + (i.mkiValue && i.mkiLength ? "|" + i.mkiValue + ":" + i.mkiLength : "")
    }
    ,
    e.getCryptoParameters = function(i, o) {
        return e.matchPrefix(i + o, "a=crypto:").map(e.parseCryptoLine)
    }
    ,
    e.getIceParameters = function(i, o) {
        const s = e.matchPrefix(i + o, "a=ice-ufrag:")[0]
          , c = e.matchPrefix(i + o, "a=ice-pwd:")[0];
        return s && c ? {
            usernameFragment: s.substr(12),
            password: c.substr(10)
        } : null
    }
    ,
    e.writeIceParameters = function(i) {
        let o = "a=ice-ufrag:" + i.usernameFragment + `\r
a=ice-pwd:` + i.password + `\r
`;
        return i.iceLite && (o += `a=ice-lite\r
`),
        o
    }
    ,
    e.parseRtpParameters = function(i) {
        const o = {
            codecs: [],
            headerExtensions: [],
            fecMechanisms: [],
            rtcp: []
        }
          , c = e.splitLines(i)[0].split(" ");
        for (let d = 3; d < c.length; d++) {
            const _ = c[d]
              , b = e.matchPrefix(i, "a=rtpmap:" + _ + " ")[0];
            if (b) {
                const k = e.parseRtpMap(b)
                  , j = e.matchPrefix(i, "a=fmtp:" + _ + " ");
                switch (k.parameters = j.length ? e.parseFmtp(j[0]) : {},
                k.rtcpFeedback = e.matchPrefix(i, "a=rtcp-fb:" + _ + " ").map(e.parseRtcpFb),
                o.codecs.push(k),
                k.name.toUpperCase()) {
                case "RED":
                case "ULPFEC":
                    o.fecMechanisms.push(k.name.toUpperCase());
                    break
                }
            }
        }
        return e.matchPrefix(i, "a=extmap:").forEach(d=>{
            o.headerExtensions.push(e.parseExtmap(d))
        }
        ),
        o
    }
    ,
    e.writeRtpDescription = function(i, o) {
        let s = "";
        s += "m=" + i + " ",
        s += o.codecs.length > 0 ? "9" : "0",
        s += " UDP/TLS/RTP/SAVPF ",
        s += o.codecs.map(d=>d.preferredPayloadType !== void 0 ? d.preferredPayloadType : d.payloadType).join(" ") + `\r
`,
        s += `c=IN IP4 0.0.0.0\r
`,
        s += `a=rtcp:9 IN IP4 0.0.0.0\r
`,
        o.codecs.forEach(d=>{
            s += e.writeRtpMap(d),
            s += e.writeFmtp(d),
            s += e.writeRtcpFb(d)
        }
        );
        let c = 0;
        return o.codecs.forEach(d=>{
            d.maxptime > c && (c = d.maxptime)
        }
        ),
        c > 0 && (s += "a=maxptime:" + c + `\r
`),
        o.headerExtensions && o.headerExtensions.forEach(d=>{
            s += e.writeExtmap(d)
        }
        ),
        s
    }
    ,
    e.parseRtpEncodingParameters = function(i) {
        const o = []
          , s = e.parseRtpParameters(i)
          , c = s.fecMechanisms.indexOf("RED") !== -1
          , d = s.fecMechanisms.indexOf("ULPFEC") !== -1
          , _ = e.matchPrefix(i, "a=ssrc:").map(_e=>e.parseSsrcMedia(_e)).filter(_e=>_e.attribute === "cname")
          , b = _.length > 0 && _[0].ssrc;
        let k;
        const j = e.matchPrefix(i, "a=ssrc-group:FID").map(_e=>_e.substr(17).split(" ").map(tt=>parseInt(tt, 10)));
        j.length > 0 && j[0].length > 1 && j[0][0] === b && (k = j[0][1]),
        s.codecs.forEach(_e=>{
            if (_e.name.toUpperCase() === "RTX" && _e.parameters.apt) {
                let et = {
                    ssrc: b,
                    codecPayloadType: parseInt(_e.parameters.apt, 10)
                };
                b && k && (et.rtx = {
                    ssrc: k
                }),
                o.push(et),
                c && (et = JSON.parse(JSON.stringify(et)),
                et.fec = {
                    ssrc: b,
                    mechanism: d ? "red+ulpfec" : "red"
                },
                o.push(et))
            }
        }
        ),
        o.length === 0 && b && o.push({
            ssrc: b
        });
        let$ = e.matchPrefix(i, "b=");
        return $.length && ($[0].indexOf("b=TIAS:") === 0 ? $ = parseInt($[0].substr(7), 10) : $[0].indexOf("b=AS:") === 0 ? $ = parseInt($[0].substr(5), 10) * 1e3 * .95 - 50 * 40 * 8 : $ = void 0,
        o.forEach(_e=>{
            _e.maxBitrate = $
        }
        )),
        o
    }
    ,
    e.parseRtcpParameters = function(i) {
        const o = {}
          , s = e.matchPrefix(i, "a=ssrc:").map(_=>e.parseSsrcMedia(_)).filter(_=>_.attribute === "cname")[0];
        s && (o.cname = s.value,
        o.ssrc = s.ssrc);
        const c = e.matchPrefix(i, "a=rtcp-rsize");
        o.reducedSize = c.length > 0,
        o.compound = c.length === 0;
        const d = e.matchPrefix(i, "a=rtcp-mux");
        return o.mux = d.length > 0,
        o
    }
    ,
    e.writeRtcpParameters = function(i) {
        let o = "";
        return i.reducedSize && (o += `a=rtcp-rsize\r
`),
        i.mux && (o += `a=rtcp-mux\r
`),
        i.ssrc !== void 0 && i.cname && (o += "a=ssrc:" + i.ssrc + " cname:" + i.cname + `\r
`),
        o
    }
    ,
    e.parseMsid = function(i) {
        let o;
        const s = e.matchPrefix(i, "a=msid:");
        if (s.length === 1)
            return o = s[0].substr(7).split(" "),
            {
                stream: o[0],
                track: o[1]
            };
        const c = e.matchPrefix(i, "a=ssrc:").map(d=>e.parseSsrcMedia(d)).filter(d=>d.attribute === "msid");
        if (c.length > 0)
            return o = c[0].value.split(" "),
            {
                stream: o[0],
                track: o[1]
            }
    }
    ,
    e.parseSctpDescription = function(i) {
        const o = e.parseMLine(i)
          , s = e.matchPrefix(i, "a=max-message-size:");
        let c;
        s.length > 0 && (c = parseInt(s[0].substr(19), 10)),
        isNaN(c) && (c = 65536);
        const d = e.matchPrefix(i, "a=sctp-port:");
        if (d.length > 0)
            return {
                port: parseInt(d[0].substr(12), 10),
                protocol: o.fmt,
                maxMessageSize: c
            };
        const _ = e.matchPrefix(i, "a=sctpmap:");
        if (_.length > 0) {
            const b = _[0].substr(10).split(" ");
            return {
                port: parseInt(b[0], 10),
                protocol: b[1],
                maxMessageSize: c
            }
        }
    }
    ,
    e.writeSctpDescription = function(i, o) {
        let s = [];
        return i.protocol !== "DTLS/SCTP" ? s = ["m=" + i.kind + " 9 " + i.protocol + " " + o.protocol + `\r
`, `c=IN IP4 0.0.0.0\r
`, "a=sctp-port:" + o.port + `\r
`] : s = ["m=" + i.kind + " 9 " + i.protocol + " " + o.port + `\r
`, `c=IN IP4 0.0.0.0\r
`, "a=sctpmap:" + o.port + " " + o.protocol + ` 65535\r
`],
        o.maxMessageSize !== void 0 && s.push("a=max-message-size:" + o.maxMessageSize + `\r
`),
        s.join("")
    }
    ,
    e.generateSessionId = function() {
        return Math.random().toString().substr(2, 21)
    }
    ,
    e.writeSessionBoilerplate = function(i, o, s) {
        let c;
        const d = o !== void 0 ? o : 2;
        return i ? c = i : c = e.generateSessionId(),
        `v=0\r
o=` + (s || "thisisadapterortc") + " " + c + " " + d + ` IN IP4 127.0.0.1\r
s=-\r
t=0 0\r
`
    }
    ,
    e.getDirection = function(i, o) {
        const s = e.splitLines(i);
        for (let c = 0; c < s.length; c++)
            switch (s[c]) {
            case "a=sendrecv":
            case "a=sendonly":
            case "a=recvonly":
            case "a=inactive":
                return s[c].substr(2)
            }
        return o ? e.getDirection(o) : "sendrecv"
    }
    ,
    e.getKind = function(i) {
        return e.splitLines(i)[0].split(" ")[0].substr(2)
    }
    ,
    e.isRejected = function(i) {
        return i.split(" ", 2)[1] === "0"
    }
    ,
    e.parseMLine = function(i) {
        const s = e.splitLines(i)[0].substr(2).split(" ");
        return {
            kind: s[0],
            port: parseInt(s[1], 10),
            protocol: s[2],
            fmt: s.slice(3).join(" ")
        }
    }
    ,
    e.parseOLine = function(i) {
        const s = e.matchPrefix(i, "o=")[0].substr(2).split(" ");
        return {
            username: s[0],
            sessionId: s[1],
            sessionVersion: parseInt(s[2], 10),
            netType: s[3],
            addressType: s[4],
            address: s[5]
        }
    }
    ,
    e.isValidSDP = function(i) {
        if (typeof i != "string" || i.length === 0)
            return !1;
        const o = e.splitLines(i);
        for (let s = 0; s < o.length; s++)
            if (o[s].length < 2 || o[s].charAt(1) !== "=")
                return !1;
        return !0
    }
    ,
    a.exports = e
}
)(sdp$1);
var SDPUtils = sdp$1.exports
  , sdp = _mergeNamespaces({
    __proto__: null,
    default: SDPUtils
}, [sdp$1.exports]);
function shimRTCIceCandidate(a) {
    if (!a.RTCIceCandidate || a.RTCIceCandidate && "foundation"in a.RTCIceCandidate.prototype)
        return;
    const e = a.RTCIceCandidate;
    a.RTCIceCandidate = function(o) {
        if (typeof o == "object" && o.candidate && o.candidate.indexOf("a=") === 0 && (o = JSON.parse(JSON.stringify(o)),
        o.candidate = o.candidate.substr(2)),
        o.candidate && o.candidate.length) {
            const s = new e(o)
              , c = SDPUtils.parseCandidate(o.candidate)
              , d = Object.assign(s, c);
            return d.toJSON = function() {
                return {
                    candidate: d.candidate,
                    sdpMid: d.sdpMid,
                    sdpMLineIndex: d.sdpMLineIndex,
                    usernameFragment: d.usernameFragment
                }
            }
            ,
            d
        }
        return new e(o)
    }
    ,
    a.RTCIceCandidate.prototype = e.prototype,
    wrapPeerConnectionEvent(a, "icecandidate", i=>(i.candidate && Object.defineProperty(i, "candidate", {
        value: new a.RTCIceCandidate(i.candidate),
        writable: "false"
    }),
    i))
}
function shimMaxMessageSize(a, e) {
    if (!a.RTCPeerConnection)
        return;
    "sctp"in a.RTCPeerConnection.prototype || Object.defineProperty(a.RTCPeerConnection.prototype, "sctp", {
        get() {
            return typeof this._sctp == "undefined" ? null : this._sctp
        }
    });
    const i = function(_) {
        if (!_ || !_.sdp)
            return !1;
        const b = SDPUtils.splitSections(_.sdp);
        return b.shift(),
        b.some(k=>{
            const j = SDPUtils.parseMLine(k);
            return j && j.kind === "application" && j.protocol.indexOf("SCTP") !== -1
        }
        )
    }
      , o = function(_) {
        const b = _.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
        if (b === null || b.length < 2)
            return -1;
        const k = parseInt(b[1], 10);
        return k !== k ? -1 : k
    }
      , s = function(_) {
        let b = 65536;
        return e.browser === "firefox" && (e.version < 57 ? _ === -1 ? b = 16384 : b = 2147483637 : e.version < 60 ? b = e.version === 57 ? 65535 : 65536 : b = 2147483637),
        b
    }
      , c = function(_, b) {
        let k = 65536;
        e.browser === "firefox" && e.version === 57 && (k = 65535);
        const j = SDPUtils.matchPrefix(_.sdp, "a=max-message-size:");
        return j.length > 0 ? k = parseInt(j[0].substr(19), 10) : e.browser === "firefox" && b !== -1 && (k = 2147483637),
        k
    }
      , d = a.RTCPeerConnection.prototype.setRemoteDescription;
    a.RTCPeerConnection.prototype.setRemoteDescription = function() {
        if (this._sctp = null,
        e.browser === "chrome" && e.version >= 76) {
            const {sdpSemantics: b} = this.getConfiguration();
            b === "plan-b" && Object.defineProperty(this, "sctp", {
                get() {
                    return typeof this._sctp == "undefined" ? null : this._sctp
                },
                enumerable: !0,
                configurable: !0
            })
        }
        if (i(arguments[0])) {
            const b = o(arguments[0])
              , k = s(b)
              , j = c(arguments[0], b);
            let$;
            k === 0 && j === 0 ? $ = Number.POSITIVE_INFINITY : k === 0 || j === 0 ? $ = Math.max(k, j) : $ = Math.min(k, j);
            const _e = {};
            Object.defineProperty(_e, "maxMessageSize", {
                get() {
                    return $
                }
            }),
            this._sctp = _e
        }
        return d.apply(this, arguments)
    }
}
function shimSendThrowTypeError(a) {
    if (!(a.RTCPeerConnection && "createDataChannel"in a.RTCPeerConnection.prototype))
        return;
    function e(o, s) {
        const c = o.send;
        o.send = function() {
            const _ = arguments[0]
              , b = _.length || _.size || _.byteLength;
            if (o.readyState === "open" && s.sctp && b > s.sctp.maxMessageSize)
                throw new TypeError("Message too large (can send a maximum of " + s.sctp.maxMessageSize + " bytes)");
            return c.apply(o, arguments)
        }
    }
    const i = a.RTCPeerConnection.prototype.createDataChannel;
    a.RTCPeerConnection.prototype.createDataChannel = function() {
        const s = i.apply(this, arguments);
        return e(s, this),
        s
    }
    ,
    wrapPeerConnectionEvent(a, "datachannel", o=>(e(o.channel, o.target),
    o))
}
function shimConnectionState(a) {
    if (!a.RTCPeerConnection || "connectionState"in a.RTCPeerConnection.prototype)
        return;
    const e = a.RTCPeerConnection.prototype;
    Object.defineProperty(e, "connectionState", {
        get() {
            return {
                completed: "connected",
                checking: "connecting"
            }[this.iceConnectionState] || this.iceConnectionState
        },
        enumerable: !0,
        configurable: !0
    }),
    Object.defineProperty(e, "onconnectionstatechange", {
        get() {
            return this._onconnectionstatechange || null
        },
        set(i) {
            this._onconnectionstatechange && (this.removeEventListener("connectionstatechange", this._onconnectionstatechange),
            delete this._onconnectionstatechange),
            i && this.addEventListener("connectionstatechange", this._onconnectionstatechange = i)
        },
        enumerable: !0,
        configurable: !0
    }),
    ["setLocalDescription", "setRemoteDescription"].forEach(i=>{
        const o = e[i];
        e[i] = function() {
            return this._connectionstatechangepoly || (this._connectionstatechangepoly = s=>{
                const c = s.target;
                if (c._lastConnectionState !== c.connectionState) {
                    c._lastConnectionState = c.connectionState;
                    const d = new Event("connectionstatechange",s);
                    c.dispatchEvent(d)
                }
                return s
            }
            ,
            this.addEventListener("iceconnectionstatechange", this._connectionstatechangepoly)),
            o.apply(this, arguments)
        }
    }
    )
}
function removeExtmapAllowMixed(a, e) {
    if (!a.RTCPeerConnection || e.browser === "chrome" && e.version >= 71 || e.browser === "safari" && e.version >= 605)
        return;
    const i = a.RTCPeerConnection.prototype.setRemoteDescription;
    a.RTCPeerConnection.prototype.setRemoteDescription = function(s) {
        if (s && s.sdp && s.sdp.indexOf(`
a=extmap-allow-mixed`) !== -1) {
            const c = s.sdp.split(`
`).filter(d=>d.trim() !== "a=extmap-allow-mixed").join(`
`);
            a.RTCSessionDescription && s instanceof a.RTCSessionDescription ? arguments[0] = new a.RTCSessionDescription({
                type: s.type,
                sdp: c
            }) : s.sdp = c
        }
        return i.apply(this, arguments)
    }
}
function shimAddIceCandidateNullOrEmpty(a, e) {
    if (!(a.RTCPeerConnection && a.RTCPeerConnection.prototype))
        return;
    const i = a.RTCPeerConnection.prototype.addIceCandidate;
    !i || i.length === 0 || (a.RTCPeerConnection.prototype.addIceCandidate = function() {
        return arguments[0] ? (e.browser === "chrome" && e.version < 78 || e.browser === "firefox" && e.version < 68 || e.browser === "safari") && arguments[0] && arguments[0].candidate === "" ? Promise.resolve() : i.apply(this, arguments) : (arguments[1] && arguments[1].apply(null),
        Promise.resolve())
    }
    )
}
function shimParameterlessSetLocalDescription(a, e) {
    if (!(a.RTCPeerConnection && a.RTCPeerConnection.prototype))
        return;
    const i = a.RTCPeerConnection.prototype.setLocalDescription;
    !i || i.length === 0 || (a.RTCPeerConnection.prototype.setLocalDescription = function() {
        let s = arguments[0] || {};
        if (typeof s != "object" || s.type && s.sdp)
            return i.apply(this, arguments);
        if (s = {
            type: s.type,
            sdp: s.sdp
        },
        !s.type)
            switch (this.signalingState) {
            case "stable":
            case "have-local-offer":
            case "have-remote-pranswer":
                s.type = "offer";
                break;
            default:
                s.type = "answer";
                break
            }
        return s.sdp || s.type !== "offer" && s.type !== "answer" ? i.apply(this, [s]) : (s.type === "offer" ? this.createOffer : this.createAnswer).apply(this).then(d=>i.apply(this, [d]))
    }
    )
}
var commonShim = Object.freeze(Object.defineProperty({
    __proto__: null,
    shimRTCIceCandidate,
    shimMaxMessageSize,
    shimSendThrowTypeError,
    shimConnectionState,
    removeExtmapAllowMixed,
    shimAddIceCandidateNullOrEmpty,
    shimParameterlessSetLocalDescription
}, Symbol.toStringTag, {
    value: "Module"
}));
function adapterFactory({window: a}={}, e={
    shimChrome: !0,
    shimFirefox: !0,
    shimSafari: !0
}) {
    const i = log$L
      , o = detectBrowser(a)
      , s = {
        browserDetails: o,
        commonShim,
        extractVersion,
        disableLog,
        disableWarnings,
        sdp
    };
    switch (o.browser) {
    case "chrome":
        if (!chromeShim || !shimPeerConnection$1 || !e.shimChrome)
            return i("Chrome shim is not included in this adapter release."),
            s;
        if (o.version === null)
            return i("Chrome shim can not determine version, not shimming."),
            s;
        i("adapter.js shimming chrome."),
        s.browserShim = chromeShim,
        shimAddIceCandidateNullOrEmpty(a, o),
        shimParameterlessSetLocalDescription(a),
        shimGetUserMedia$2(a, o),
        shimMediaStream(a),
        shimPeerConnection$1(a, o),
        shimOnTrack$1(a),
        shimAddTrackRemoveTrack(a, o),
        shimGetSendersWithDtmf(a),
        shimGetStats(a),
        shimSenderReceiverGetStats(a),
        fixNegotiationNeeded(a, o),
        shimRTCIceCandidate(a),
        shimConnectionState(a),
        shimMaxMessageSize(a, o),
        shimSendThrowTypeError(a),
        removeExtmapAllowMixed(a, o);
        break;
    case "firefox":
        if (!firefoxShim || !shimPeerConnection || !e.shimFirefox)
            return i("Firefox shim is not included in this adapter release."),
            s;
        i("adapter.js shimming firefox."),
        s.browserShim = firefoxShim,
        shimAddIceCandidateNullOrEmpty(a, o),
        shimParameterlessSetLocalDescription(a),
        shimGetUserMedia$1(a, o),
        shimPeerConnection(a, o),
        shimOnTrack(a),
        shimRemoveStream(a),
        shimSenderGetStats(a),
        shimReceiverGetStats(a),
        shimRTCDataChannel(a),
        shimAddTransceiver(a),
        shimGetParameters(a),
        shimCreateOffer(a),
        shimCreateAnswer(a),
        shimRTCIceCandidate(a),
        shimConnectionState(a),
        shimMaxMessageSize(a, o),
        shimSendThrowTypeError(a);
        break;
    case "safari":
        if (!safariShim || !e.shimSafari)
            return i("Safari shim is not included in this adapter release."),
            s;
        i("adapter.js shimming safari."),
        s.browserShim = safariShim,
        shimAddIceCandidateNullOrEmpty(a, o),
        shimParameterlessSetLocalDescription(a),
        shimRTCIceServerUrls(a),
        shimCreateOfferLegacy(a),
        shimCallbacksAPI(a),
        shimLocalStreamsAPI(a),
        shimRemoteStreamsAPI(a),
        shimTrackEventTransceiver(a),
        shimGetUserMedia(a),
        shimAudioContext(a),
        shimRTCIceCandidate(a),
        shimMaxMessageSize(a, o),
        shimSendThrowTypeError(a),
        removeExtmapAllowMixed(a, o);
        break;
    default:
        i("Unsupported browser!");
        break
    }
    return s
}
adapterFactory({
    window: typeof window == "undefined" ? void 0 : window
});
Promise.prototype._timeout = function(a, e) {
    let i;
    return new Promise((o,s)=>(i = window.setTimeout(()=>{
        s(e)
    }
    , a),
    this.then(c=>{
        clearTimeout(i),
        o(c)
    }
    , c=>{
        clearTimeout(i),
        s(c)
    }
    )))
}
;
function clear() {
    const a = console.log;
    console.log = function(...e) {
        typeof e[0] == "string" && e[0].indexOf("Babylon.js") == 0 || a(...e)
    }
}
clear();
var Constants = function() {
    function a() {}
    return a.ALPHA_DISABLE = 0,
    a.ALPHA_ADD = 1,
    a.ALPHA_COMBINE = 2,
    a.ALPHA_SUBTRACT = 3,
    a.ALPHA_MULTIPLY = 4,
    a.ALPHA_MAXIMIZED = 5,
    a.ALPHA_ONEONE = 6,
    a.ALPHA_PREMULTIPLIED = 7,
    a.ALPHA_PREMULTIPLIED_PORTERDUFF = 8,
    a.ALPHA_INTERPOLATE = 9,
    a.ALPHA_SCREENMODE = 10,
    a.ALPHA_ONEONE_ONEONE = 11,
    a.ALPHA_ALPHATOCOLOR = 12,
    a.ALPHA_REVERSEONEMINUS = 13,
    a.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14,
    a.ALPHA_ONEONE_ONEZERO = 15,
    a.ALPHA_EXCLUSION = 16,
    a.ALPHA_LAYER_ACCUMULATE = 17,
    a.ALPHA_EQUATION_ADD = 0,
    a.ALPHA_EQUATION_SUBSTRACT = 1,
    a.ALPHA_EQUATION_REVERSE_SUBTRACT = 2,
    a.ALPHA_EQUATION_MAX = 3,
    a.ALPHA_EQUATION_MIN = 4,
    a.ALPHA_EQUATION_DARKEN = 5,
    a.DELAYLOADSTATE_NONE = 0,
    a.DELAYLOADSTATE_LOADED = 1,
    a.DELAYLOADSTATE_LOADING = 2,
    a.DELAYLOADSTATE_NOTLOADED = 4,
    a.NEVER = 512,
    a.ALWAYS = 519,
    a.LESS = 513,
    a.EQUAL = 514,
    a.LEQUAL = 515,
    a.GREATER = 516,
    a.GEQUAL = 518,
    a.NOTEQUAL = 517,
    a.KEEP = 7680,
    a.ZERO = 0,
    a.REPLACE = 7681,
    a.INCR = 7682,
    a.DECR = 7683,
    a.INVERT = 5386,
    a.INCR_WRAP = 34055,
    a.DECR_WRAP = 34056,
    a.TEXTURE_CLAMP_ADDRESSMODE = 0,
    a.TEXTURE_WRAP_ADDRESSMODE = 1,
    a.TEXTURE_MIRROR_ADDRESSMODE = 2,
    a.TEXTURE_CREATIONFLAG_STORAGE = 1,
    a.TEXTUREFORMAT_ALPHA = 0,
    a.TEXTUREFORMAT_LUMINANCE = 1,
    a.TEXTUREFORMAT_LUMINANCE_ALPHA = 2,
    a.TEXTUREFORMAT_RGB = 4,
    a.TEXTUREFORMAT_RGBA = 5,
    a.TEXTUREFORMAT_RED = 6,
    a.TEXTUREFORMAT_R = 6,
    a.TEXTUREFORMAT_RG = 7,
    a.TEXTUREFORMAT_RED_INTEGER = 8,
    a.TEXTUREFORMAT_R_INTEGER = 8,
    a.TEXTUREFORMAT_RG_INTEGER = 9,
    a.TEXTUREFORMAT_RGB_INTEGER = 10,
    a.TEXTUREFORMAT_RGBA_INTEGER = 11,
    a.TEXTUREFORMAT_BGRA = 12,
    a.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13,
    a.TEXTUREFORMAT_DEPTH32_FLOAT = 14,
    a.TEXTUREFORMAT_DEPTH16 = 15,
    a.TEXTUREFORMAT_DEPTH24 = 16,
    a.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492,
    a.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495,
    a.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494,
    a.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779,
    a.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778,
    a.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777,
    a.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776,
    a.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808,
    a.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196,
    a.TEXTURETYPE_UNSIGNED_BYTE = 0,
    a.TEXTURETYPE_UNSIGNED_INT = 0,
    a.TEXTURETYPE_FLOAT = 1,
    a.TEXTURETYPE_HALF_FLOAT = 2,
    a.TEXTURETYPE_BYTE = 3,
    a.TEXTURETYPE_SHORT = 4,
    a.TEXTURETYPE_UNSIGNED_SHORT = 5,
    a.TEXTURETYPE_INT = 6,
    a.TEXTURETYPE_UNSIGNED_INTEGER = 7,
    a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8,
    a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9,
    a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10,
    a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11,
    a.TEXTURETYPE_UNSIGNED_INT_24_8 = 12,
    a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13,
    a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14,
    a.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15,
    a.TEXTURETYPE_UNDEFINED = 16,
    a.TEXTURE_NEAREST_SAMPLINGMODE = 1,
    a.TEXTURE_NEAREST_NEAREST = 1,
    a.TEXTURE_BILINEAR_SAMPLINGMODE = 2,
    a.TEXTURE_LINEAR_LINEAR = 2,
    a.TEXTURE_TRILINEAR_SAMPLINGMODE = 3,
    a.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3,
    a.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4,
    a.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5,
    a.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6,
    a.TEXTURE_NEAREST_LINEAR = 7,
    a.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8,
    a.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9,
    a.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10,
    a.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11,
    a.TEXTURE_LINEAR_NEAREST = 12,
    a.TEXTURE_EXPLICIT_MODE = 0,
    a.TEXTURE_SPHERICAL_MODE = 1,
    a.TEXTURE_PLANAR_MODE = 2,
    a.TEXTURE_CUBIC_MODE = 3,
    a.TEXTURE_PROJECTION_MODE = 4,
    a.TEXTURE_SKYBOX_MODE = 5,
    a.TEXTURE_INVCUBIC_MODE = 6,
    a.TEXTURE_EQUIRECTANGULAR_MODE = 7,
    a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8,
    a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9,
    a.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096,
    a.TEXTURE_FILTERING_QUALITY_HIGH = 64,
    a.TEXTURE_FILTERING_QUALITY_MEDIUM = 16,
    a.TEXTURE_FILTERING_QUALITY_LOW = 8,
    a.SCALEMODE_FLOOR = 1,
    a.SCALEMODE_NEAREST = 2,
    a.SCALEMODE_CEILING = 3,
    a.MATERIAL_TextureDirtyFlag = 1,
    a.MATERIAL_LightDirtyFlag = 2,
    a.MATERIAL_FresnelDirtyFlag = 4,
    a.MATERIAL_AttributesDirtyFlag = 8,
    a.MATERIAL_MiscDirtyFlag = 16,
    a.MATERIAL_PrePassDirtyFlag = 32,
    a.MATERIAL_AllDirtyFlag = 63,
    a.MATERIAL_TriangleFillMode = 0,
    a.MATERIAL_WireFrameFillMode = 1,
    a.MATERIAL_PointFillMode = 2,
    a.MATERIAL_PointListDrawMode = 3,
    a.MATERIAL_LineListDrawMode = 4,
    a.MATERIAL_LineLoopDrawMode = 5,
    a.MATERIAL_LineStripDrawMode = 6,
    a.MATERIAL_TriangleStripDrawMode = 7,
    a.MATERIAL_TriangleFanDrawMode = 8,
    a.MATERIAL_ClockWiseSideOrientation = 0,
    a.MATERIAL_CounterClockWiseSideOrientation = 1,
    a.ACTION_NothingTrigger = 0,
    a.ACTION_OnPickTrigger = 1,
    a.ACTION_OnLeftPickTrigger = 2,
    a.ACTION_OnRightPickTrigger = 3,
    a.ACTION_OnCenterPickTrigger = 4,
    a.ACTION_OnPickDownTrigger = 5,
    a.ACTION_OnDoublePickTrigger = 6,
    a.ACTION_OnPickUpTrigger = 7,
    a.ACTION_OnPickOutTrigger = 16,
    a.ACTION_OnLongPressTrigger = 8,
    a.ACTION_OnPointerOverTrigger = 9,
    a.ACTION_OnPointerOutTrigger = 10,
    a.ACTION_OnEveryFrameTrigger = 11,
    a.ACTION_OnIntersectionEnterTrigger = 12,
    a.ACTION_OnIntersectionExitTrigger = 13,
    a.ACTION_OnKeyDownTrigger = 14,
    a.ACTION_OnKeyUpTrigger = 15,
    a.PARTICLES_BILLBOARDMODE_Y = 2,
    a.PARTICLES_BILLBOARDMODE_ALL = 7,
    a.PARTICLES_BILLBOARDMODE_STRETCHED = 8,
    a.MESHES_CULLINGSTRATEGY_STANDARD = 0,
    a.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1,
    a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2,
    a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3,
    a.SCENELOADER_NO_LOGGING = 0,
    a.SCENELOADER_MINIMAL_LOGGING = 1,
    a.SCENELOADER_SUMMARY_LOGGING = 2,
    a.SCENELOADER_DETAILED_LOGGING = 3,
    a.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0,
    a.PREPASS_POSITION_TEXTURE_TYPE = 1,
    a.PREPASS_VELOCITY_TEXTURE_TYPE = 2,
    a.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3,
    a.PREPASS_COLOR_TEXTURE_TYPE = 4,
    a.PREPASS_DEPTH_TEXTURE_TYPE = 5,
    a.PREPASS_NORMAL_TEXTURE_TYPE = 6,
    a.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7,
    a.BUFFER_CREATIONFLAG_READ = 1,
    a.BUFFER_CREATIONFLAG_WRITE = 2,
    a.BUFFER_CREATIONFLAG_READWRITE = 3,
    a.BUFFER_CREATIONFLAG_UNIFORM = 4,
    a.BUFFER_CREATIONFLAG_VERTEX = 8,
    a.BUFFER_CREATIONFLAG_INDEX = 16,
    a.BUFFER_CREATIONFLAG_STORAGE = 32,
    a.RENDERPASS_MAIN = 0,
    a.INPUT_ALT_KEY = 18,
    a.INPUT_CTRL_KEY = 17,
    a.INPUT_META_KEY1 = 91,
    a.INPUT_META_KEY2 = 92,
    a.INPUT_META_KEY3 = 93,
    a.INPUT_SHIFT_KEY = 16,
    a.SNAPSHOTRENDERING_STANDARD = 0,
    a.SNAPSHOTRENDERING_FAST = 1,
    a.PERSPECTIVE_CAMERA = 0,
    a.ORTHOGRAPHIC_CAMERA = 1,
    a.FOVMODE_VERTICAL_FIXED = 0,
    a.FOVMODE_HORIZONTAL_FIXED = 1,
    a.RIG_MODE_NONE = 0,
    a.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10,
    a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11,
    a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12,
    a.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13,
    a.RIG_MODE_STEREOSCOPIC_INTERLACED = 14,
    a.RIG_MODE_VR = 20,
    a.RIG_MODE_WEBVR = 21,
    a.RIG_MODE_CUSTOM = 22,
    a.MAX_SUPPORTED_UV_SETS = 6,
    a.GL_ALPHA_EQUATION_ADD = 32774,
    a.GL_ALPHA_EQUATION_MIN = 32775,
    a.GL_ALPHA_EQUATION_MAX = 32776,
    a.GL_ALPHA_EQUATION_SUBTRACT = 32778,
    a.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 32779,
    a.GL_ALPHA_FUNCTION_SRC = 768,
    a.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 769,
    a.GL_ALPHA_FUNCTION_SRC_ALPHA = 770,
    a.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 771,
    a.GL_ALPHA_FUNCTION_DST_ALPHA = 772,
    a.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 773,
    a.GL_ALPHA_FUNCTION_DST_COLOR = 774,
    a.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 775,
    a.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 776,
    a.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 32769,
    a.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 32770,
    a.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 32771,
    a.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 32772,
    a
}();
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics = function(a, e) {
    return extendStatics = Object.setPrototypeOf || {
        __proto__: []
    }instanceof Array && function(i, o) {
        i.__proto__ = o
    }
    || function(i, o) {
        for (var s in o)
            Object.prototype.hasOwnProperty.call(o, s) && (i[s] = o[s])
    }
    ,
    extendStatics(a, e)
};
function __extends(a, e) {
    if (typeof e != "function" && e !== null)
        throw new TypeError("Class extends value " + String(e) + " is not a constructor or null");
    extendStatics(a, e);
    function i() {
        this.constructor = a
    }
    a.prototype = e === null ? Object.create(e) : (i.prototype = e.prototype,
    new i)
}
var __assign = function() {
    return __assign = Object.assign || function(e) {
        for (var i, o = 1, s = arguments.length; o < s; o++) {
            i = arguments[o];
            for (var c in i)
                Object.prototype.hasOwnProperty.call(i, c) && (e[c] = i[c])
        }
        return e
    }
    ,
    __assign.apply(this, arguments)
};
function __decorate(a, e, i, o) {
    var s = arguments.length, c = s < 3 ? e : o === null ? o = Object.getOwnPropertyDescriptor(e, i) : o, d;
    if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
        c = Reflect.decorate(a, e, i, o);
    else
        for (var _ = a.length - 1; _ >= 0; _--)
            (d = a[_]) && (c = (s < 3 ? d(c) : s > 3 ? d(e, i, c) : d(e, i)) || c);
    return s > 3 && c && Object.defineProperty(e, i, c),
    c
}
function __awaiter(a, e, i, o) {
    function s(c) {
        return c instanceof i ? c : new i(function(d) {
            d(c)
        }
        )
    }
    return new (i || (i = Promise))(function(c, d) {
        function _(j) {
            try {
                k(o.next(j))
            } catch ($) {
                d($)
            }
        }
        function b(j) {
            try {
                k(o.throw(j))
            } catch ($) {
                d($)
            }
        }
        function k(j) {
            j.done ? c(j.value) : s(j.value).then(_, b)
        }
        k((o = o.apply(a, e || [])).next())
    }
    )
}
function __generator(a, e) {
    var i = {
        label: 0,
        sent: function() {
            if (c[0] & 1)
                throw c[1];
            return c[1]
        },
        trys: [],
        ops: []
    }, o, s, c, d;
    return d = {
        next: _(0),
        throw: _(1),
        return: _(2)
    },
    typeof Symbol == "function" && (d[Symbol.iterator] = function() {
        return this
    }
    ),
    d;
    function _(k) {
        return function(j) {
            return b([k, j])
        }
    }
    function b(k) {
        if (o)
            throw new TypeError("Generator is already executing.");
        for (; i; )
            try {
                if (o = 1,
                s && (c = k[0] & 2 ? s.return : k[0] ? s.throw || ((c = s.return) && c.call(s),
                0) : s.next) && !(c = c.call(s, k[1])).done)
                    return c;
                switch (s = 0,
                c && (k = [k[0] & 2, c.value]),
                k[0]) {
                case 0:
                case 1:
                    c = k;
                    break;
                case 4:
                    return i.label++,
                    {
                        value: k[1],
                        done: !1
                    };
                case 5:
                    i.label++,
                    s = k[1],
                    k = [0];
                    continue;
                case 7:
                    k = i.ops.pop(),
                    i.trys.pop();
                    continue;
                default:
                    if (c = i.trys,
                    !(c = c.length > 0 && c[c.length - 1]) && (k[0] === 6 || k[0] === 2)) {
                        i = 0;
                        continue
                    }
                    if (k[0] === 3 && (!c || k[1] > c[0] && k[1] < c[3])) {
                        i.label = k[1];
                        break
                    }
                    if (k[0] === 6 && i.label < c[1]) {
                        i.label = c[1],
                        c = k;
                        break
                    }
                    if (c && i.label < c[2]) {
                        i.label = c[2],
                        i.ops.push(k);
                        break
                    }
                    c[2] && i.ops.pop(),
                    i.trys.pop();
                    continue
                }
                k = e.call(a, i)
            } catch (j) {
                k = [6, j],
                s = 0
            } finally {
                o = c = 0
            }
        if (k[0] & 5)
            throw k[1];
        return {
            value: k[0] ? k[1] : void 0,
            done: !0
        }
    }
}
function __spreadArray(a, e, i) {
    if (i || arguments.length === 2)
        for (var o = 0, s = e.length, c; o < s; o++)
            (c || !(o in e)) && (c || (c = Array.prototype.slice.call(e, 0, o)),
            c[o] = e[o]);
    return a.concat(c || Array.prototype.slice.call(e))
}
var EngineStore = function() {
    function a() {}
    return Object.defineProperty(a, "LastCreatedEngine", {
        get: function() {
            return this.Instances.length === 0 ? null : this.Instances[this.Instances.length - 1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "LastCreatedScene", {
        get: function() {
            return this._LastCreatedScene
        },
        enumerable: !1,
        configurable: !0
    }),
    a.Instances = new Array,
    a._LastCreatedScene = null,
    a.UseFallbackTexture = !0,
    a.FallbackTexture = "",
    a
}()
  , EventState = function() {
    function a(e, i, o, s) {
        i === void 0 && (i = !1),
        this.initialize(e, i, o, s)
    }
    return a.prototype.initialize = function(e, i, o, s) {
        return i === void 0 && (i = !1),
        this.mask = e,
        this.skipNextObservers = i,
        this.target = o,
        this.currentTarget = s,
        this
    }
    ,
    a
}()
  , Observer = function() {
    function a(e, i, o) {
        o === void 0 && (o = null),
        this.callback = e,
        this.mask = i,
        this.scope = o,
        this._willBeUnregistered = !1,
        this.unregisterOnNextCall = !1
    }
    return a
}()
  , Observable = function() {
    function a(e) {
        this._observers = new Array,
        this._eventState = new EventState(0),
        e && (this._onObserverAdded = e)
    }
    return a.FromPromise = function(e, i) {
        var o = new a;
        return e.then(function(s) {
            o.notifyObservers(s)
        }).catch(function(s) {
            if (i)
                i.notifyObservers(s);
            else
                throw s
        }),
        o
    }
    ,
    Object.defineProperty(a.prototype, "observers", {
        get: function() {
            return this._observers
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.add = function(e, i, o, s, c) {
        if (i === void 0 && (i = -1),
        o === void 0 && (o = !1),
        s === void 0 && (s = null),
        c === void 0 && (c = !1),
        !e)
            return null;
        var d = new Observer(e,i,s);
        return d.unregisterOnNextCall = c,
        o ? this._observers.unshift(d) : this._observers.push(d),
        this._onObserverAdded && this._onObserverAdded(d),
        d
    }
    ,
    a.prototype.addOnce = function(e) {
        return this.add(e, void 0, void 0, void 0, !0)
    }
    ,
    a.prototype.remove = function(e) {
        if (!e)
            return !1;
        var i = this._observers.indexOf(e);
        return i !== -1 ? (this._deferUnregister(e),
        !0) : !1
    }
    ,
    a.prototype.removeCallback = function(e, i) {
        for (var o = 0; o < this._observers.length; o++) {
            var s = this._observers[o];
            if (!s._willBeUnregistered && s.callback === e && (!i || i === s.scope))
                return this._deferUnregister(s),
                !0
        }
        return !1
    }
    ,
    a.prototype._deferUnregister = function(e) {
        var i = this;
        e.unregisterOnNextCall = !1,
        e._willBeUnregistered = !0,
        setTimeout(function() {
            i._remove(e)
        }, 0)
    }
    ,
    a.prototype._remove = function(e) {
        if (!e)
            return !1;
        var i = this._observers.indexOf(e);
        return i !== -1 ? (this._observers.splice(i, 1),
        !0) : !1
    }
    ,
    a.prototype.makeObserverTopPriority = function(e) {
        this._remove(e),
        this._observers.unshift(e)
    }
    ,
    a.prototype.makeObserverBottomPriority = function(e) {
        this._remove(e),
        this._observers.push(e)
    }
    ,
    a.prototype.notifyObservers = function(e, i, o, s, c) {
        if (i === void 0 && (i = -1),
        !this._observers.length)
            return !0;
        var d = this._eventState;
        d.mask = i,
        d.target = o,
        d.currentTarget = s,
        d.skipNextObservers = !1,
        d.lastReturnValue = e,
        d.userInfo = c;
        for (var _ = 0, b = this._observers; _ < b.length; _++) {
            var k = b[_];
            if (!k._willBeUnregistered && (k.mask & i && (k.scope ? d.lastReturnValue = k.callback.apply(k.scope, [e, d]) : d.lastReturnValue = k.callback(e, d),
            k.unregisterOnNextCall && this._deferUnregister(k)),
            d.skipNextObservers))
                return !1
        }
        return !0
    }
    ,
    a.prototype.notifyObserversWithPromise = function(e, i, o, s, c) {
        var d = this;
        i === void 0 && (i = -1);
        var _ = Promise.resolve(e);
        if (!this._observers.length)
            return _;
        var b = this._eventState;
        return b.mask = i,
        b.target = o,
        b.currentTarget = s,
        b.skipNextObservers = !1,
        b.userInfo = c,
        this._observers.forEach(function(k) {
            b.skipNextObservers || k._willBeUnregistered || k.mask & i && (k.scope ? _ = _.then(function(j) {
                return b.lastReturnValue = j,
                k.callback.apply(k.scope, [e, b])
            }) : _ = _.then(function(j) {
                return b.lastReturnValue = j,
                k.callback(e, b)
            }),
            k.unregisterOnNextCall && d._deferUnregister(k))
        }),
        _.then(function() {
            return e
        })
    }
    ,
    a.prototype.notifyObserver = function(e, i, o) {
        if (o === void 0 && (o = -1),
        !e._willBeUnregistered) {
            var s = this._eventState;
            s.mask = o,
            s.skipNextObservers = !1,
            e.callback(i, s),
            e.unregisterOnNextCall && this._deferUnregister(e)
        }
    }
    ,
    a.prototype.hasObservers = function() {
        return this._observers.length > 0
    }
    ,
    a.prototype.clear = function() {
        this._observers = new Array,
        this._onObserverAdded = null
    }
    ,
    a.prototype.clone = function() {
        var e = new a;
        return e._observers = this._observers.slice(0),
        e
    }
    ,
    a.prototype.hasSpecificMask = function(e) {
        e === void 0 && (e = -1);
        for (var i = 0, o = this._observers; i < o.length; i++) {
            var s = o[i];
            if (s.mask & e || s.mask === e)
                return !0
        }
        return !1
    }
    ,
    a
}();
function IsWindowObjectExist() {
    return typeof window != "undefined"
}
function IsNavigatorAvailable() {
    return typeof navigator != "undefined"
}
function IsDocumentAvailable() {
    return typeof document != "undefined"
}
function GetDOMTextContent(a) {
    for (var e = "", i = a.firstChild; i; )
        i.nodeType === 3 && (e += i.textContent),
        i = i.nextSibling;
    return e
}
var DomManagement = {
    IsWindowObjectExist,
    IsNavigatorAvailable,
    IsDocumentAvailable,
    GetDOMTextContent
}
  , Logger$2 = function() {
    function a() {}
    return a._CheckLimit = function(e, i) {
        var o = a._LogLimitOutputs[e];
        return o ? o.current++ : (o = {
            limit: i,
            current: 1
        },
        a._LogLimitOutputs[e] = o),
        o.current <= o.limit
    }
    ,
    a._GenerateLimitMessage = function(e, i) {
        var o = a._LogLimitOutputs[e];
        if (!(!o || !a.MessageLimitReached) && o.current === o.limit)
            switch (i) {
            case 0:
                a.Log(a.MessageLimitReached.replace(/%LIMIT%/g, "" + o.limit).replace(/%TYPE%/g, "log"));
                break;
            case 1:
                a.Warn(a.MessageLimitReached.replace(/%LIMIT%/g, "" + o.limit).replace(/%TYPE%/g, "warning"));
                break;
            case 2:
                a.Error(a.MessageLimitReached.replace(/%LIMIT%/g, "" + o.limit).replace(/%TYPE%/g, "error"));
                break
            }
    }
    ,
    a._AddLogEntry = function(e) {
        a._LogCache = e + a._LogCache,
        a.OnNewCacheEntry && a.OnNewCacheEntry(e)
    }
    ,
    a._FormatMessage = function(e) {
        var i = function(s) {
            return s < 10 ? "0" + s : "" + s
        }
          , o = new Date;
        return "[" + i(o.getHours()) + ":" + i(o.getMinutes()) + ":" + i(o.getSeconds()) + "]: " + e
    }
    ,
    a._LogDisabled = function(e, i) {}
    ,
    a._LogEnabled = function(e, i) {
        if (!(i !== void 0 && !a._CheckLimit(e, i))) {
            var o = a._FormatMessage(e);
            console.log("BJS - " + o);
            var s = "<div style='color:white'>" + o + "</div><br>";
            a._AddLogEntry(s),
            a._GenerateLimitMessage(e, 0)
        }
    }
    ,
    a._WarnDisabled = function(e, i) {}
    ,
    a._WarnEnabled = function(e, i) {
        if (!(i !== void 0 && !a._CheckLimit(e, i))) {
            var o = a._FormatMessage(e);
            console.warn("BJS - " + o);
            var s = "<div style='color:orange'>" + e + "</div><br>";
            a._AddLogEntry(s),
            a._GenerateLimitMessage(e, 1)
        }
    }
    ,
    a._ErrorDisabled = function(e, i) {}
    ,
    a._ErrorEnabled = function(e, i) {
        if (!(i !== void 0 && !a._CheckLimit(e, i))) {
            var o = a._FormatMessage(e);
            a.errorsCount++,
            console.error("BJS - " + o);
            var s = "<div style='color:red'>" + o + "</div><br>";
            a._AddLogEntry(s),
            a._GenerateLimitMessage(e, 2)
        }
    }
    ,
    Object.defineProperty(a, "LogCache", {
        get: function() {
            return a._LogCache
        },
        enumerable: !1,
        configurable: !0
    }),
    a.ClearLogCache = function() {
        a._LogCache = "",
        a._LogLimitOutputs = {},
        a.errorsCount = 0
    }
    ,
    Object.defineProperty(a, "LogLevels", {
        set: function(e) {
            (e & a.MessageLogLevel) === a.MessageLogLevel ? a.Log = a._LogEnabled : a.Log = a._LogDisabled,
            (e & a.WarningLogLevel) === a.WarningLogLevel ? a.Warn = a._WarnEnabled : a.Warn = a._WarnDisabled,
            (e & a.ErrorLogLevel) === a.ErrorLogLevel ? a.Error = a._ErrorEnabled : a.Error = a._ErrorDisabled
        },
        enumerable: !1,
        configurable: !0
    }),
    a.NoneLogLevel = 0,
    a.MessageLogLevel = 1,
    a.WarningLogLevel = 2,
    a.ErrorLogLevel = 4,
    a.AllLogLevel = 7,
    a.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",
    a._LogCache = "",
    a._LogLimitOutputs = {},
    a.errorsCount = 0,
    a.Log = a._LogEnabled,
    a.Warn = a._WarnEnabled,
    a.Error = a._ErrorEnabled,
    a
}()
  , EndsWith = function(a, e) {
    return a.indexOf(e, a.length - e.length) !== -1
}
  , StartsWith = function(a, e) {
    return a ? a.indexOf(e) === 0 : !1
}
  , Decode = function(a) {
    if (typeof TextDecoder != "undefined")
        return new TextDecoder().decode(a);
    for (var e = "", i = 0; i < a.byteLength; i++)
        e += String.fromCharCode(a[i]);
    return e
}
  , EncodeArrayBufferToBase64 = function(a) {
    for (var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", i = "", o, s, c, d, _, b, k, j = 0, $ = ArrayBuffer.isView(a) ? new Uint8Array(a.buffer,a.byteOffset,a.byteLength) : new Uint8Array(a); j < $.length; )
        o = $[j++],
        s = j < $.length ? $[j++] : Number.NaN,
        c = j < $.length ? $[j++] : Number.NaN,
        d = o >> 2,
        _ = (o & 3) << 4 | s >> 4,
        b = (s & 15) << 2 | c >> 6,
        k = c & 63,
        isNaN(s) ? b = k = 64 : isNaN(c) && (k = 64),
        i += e.charAt(d) + e.charAt(_) + e.charAt(b) + e.charAt(k);
    return i
}
  , DecodeBase64ToString = function(a) {
    return atob(a)
}
  , DecodeBase64ToBinary = function(a) {
    for (var e = DecodeBase64ToString(a), i = e.length, o = new Uint8Array(new ArrayBuffer(i)), s = 0; s < i; s++)
        o[s] = e.charCodeAt(s);
    return o.buffer
}
  , PadNumber = function(a, e) {
    for (var i = String(a); i.length < e; )
        i = "0" + i;
    return i
}
  , StringTools = {
    EndsWith,
    StartsWith,
    Decode,
    EncodeArrayBufferToBase64,
    DecodeBase64ToString,
    DecodeBase64ToBinary,
    PadNumber
}
  , ShaderCodeNode = function() {
    function a() {
        this.children = []
    }
    return a.prototype.isValid = function(e) {
        return !0
    }
    ,
    a.prototype.process = function(e, i) {
        var o = "";
        if (this.line) {
            var s = this.line
              , c = i.processor;
            if (c) {
                if (c.lineProcessor && (s = c.lineProcessor(s, i.isFragment, i.processingContext)),
                c.attributeProcessor && StartsWith(this.line, "attribute"))
                    s = c.attributeProcessor(this.line, e, i.processingContext);
                else if (c.varyingProcessor && StartsWith(this.line, "varying"))
                    s = c.varyingProcessor(this.line, i.isFragment, e, i.processingContext);
                else if (c.uniformProcessor && c.uniformRegexp && c.uniformRegexp.test(this.line))
                    i.lookForClosingBracketForUniformBuffer || (s = c.uniformProcessor(this.line, i.isFragment, e, i.processingContext));
                else if (c.uniformBufferProcessor && c.uniformBufferRegexp && c.uniformBufferRegexp.test(this.line))
                    i.lookForClosingBracketForUniformBuffer || (s = c.uniformBufferProcessor(this.line, i.isFragment, i.processingContext),
                    i.lookForClosingBracketForUniformBuffer = !0);
                else if (c.textureProcessor && c.textureRegexp && c.textureRegexp.test(this.line))
                    s = c.textureProcessor(this.line, i.isFragment, e, i.processingContext);
                else if ((c.uniformProcessor || c.uniformBufferProcessor) && StartsWith(this.line, "uniform") && !i.lookForClosingBracketForUniformBuffer) {
                    var d = /uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/;
                    d.test(this.line) ? c.uniformProcessor && (s = c.uniformProcessor(this.line, i.isFragment, e, i.processingContext)) : c.uniformBufferProcessor && (s = c.uniformBufferProcessor(this.line, i.isFragment, i.processingContext),
                    i.lookForClosingBracketForUniformBuffer = !0)
                }
                i.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1 && (i.lookForClosingBracketForUniformBuffer = !1,
                c.endOfUniformBufferProcessor && (s = c.endOfUniformBufferProcessor(this.line, i.isFragment, i.processingContext)))
            }
            o += s + `\r
`
        }
        return this.children.forEach(function(_) {
            o += _.process(e, i)
        }),
        this.additionalDefineKey && (e[this.additionalDefineKey] = this.additionalDefineValue || "true"),
        o
    }
    ,
    a
}()
  , ShaderCodeCursor = function() {
    function a() {}
    return Object.defineProperty(a.prototype, "currentLine", {
        get: function() {
            return this._lines[this.lineIndex]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "canRead", {
        get: function() {
            return this.lineIndex < this._lines.length - 1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "lines", {
        set: function(e) {
            this._lines = [];
            for (var i = 0, o = e; i < o.length; i++) {
                var s = o[i];
                if (s[0] === "#") {
                    this._lines.push(s);
                    continue
                }
                for (var c = s.split(";"), d = 0; d < c.length; d++) {
                    var _ = c[d];
                    _ = _.trim(),
                    _ && this._lines.push(_ + (d !== c.length - 1 ? ";" : ""))
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    a
}()
  , ShaderCodeConditionNode = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.process = function(i, o) {
        for (var s = 0; s < this.children.length; s++) {
            var c = this.children[s];
            if (c.isValid(i))
                return c.process(i, o)
        }
        return ""
    }
    ,
    e
}(ShaderCodeNode)
  , ShaderCodeTestNode = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.isValid = function(i) {
        return this.testExpression.isTrue(i)
    }
    ,
    e
}(ShaderCodeNode)
  , ShaderDefineExpression = function() {
    function a() {}
    return a.prototype.isTrue = function(e) {
        return !0
    }
    ,
    a.postfixToInfix = function(e) {
        for (var i = [], o = 0, s = e; o < s.length; o++) {
            var c = s[o];
            if (a._OperatorPriority[c] === void 0)
                i.push(c);
            else {
                var d = i[i.length - 1]
                  , _ = i[i.length - 2];
                i.length -= 2,
                i.push("(" + _ + c + d + ")")
            }
        }
        return i[i.length - 1]
    }
    ,
    a.infixToPostfix = function(e) {
        for (var i = [], o = -1, s = function() {
            k = k.trim(),
            k !== "" && (i.push(k),
            k = "")
        }, c = function(_e) {
            o < a._Stack.length - 1 && (a._Stack[++o] = _e)
        }, d = function() {
            return a._Stack[o]
        }, _ = function() {
            return o === -1 ? "!!INVALID EXPRESSION!!" : a._Stack[o--]
        }, b = 0, k = ""; b < e.length; ) {
            var j = e.charAt(b)
              , $ = b < e.length - 1 ? e.substr(b, 2) : "";
            if (j === "(")
                k = "",
                c(j);
            else if (j === ")") {
                for (s(); o !== -1 && d() !== "("; )
                    i.push(_());
                _()
            } else if (a._OperatorPriority[$] > 1) {
                for (s(); o !== -1 && a._OperatorPriority[d()] >= a._OperatorPriority[$]; )
                    i.push(_());
                c($),
                b++
            } else
                k += j;
            b++
        }
        for (s(); o !== -1; )
            d() === "(" ? _() : i.push(_());
        return i
    }
    ,
    a._OperatorPriority = {
        ")": 0,
        "(": 1,
        "||": 2,
        "&&": 3
    },
    a._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""],
    a
}()
  , ShaderDefineIsDefinedOperator = function(a) {
    __extends(e, a);
    function e(i, o) {
        o === void 0 && (o = !1);
        var s = a.call(this) || this;
        return s.define = i,
        s.not = o,
        s
    }
    return e.prototype.isTrue = function(i) {
        var o = i[this.define] !== void 0;
        return this.not && (o = !o),
        o
    }
    ,
    e
}(ShaderDefineExpression)
  , ShaderDefineOrOperator = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.isTrue = function(i) {
        return this.leftOperand.isTrue(i) || this.rightOperand.isTrue(i)
    }
    ,
    e
}(ShaderDefineExpression)
  , ShaderDefineAndOperator = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.isTrue = function(i) {
        return this.leftOperand.isTrue(i) && this.rightOperand.isTrue(i)
    }
    ,
    e
}(ShaderDefineExpression)
  , ShaderDefineArithmeticOperator = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this) || this;
        return c.define = i,
        c.operand = o,
        c.testValue = s,
        c
    }
    return e.prototype.isTrue = function(i) {
        var o = i[this.define];
        o === void 0 && (o = this.define);
        var s = !1
          , c = parseInt(o)
          , d = parseInt(this.testValue);
        switch (this.operand) {
        case ">":
            s = c > d;
            break;
        case "<":
            s = c < d;
            break;
        case "<=":
            s = c <= d;
            break;
        case ">=":
            s = c >= d;
            break;
        case "==":
            s = c === d;
            break
        }
        return s
    }
    ,
    e
}(ShaderDefineExpression);
function _WarnImport(a) {
    return a + " needs to be imported before as it contains a side-effect required by your code."
}
var ShaderLanguage;
(function(a) {
    a[a.GLSL = 0] = "GLSL",
    a[a.WGSL = 1] = "WGSL"
}
)(ShaderLanguage || (ShaderLanguage = {}));
var regexSE = /defined\s*?\((.+?)\)/g, regexSERevert = /defined\s*?\[(.+?)\]/g, ShaderProcessor = function() {
    function a() {}
    return a.Initialize = function(e) {
        e.processor && e.processor.initializeShaders && e.processor.initializeShaders(e.processingContext)
    }
    ,
    a.Process = function(e, i, o, s) {
        var c = this, d;
        !((d = i.processor) === null || d === void 0) && d.preProcessShaderCode && (e = i.processor.preProcessShaderCode(e)),
        this._ProcessIncludes(e, i, function(_) {
            var b = c._ProcessShaderConversion(_, i, s);
            o(b)
        })
    }
    ,
    a.PreProcess = function(e, i, o, s) {
        var c = this, d;
        !((d = i.processor) === null || d === void 0) && d.preProcessShaderCode && (e = i.processor.preProcessShaderCode(e)),
        this._ProcessIncludes(e, i, function(_) {
            var b = c._ApplyPreProcessing(_, i, s);
            o(b)
        })
    }
    ,
    a.Finalize = function(e, i, o) {
        return !o.processor || !o.processor.finalizeShaders ? {
            vertexCode: e,
            fragmentCode: i
        } : o.processor.finalizeShaders(e, i, o.processingContext)
    }
    ,
    a._ProcessPrecision = function(e, i) {
        var o;
        if (!((o = i.processor) === null || o === void 0) && o.noPrecision)
            return e;
        var s = i.shouldUseHighPrecisionShader;
        return e.indexOf("precision highp float") === -1 ? s ? e = `precision highp float;
` + e : e = `precision mediump float;
` + e : s || (e = e.replace("precision highp float", "precision mediump float")),
        e
    }
    ,
    a._ExtractOperation = function(e) {
        var i = /defined\((.+)\)/
          , o = i.exec(e);
        if (o && o.length)
            return new ShaderDefineIsDefinedOperator(o[1].trim(),e[0] === "!");
        for (var s = ["==", ">=", "<=", "<", ">"], c = "", d = 0, _ = 0, b = s; _ < b.length && (c = b[_],
        d = e.indexOf(c),
        !(d > -1)); _++)
            ;
        if (d === -1)
            return new ShaderDefineIsDefinedOperator(e);
        var k = e.substring(0, d).trim()
          , j = e.substring(d + c.length).trim();
        return new ShaderDefineArithmeticOperator(k,c,j)
    }
    ,
    a._BuildSubExpression = function(e) {
        e = e.replace(regexSE, "defined[$1]");
        for (var i = ShaderDefineExpression.infixToPostfix(e), o = [], s = 0, c = i; s < c.length; s++) {
            var d = c[s];
            if (d !== "||" && d !== "&&")
                o.push(d);
            else if (o.length >= 2) {
                var _ = o[o.length - 1]
                  , b = o[o.length - 2];
                o.length -= 2;
                var k = d == "&&" ? new ShaderDefineAndOperator : new ShaderDefineOrOperator;
                typeof _ == "string" && (_ = _.replace(regexSERevert, "defined($1)")),
                typeof b == "string" && (b = b.replace(regexSERevert, "defined($1)")),
                k.leftOperand = typeof b == "string" ? this._ExtractOperation(b) : b,
                k.rightOperand = typeof _ == "string" ? this._ExtractOperation(_) : _,
                o.push(k)
            }
        }
        var j = o[o.length - 1];
        return typeof j == "string" && (j = j.replace(regexSERevert, "defined($1)")),
        typeof j == "string" ? this._ExtractOperation(j) : j
    }
    ,
    a._BuildExpression = function(e, i) {
        var o = new ShaderCodeTestNode
          , s = e.substring(0, i)
          , c = e.substring(i);
        return c = c.substring(0, (c.indexOf("//") + 1 || c.length + 1) - 1).trim(),
        s === "#ifdef" ? o.testExpression = new ShaderDefineIsDefinedOperator(c) : s === "#ifndef" ? o.testExpression = new ShaderDefineIsDefinedOperator(c,!0) : o.testExpression = this._BuildSubExpression(c),
        o
    }
    ,
    a._MoveCursorWithinIf = function(e, i, o) {
        for (var s = e.currentLine; this._MoveCursor(e, o); ) {
            s = e.currentLine;
            var c = s.substring(0, 5).toLowerCase();
            if (c === "#else") {
                var d = new ShaderCodeNode;
                i.children.push(d),
                this._MoveCursor(e, d);
                return
            } else if (c === "#elif") {
                var _ = this._BuildExpression(s, 5);
                i.children.push(_),
                o = _
            }
        }
    }
    ,
    a._MoveCursor = function(e, i) {
        for (; e.canRead; ) {
            e.lineIndex++;
            var o = e.currentLine
              , s = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/
              , c = s.exec(o);
            if (c && c.length) {
                var d = c[0];
                switch (d) {
                case "#ifdef":
                    {
                        var _ = new ShaderCodeConditionNode;
                        i.children.push(_);
                        var b = this._BuildExpression(o, 6);
                        _.children.push(b),
                        this._MoveCursorWithinIf(e, _, b);
                        break
                    }
                case "#else":
                case "#elif":
                    return !0;
                case "#endif":
                    return !1;
                case "#ifndef":
                    {
                        var _ = new ShaderCodeConditionNode;
                        i.children.push(_);
                        var b = this._BuildExpression(o, 7);
                        _.children.push(b),
                        this._MoveCursorWithinIf(e, _, b);
                        break
                    }
                case "#if":
                    {
                        var _ = new ShaderCodeConditionNode
                          , b = this._BuildExpression(o, 3);
                        i.children.push(_),
                        _.children.push(b),
                        this._MoveCursorWithinIf(e, _, b);
                        break
                    }
                }
            } else {
                var k = new ShaderCodeNode;
                if (k.line = o,
                i.children.push(k),
                o[0] === "#" && o[1] === "d") {
                    var j = o.replace(";", "").split(" ");
                    k.additionalDefineKey = j[1],
                    j.length === 3 && (k.additionalDefineValue = j[2])
                }
            }
        }
        return !1
    }
    ,
    a._EvaluatePreProcessors = function(e, i, o) {
        var s = new ShaderCodeNode
          , c = new ShaderCodeCursor;
        return c.lineIndex = -1,
        c.lines = e.split(`
`),
        this._MoveCursor(c, s),
        s.process(i, o)
    }
    ,
    a._PreparePreProcessors = function(e, i) {
        for (var o, s = e.defines, c = {}, d = 0, _ = s; d < _.length; d++) {
            var b = _[d]
              , k = b.replace("#define", "").replace(";", "").trim()
              , j = k.split(" ");
            c[j[0]] = j.length > 1 ? j[1] : ""
        }
        return ((o = e.processor) === null || o === void 0 ? void 0 : o.shaderLanguage) === ShaderLanguage.GLSL && (c.GL_ES = "true"),
        c.__VERSION__ = e.version,
        c[e.platformName] = "true",
        i._getGlobalDefines(c),
        c
    }
    ,
    a._ProcessShaderConversion = function(e, i, o) {
        var s = this._ProcessPrecision(e, i);
        if (!i.processor)
            return s;
        if (i.processor.shaderLanguage === ShaderLanguage.GLSL && s.indexOf("#version 3") !== -1)
            return s.replace("#version 300 es", "");
        var c = i.defines
          , d = this._PreparePreProcessors(i, o);
        return i.processor.preProcessor && (s = i.processor.preProcessor(s, c, i.isFragment, i.processingContext)),
        s = this._EvaluatePreProcessors(s, d, i),
        i.processor.postProcessor && (s = i.processor.postProcessor(s, c, i.isFragment, i.processingContext, o)),
        o._features.needShaderCodeInlining && (s = o.inlineShaderCode(s)),
        s
    }
    ,
    a._ApplyPreProcessing = function(e, i, o) {
        var s, c, d = e, _ = i.defines, b = this._PreparePreProcessors(i, o);
        return !((s = i.processor) === null || s === void 0) && s.preProcessor && (d = i.processor.preProcessor(d, _, i.isFragment, i.processingContext)),
        d = this._EvaluatePreProcessors(d, b, i),
        !((c = i.processor) === null || c === void 0) && c.postProcessor && (d = i.processor.postProcessor(d, _, i.isFragment, i.processingContext, o)),
        o._features.needShaderCodeInlining && (d = o.inlineShaderCode(d)),
        d
    }
    ,
    a._ProcessIncludes = function(e, i, o) {
        for (var s = this, c = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g, d = c.exec(e), _ = new String(e), b = !1; d != null; ) {
            var k = d[1];
            if (k.indexOf("__decl__") !== -1 && (k = k.replace(/__decl__/, ""),
            i.supportsUniformBuffers && (k = k.replace(/Vertex/, "Ubo"),
            k = k.replace(/Fragment/, "Ubo")),
            k = k + "Declaration"),
            i.includesShadersStore[k]) {
                var j = i.includesShadersStore[k];
                if (d[2])
                    for (var $ = d[3].split(","), _e = 0; _e < $.length; _e += 2) {
                        var et = new RegExp($[_e],"g")
                          , tt = $[_e + 1];
                        j = j.replace(et, tt)
                    }
                if (d[4]) {
                    var rt = d[5];
                    if (rt.indexOf("..") !== -1) {
                        var it = rt.split("..")
                          , nt = parseInt(it[0])
                          , ot = parseInt(it[1])
                          , at = j.slice(0);
                        j = "",
                        isNaN(ot) && (ot = i.indexParameters[it[1]]);
                        for (var st = nt; st < ot; st++)
                            i.supportsUniformBuffers || (at = at.replace(/light\{X\}.(\w*)/g, function(ct, lt) {
                                return lt + "{X}"
                            })),
                            j += at.replace(/\{X\}/g, st.toString()) + `
`
                    } else
                        i.supportsUniformBuffers || (j = j.replace(/light\{X\}.(\w*)/g, function(ct, lt) {
                            return lt + "{X}"
                        })),
                        j = j.replace(/\{X\}/g, rt)
                }
                _ = _.replace(d[0], j),
                b = b || j.indexOf("#include<") >= 0 || j.indexOf("#include <") >= 0
            } else {
                var ut = i.shadersRepository + "ShadersInclude/" + k + ".fx";
                a._FileToolsLoadFile(ut, function(ct) {
                    i.includesShadersStore[k] = ct,
                    s._ProcessIncludes(_, i, o)
                });
                return
            }
            d = c.exec(e)
        }
        b ? this._ProcessIncludes(_.toString(), i, o) : o(_)
    }
    ,
    a._FileToolsLoadFile = function(e, i, o, s, c, d) {
        throw _WarnImport("FileTools")
    }
    ,
    a
}(), ShaderStore = function() {
    function a() {}
    return a.GetShadersRepository = function(e) {
        return e === void 0 && (e = ShaderLanguage.GLSL),
        e === ShaderLanguage.GLSL ? a.ShadersRepository : a.ShadersRepositoryWGSL
    }
    ,
    a.GetShadersStore = function(e) {
        return e === void 0 && (e = ShaderLanguage.GLSL),
        e === ShaderLanguage.GLSL ? a.ShadersStore : a.ShadersStoreWGSL
    }
    ,
    a.GetIncludesShadersStore = function(e) {
        return e === void 0 && (e = ShaderLanguage.GLSL),
        e === ShaderLanguage.GLSL ? a.IncludesShadersStore : a.IncludesShadersStoreWGSL
    }
    ,
    a.ShadersRepository = "src/Shaders/",
    a.ShadersStore = {},
    a.IncludesShadersStore = {},
    a.ShadersRepositoryWGSL = "src/ShadersWGSL/",
    a.ShadersStoreWGSL = {},
    a.IncludesShadersStoreWGSL = {},
    a
}(), Effect = function() {
    function a(e, i, o, s, c, d, _, b, k, j, $, _e) {
        var et = this;
        s === void 0 && (s = null),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null),
        k === void 0 && (k = null),
        $ === void 0 && ($ = ""),
        _e === void 0 && (_e = ShaderLanguage.GLSL);
        var tt, rt;
        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 = $;
        var it = null;
        if (i.attributes) {
            var nt = i;
            if (this._engine = o,
            this._attributesNames = nt.attributes,
            this._uniformsNames = nt.uniformsNames.concat(nt.samplers),
            this._samplerList = nt.samplers.slice(),
            this.defines = nt.defines,
            this.onError = nt.onError,
            this.onCompiled = nt.onCompiled,
            this._fallbacks = nt.fallbacks,
            this._indexParameters = nt.indexParameters,
            this._transformFeedbackVaryings = nt.transformFeedbackVaryings || null,
            this._multiTarget = !!nt.multiTarget,
            this._shaderLanguage = (tt = nt.shaderLanguage) !== null && tt !== void 0 ? tt : ShaderLanguage.GLSL,
            nt.uniformBuffersNames) {
                this._uniformBuffersNamesList = nt.uniformBuffersNames.slice();
                for (var ot = 0; ot < nt.uniformBuffersNames.length; ot++)
                    this._uniformBuffersNames[nt.uniformBuffersNames[ot]] = ot
            }
            it = (rt = nt.processFinalCode) !== null && rt !== void 0 ? rt : null
        } else
            this._engine = c,
            this.defines = d == null ? "" : d,
            this._uniformsNames = o.concat(s),
            this._samplerList = s ? s.slice() : [],
            this._attributesNames = i,
            this._uniformBuffersNamesList = [],
            this._shaderLanguage = _e,
            this.onError = k,
            this.onCompiled = b,
            this._indexParameters = j,
            this._fallbacks = _;
        this._attributeLocationByName = {},
        this.uniqueId = a._uniqueIdSeed++;
        var at, st, ut = IsWindowObjectExist() ? this._engine.getHostDocument() : null;
        e.vertexSource ? at = "source:" + e.vertexSource : e.vertexElement ? (at = ut ? ut.getElementById(e.vertexElement) : null,
        at || (at = e.vertexElement)) : at = e.vertex || e,
        e.fragmentSource ? st = "source:" + e.fragmentSource : e.fragmentElement ? (st = ut ? ut.getElementById(e.fragmentElement) : null,
        st || (st = e.fragmentElement)) : st = e.fragment || e,
        this._processingContext = this._engine._getShaderProcessingContext(this._shaderLanguage);
        var ct = {
            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
        }
          , lt = [void 0, void 0]
          , ft = function() {
            if (lt[0] && lt[1]) {
                ct.isFragment = !0;
                var ht = lt[0]
                  , pt = lt[1];
                ShaderProcessor.Process(pt, ct, function(dt) {
                    it && (dt = it("fragment", dt));
                    var _t = ShaderProcessor.Finalize(ht, dt, ct);
                    et._useFinalCode(_t.vertexCode, _t.fragmentCode, e)
                }, et._engine)
            }
        };
        this._loadShader(at, "Vertex", "", function(ht) {
            ShaderProcessor.Initialize(ct),
            ShaderProcessor.Process(ht, ct, function(pt) {
                et._rawVertexSourceCode = ht,
                it && (pt = it("vertex", pt)),
                lt[0] = pt,
                ft()
            }, et._engine)
        }),
        this._loadShader(st, "Fragment", "Pixel", function(ht) {
            et._rawFragmentSourceCode = ht,
            lt[1] = ht,
            ft()
        })
    }
    return Object.defineProperty(a, "ShadersRepository", {
        get: function() {
            return ShaderStore.ShadersRepository
        },
        set: function(e) {
            ShaderStore.ShadersRepository = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onBindObservable", {
        get: function() {
            return this._onBindObservable || (this._onBindObservable = new Observable),
            this._onBindObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._useFinalCode = function(e, i, o) {
        if (o) {
            var s = o.vertexElement || o.vertex || o.spectorName || o
              , c = o.fragmentElement || o.fragment || o.spectorName || o;
            this._vertexSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? "//" : "") + "#define SHADER_NAME vertex:" + s + `
` + e,
            this._fragmentSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? "//" : "") + "#define SHADER_NAME fragment:" + c + `
` + i
        } else
            this._vertexSourceCode = e,
            this._fragmentSourceCode = i;
        this._prepareEffect()
    }
    ,
    Object.defineProperty(a.prototype, "key", {
        get: function() {
            return this._key
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.isReady = function() {
        try {
            return this._isReadyInternal()
        } catch {
            return !1
        }
    }
    ,
    a.prototype._isReadyInternal = function() {
        return this._isReady ? !0 : this._pipelineContext ? this._pipelineContext.isReady : !1
    }
    ,
    a.prototype.getEngine = function() {
        return this._engine
    }
    ,
    a.prototype.getPipelineContext = function() {
        return this._pipelineContext
    }
    ,
    a.prototype.getAttributesNames = function() {
        return this._attributesNames
    }
    ,
    a.prototype.getAttributeLocation = function(e) {
        return this._attributes[e]
    }
    ,
    a.prototype.getAttributeLocationByName = function(e) {
        return this._attributeLocationByName[e]
    }
    ,
    a.prototype.getAttributesCount = function() {
        return this._attributes.length
    }
    ,
    a.prototype.getUniformIndex = function(e) {
        return this._uniformsNames.indexOf(e)
    }
    ,
    a.prototype.getUniform = function(e) {
        return this._uniforms[e]
    }
    ,
    a.prototype.getSamplers = function() {
        return this._samplerList
    }
    ,
    a.prototype.getUniformNames = function() {
        return this._uniformsNames
    }
    ,
    a.prototype.getUniformBuffersNames = function() {
        return this._uniformBuffersNamesList
    }
    ,
    a.prototype.getIndexParameters = function() {
        return this._indexParameters
    }
    ,
    a.prototype.getCompilationError = function() {
        return this._compilationError
    }
    ,
    a.prototype.allFallbacksProcessed = function() {
        return this._allFallbacksProcessed
    }
    ,
    a.prototype.executeWhenCompiled = function(e) {
        var i = this;
        if (this.isReady()) {
            e(this);
            return
        }
        this.onCompileObservable.add(function(o) {
            e(o)
        }),
        (!this._pipelineContext || this._pipelineContext.isAsync) && setTimeout(function() {
            i._checkIsReady(null)
        }, 16)
    }
    ,
    a.prototype._checkIsReady = function(e) {
        var i = this;
        try {
            if (this._isReadyInternal())
                return
        } catch (o) {
            this._processCompilationErrors(o, e);
            return
        }
        setTimeout(function() {
            i._checkIsReady(e)
        }, 16)
    }
    ,
    a.prototype._loadShader = function(e, i, o, s) {
        if (typeof HTMLElement != "undefined" && e instanceof HTMLElement) {
            var c = GetDOMTextContent(e);
            s(c);
            return
        }
        if (e.substr(0, 7) === "source:") {
            s(e.substr(7));
            return
        }
        if (e.substr(0, 7) === "base64:") {
            var d = window.atob(e.substr(7));
            s(d);
            return
        }
        var _ = ShaderStore.GetShadersStore(this._shaderLanguage);
        if (_[e + i + "Shader"]) {
            s(_[e + i + "Shader"]);
            return
        }
        if (o && _[e + o + "Shader"]) {
            s(_[e + o + "Shader"]);
            return
        }
        var b;
        e[0] === "." || e[0] === "/" || e.indexOf("http") > -1 ? b = e : b = ShaderStore.GetShadersRepository(this._shaderLanguage) + e,
        this._engine._loadFile(b + "." + i.toLowerCase() + ".fx", s)
    }
    ,
    Object.defineProperty(a.prototype, "vertexSourceCode", {
        get: function() {
            var e, i;
            return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._vertexSourceCodeOverride : (i = (e = this._pipelineContext) === null || e === void 0 ? void 0 : e._getVertexShaderCode()) !== null && i !== void 0 ? i : this._vertexSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "fragmentSourceCode", {
        get: function() {
            var e, i;
            return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._fragmentSourceCodeOverride : (i = (e = this._pipelineContext) === null || e === void 0 ? void 0 : e._getFragmentShaderCode()) !== null && i !== void 0 ? i : this._fragmentSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rawVertexSourceCode", {
        get: function() {
            return this._rawVertexSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rawFragmentSourceCode", {
        get: function() {
            return this._rawFragmentSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._rebuildProgram = function(e, i, o, s) {
        var c = this;
        this._isReady = !1,
        this._vertexSourceCodeOverride = e,
        this._fragmentSourceCodeOverride = i,
        this.onError = function(d, _) {
            s && s(_)
        }
        ,
        this.onCompiled = function() {
            var d = c.getEngine().scenes;
            if (d)
                for (var _ = 0; _ < d.length; _++)
                    d[_].markAllMaterialsAsDirty(63);
            c._pipelineContext._handlesSpectorRebuildCallback(o)
        }
        ,
        this._fallbacks = null,
        this._prepareEffect()
    }
    ,
    a.prototype._prepareEffect = function() {
        var e = this
          , i = this._attributesNames
          , o = this.defines
          , s = this._pipelineContext;
        this._isReady = !1;
        try {
            var c = this._engine;
            this._pipelineContext = c.createPipelineContext(this._processingContext),
            this._pipelineContext._name = this._key;
            var d = this._rebuildProgram.bind(this);
            this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? c._preparePipelineContext(this._pipelineContext, this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, !0, this._rawVertexSourceCode, this._rawFragmentSourceCode, d, null, this._transformFeedbackVaryings, this._key) : c._preparePipelineContext(this._pipelineContext, this._vertexSourceCode, this._fragmentSourceCode, !1, this._rawVertexSourceCode, this._rawFragmentSourceCode, d, o, this._transformFeedbackVaryings, this._key),
            c._executeWhenRenderingStateIsCompiled(this._pipelineContext, function() {
                if (e._attributes = [],
                e._pipelineContext._fillEffectInformation(e, e._uniformBuffersNames, e._uniformsNames, e._uniforms, e._samplerList, e._samplers, i, e._attributes),
                i)
                    for (var _ = 0; _ < i.length; _++) {
                        var b = i[_];
                        e._attributeLocationByName[b] = e._attributes[_]
                    }
                c.bindSamplers(e),
                e._compilationError = "",
                e._isReady = !0,
                e.onCompiled && e.onCompiled(e),
                e.onCompileObservable.notifyObservers(e),
                e.onCompileObservable.clear(),
                e._fallbacks && e._fallbacks.unBindMesh(),
                s && e.getEngine()._deletePipelineContext(s)
            }),
            this._pipelineContext.isAsync && this._checkIsReady(s)
        } catch (_) {
            this._processCompilationErrors(_, s)
        }
    }
    ,
    a.prototype._getShaderCodeAndErrorLine = function(e, i, o) {
        var s = o ? /FRAGMENT SHADER ERROR: 0:(\d+?):/ : /VERTEX SHADER ERROR: 0:(\d+?):/
          , c = null;
        if (i && e) {
            var d = i.match(s);
            if (d && d.length === 2) {
                var _ = parseInt(d[1])
                  , b = e.split(`
`, -1);
                b.length >= _ && (c = "Offending line [" + _ + "] in " + (o ? "fragment" : "vertex") + " code: " + b[_ - 1])
            }
        }
        return [e, c]
    }
    ,
    a.prototype._processCompilationErrors = function(e, i) {
        var o, s, c, d, _;
        i === void 0 && (i = null),
        this._compilationError = e.message;
        var b = this._attributesNames
          , k = this._fallbacks;
        if (Logger$2.Error("Unable to compile effect:"),
        Logger$2.Error("Uniforms: " + this._uniformsNames.map(function(et) {
            return " " + et
        })),
        Logger$2.Error("Attributes: " + b.map(function(et) {
            return " " + et
        })),
        Logger$2.Error(`Defines:\r
` + this.defines),
        a.LogShaderCodeOnCompilationError) {
            var j = null
              , $ = null
              , _e = null;
            !((c = this._pipelineContext) === null || c === void 0) && c._getVertexShaderCode() && (o = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, !1),
            _e = o[0],
            j = o[1],
            _e && (Logger$2.Error("Vertex code:"),
            Logger$2.Error(_e))),
            !((d = this._pipelineContext) === null || d === void 0) && d._getFragmentShaderCode() && (s = this._getShaderCodeAndErrorLine((_ = this._pipelineContext) === null || _ === void 0 ? void 0 : _._getFragmentShaderCode(), this._compilationError, !0),
            _e = s[0],
            $ = s[1],
            _e && (Logger$2.Error("Fragment code:"),
            Logger$2.Error(_e))),
            j && Logger$2.Error(j),
            $ && Logger$2.Error($)
        }
        Logger$2.Error("Error: " + this._compilationError),
        i && (this._pipelineContext = i,
        this._isReady = !0,
        this.onError && this.onError(this, this._compilationError),
        this.onErrorObservable.notifyObservers(this)),
        k ? (this._pipelineContext = null,
        k.hasMoreFallbacks ? (this._allFallbacksProcessed = !1,
        Logger$2.Error("Trying next fallback."),
        this.defines = k.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(a.prototype, "isSupported", {
        get: function() {
            return this._compilationError === ""
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._bindTexture = function(e, i) {
        this._engine._bindTexture(this._samplers[e], i, e)
    }
    ,
    a.prototype.setTexture = function(e, i) {
        this._engine.setTexture(this._samplers[e], this._uniforms[e], i, e)
    }
    ,
    a.prototype.setDepthStencilTexture = function(e, i) {
        this._engine.setDepthStencilTexture(this._samplers[e], this._uniforms[e], i, e)
    }
    ,
    a.prototype.setTextureArray = function(e, i) {
        var o = e + "Ex";
        if (this._samplerList.indexOf(o + "0") === -1) {
            for (var s = this._samplerList.indexOf(e), c = 1; c < i.length; c++) {
                var d = o + (c - 1).toString();
                this._samplerList.splice(s + c, 0, d)
            }
            for (var _ = 0, b = 0, k = this._samplerList; b < k.length; b++) {
                var j = k[b];
                this._samplers[j] = _,
                _ += 1
            }
        }
        this._engine.setTextureArray(this._samplers[e], this._uniforms[e], i, e)
    }
    ,
    a.prototype.setTextureFromPostProcess = function(e, i) {
        this._engine.setTextureFromPostProcess(this._samplers[e], i, e)
    }
    ,
    a.prototype.setTextureFromPostProcessOutput = function(e, i) {
        this._engine.setTextureFromPostProcessOutput(this._samplers[e], i, e)
    }
    ,
    a.prototype.bindUniformBuffer = function(e, i) {
        var o = this._uniformBuffersNames[i];
        o === void 0 || a._baseCache[o] === e && this._engine._features.useUBOBindingCache || (a._baseCache[o] = e,
        this._engine.bindUniformBufferBase(e, o, i))
    }
    ,
    a.prototype.bindUniformBlock = function(e, i) {
        this._engine.bindUniformBlock(this._pipelineContext, e, i)
    }
    ,
    a.prototype.setInt = function(e, i) {
        return this._pipelineContext.setInt(e, i),
        this
    }
    ,
    a.prototype.setInt2 = function(e, i, o) {
        return this._pipelineContext.setInt2(e, i, o),
        this
    }
    ,
    a.prototype.setInt3 = function(e, i, o, s) {
        return this._pipelineContext.setInt3(e, i, o, s),
        this
    }
    ,
    a.prototype.setInt4 = function(e, i, o, s, c) {
        return this._pipelineContext.setInt4(e, i, o, s, c),
        this
    }
    ,
    a.prototype.setIntArray = function(e, i) {
        return this._pipelineContext.setIntArray(e, i),
        this
    }
    ,
    a.prototype.setIntArray2 = function(e, i) {
        return this._pipelineContext.setIntArray2(e, i),
        this
    }
    ,
    a.prototype.setIntArray3 = function(e, i) {
        return this._pipelineContext.setIntArray3(e, i),
        this
    }
    ,
    a.prototype.setIntArray4 = function(e, i) {
        return this._pipelineContext.setIntArray4(e, i),
        this
    }
    ,
    a.prototype.setFloatArray = function(e, i) {
        return this._pipelineContext.setArray(e, i),
        this
    }
    ,
    a.prototype.setFloatArray2 = function(e, i) {
        return this._pipelineContext.setArray2(e, i),
        this
    }
    ,
    a.prototype.setFloatArray3 = function(e, i) {
        return this._pipelineContext.setArray3(e, i),
        this
    }
    ,
    a.prototype.setFloatArray4 = function(e, i) {
        return this._pipelineContext.setArray4(e, i),
        this
    }
    ,
    a.prototype.setArray = function(e, i) {
        return this._pipelineContext.setArray(e, i),
        this
    }
    ,
    a.prototype.setArray2 = function(e, i) {
        return this._pipelineContext.setArray2(e, i),
        this
    }
    ,
    a.prototype.setArray3 = function(e, i) {
        return this._pipelineContext.setArray3(e, i),
        this
    }
    ,
    a.prototype.setArray4 = function(e, i) {
        return this._pipelineContext.setArray4(e, i),
        this
    }
    ,
    a.prototype.setMatrices = function(e, i) {
        return this._pipelineContext.setMatrices(e, i),
        this
    }
    ,
    a.prototype.setMatrix = function(e, i) {
        return this._pipelineContext.setMatrix(e, i),
        this
    }
    ,
    a.prototype.setMatrix3x3 = function(e, i) {
        return this._pipelineContext.setMatrix3x3(e, i),
        this
    }
    ,
    a.prototype.setMatrix2x2 = function(e, i) {
        return this._pipelineContext.setMatrix2x2(e, i),
        this
    }
    ,
    a.prototype.setFloat = function(e, i) {
        return this._pipelineContext.setFloat(e, i),
        this
    }
    ,
    a.prototype.setBool = function(e, i) {
        return this._pipelineContext.setInt(e, i ? 1 : 0),
        this
    }
    ,
    a.prototype.setVector2 = function(e, i) {
        return this._pipelineContext.setVector2(e, i),
        this
    }
    ,
    a.prototype.setFloat2 = function(e, i, o) {
        return this._pipelineContext.setFloat2(e, i, o),
        this
    }
    ,
    a.prototype.setVector3 = function(e, i) {
        return this._pipelineContext.setVector3(e, i),
        this
    }
    ,
    a.prototype.setFloat3 = function(e, i, o, s) {
        return this._pipelineContext.setFloat3(e, i, o, s),
        this
    }
    ,
    a.prototype.setVector4 = function(e, i) {
        return this._pipelineContext.setVector4(e, i),
        this
    }
    ,
    a.prototype.setFloat4 = function(e, i, o, s, c) {
        return this._pipelineContext.setFloat4(e, i, o, s, c),
        this
    }
    ,
    a.prototype.setColor3 = function(e, i) {
        return this._pipelineContext.setColor3(e, i),
        this
    }
    ,
    a.prototype.setColor4 = function(e, i, o) {
        return this._pipelineContext.setColor4(e, i, o),
        this
    }
    ,
    a.prototype.setDirectColor4 = function(e, i) {
        return this._pipelineContext.setDirectColor4(e, i),
        this
    }
    ,
    a.prototype.dispose = function() {
        this._pipelineContext && this._pipelineContext.dispose(),
        this._engine._releaseEffect(this)
    }
    ,
    a.RegisterShader = function(e, i, o, s) {
        s === void 0 && (s = ShaderLanguage.GLSL),
        i && (ShaderStore.GetShadersStore(s)[e + "PixelShader"] = i),
        o && (ShaderStore.GetShadersStore(s)[e + "VertexShader"] = o)
    }
    ,
    a.ResetCache = function() {
        a._baseCache = {}
    }
    ,
    a.LogShaderCodeOnCompilationError = !0,
    a._uniqueIdSeed = 0,
    a._baseCache = {},
    a.ShadersStore = ShaderStore.ShadersStore,
    a.IncludesShadersStore = ShaderStore.IncludesShadersStore,
    a
}(), DepthCullingState = function() {
    function a(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(a.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(a.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(a.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(a.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(a.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(a.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(a.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(a.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(a.prototype, "frontFace", {
        get: function() {
            return this._frontFace
        },
        set: function(e) {
            this._frontFace !== e && (this._frontFace = e,
            this._isFrontFaceDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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
    }
    ,
    a.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))
    }
    ,
    a
}(), StencilState = function() {
    function a() {
        this.reset()
    }
    return a.prototype.reset = function() {
        this.enabled = !1,
        this.mask = 255,
        this.func = a.ALWAYS,
        this.funcRef = 1,
        this.funcMask = 255,
        this.opStencilFail = a.KEEP,
        this.opDepthFail = a.KEEP,
        this.opStencilDepthPass = a.REPLACE
    }
    ,
    Object.defineProperty(a.prototype, "stencilFunc", {
        get: function() {
            return this.func
        },
        set: function(e) {
            this.func = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilFuncRef", {
        get: function() {
            return this.funcRef
        },
        set: function(e) {
            this.funcRef = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilFuncMask", {
        get: function() {
            return this.funcMask
        },
        set: function(e) {
            this.funcMask = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilOpStencilFail", {
        get: function() {
            return this.opStencilFail
        },
        set: function(e) {
            this.opStencilFail = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilOpDepthFail", {
        get: function() {
            return this.opDepthFail
        },
        set: function(e) {
            this.opDepthFail = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilOpStencilDepthPass", {
        get: function() {
            return this.opStencilDepthPass
        },
        set: function(e) {
            this.opStencilDepthPass = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilMask", {
        get: function() {
            return this.mask
        },
        set: function(e) {
            this.mask = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilTest", {
        get: function() {
            return this.enabled
        },
        set: function(e) {
            this.enabled = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.ALWAYS = 519,
    a.KEEP = 7680,
    a.REPLACE = 7681,
    a
}(), AlphaState = function() {
    function a() {
        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(a.prototype, "isDirty", {
        get: function() {
            return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "alphaBlend", {
        get: function() {
            return this._alphaBlend
        },
        set: function(e) {
            this._alphaBlend !== e && (this._alphaBlend = e,
            this._isAlphaBlendDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setAlphaBlendConstants = function(e, i, o, s) {
        this._blendConstants[0] === e && this._blendConstants[1] === i && this._blendConstants[2] === o && this._blendConstants[3] === s || (this._blendConstants[0] = e,
        this._blendConstants[1] = i,
        this._blendConstants[2] = o,
        this._blendConstants[3] = s,
        this._isBlendConstantsDirty = !0)
    }
    ,
    a.prototype.setAlphaBlendFunctionParameters = function(e, i, o, s) {
        this._blendFunctionParameters[0] === e && this._blendFunctionParameters[1] === i && this._blendFunctionParameters[2] === o && this._blendFunctionParameters[3] === s || (this._blendFunctionParameters[0] = e,
        this._blendFunctionParameters[1] = i,
        this._blendFunctionParameters[2] = o,
        this._blendFunctionParameters[3] = s,
        this._isBlendFunctionParametersDirty = !0)
    }
    ,
    a.prototype.setAlphaEquationParameters = function(e, i) {
        this._blendEquationParameters[0] === e && this._blendEquationParameters[1] === i || (this._blendEquationParameters[0] = e,
        this._blendEquationParameters[1] = i,
        this._isBlendEquationParametersDirty = !0)
    }
    ,
    a.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
    }
    ,
    a.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))
    }
    ,
    a
}(), TextureSampler = function() {
    function a() {
        this.samplingMode = -1,
        this._useMipMaps = !0,
        this._cachedWrapU = null,
        this._cachedWrapV = null,
        this._cachedWrapR = null,
        this._cachedAnisotropicFilteringLevel = null,
        this._comparisonFunction = 0
    }
    return Object.defineProperty(a.prototype, "wrapU", {
        get: function() {
            return this._cachedWrapU
        },
        set: function(e) {
            this._cachedWrapU = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "wrapV", {
        get: function() {
            return this._cachedWrapV
        },
        set: function(e) {
            this._cachedWrapV = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "wrapR", {
        get: function() {
            return this._cachedWrapR
        },
        set: function(e) {
            this._cachedWrapR = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "anisotropicFilteringLevel", {
        get: function() {
            return this._cachedAnisotropicFilteringLevel
        },
        set: function(e) {
            this._cachedAnisotropicFilteringLevel = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "comparisonFunction", {
        get: function() {
            return this._comparisonFunction
        },
        set: function(e) {
            this._comparisonFunction = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "useMipMaps", {
        get: function() {
            return this._useMipMaps
        },
        set: function(e) {
            this._useMipMaps = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setParameters = function(e, i, o, s, c, d) {
        return e === void 0 && (e = 1),
        i === void 0 && (i = 1),
        o === void 0 && (o = 1),
        s === void 0 && (s = 1),
        c === void 0 && (c = 2),
        d === void 0 && (d = 0),
        this._cachedWrapU = e,
        this._cachedWrapV = i,
        this._cachedWrapR = o,
        this._cachedAnisotropicFilteringLevel = s,
        this.samplingMode = c,
        this._comparisonFunction = d,
        this
    }
    ,
    a.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
    }
    ,
    a
}(), InternalTextureSource;
(function(a) {
    a[a.Unknown = 0] = "Unknown",
    a[a.Url = 1] = "Url",
    a[a.Temp = 2] = "Temp",
    a[a.Raw = 3] = "Raw",
    a[a.Dynamic = 4] = "Dynamic",
    a[a.RenderTarget = 5] = "RenderTarget",
    a[a.MultiRenderTarget = 6] = "MultiRenderTarget",
    a[a.Cube = 7] = "Cube",
    a[a.CubeRaw = 8] = "CubeRaw",
    a[a.CubePrefiltered = 9] = "CubePrefiltered",
    a[a.Raw3D = 10] = "Raw3D",
    a[a.Raw2DArray = 11] = "Raw2DArray",
    a[a.DepthStencil = 12] = "DepthStencil",
    a[a.CubeRawRGBD = 13] = "CubeRawRGBD",
    a[a.Depth = 14] = "Depth"
}
)(InternalTextureSource || (InternalTextureSource = {}));
var InternalTexture = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        s === void 0 && (s = !1);
        var c = a.call(this) || this;
        return c.isReady = !1,
        c.isCube = !1,
        c.is3D = !1,
        c.is2DArray = !1,
        c.isMultiview = !1,
        c.url = "",
        c.generateMipMaps = !1,
        c.samples = 0,
        c.type = -1,
        c.format = -1,
        c.onLoadedObservable = new Observable,
        c.onErrorObservable = new Observable,
        c.onRebuildCallback = null,
        c.width = 0,
        c.height = 0,
        c.depth = 0,
        c.baseWidth = 0,
        c.baseHeight = 0,
        c.baseDepth = 0,
        c.invertY = !1,
        c._invertVScale = !1,
        c._associatedChannel = -1,
        c._source = InternalTextureSource.Unknown,
        c._buffer = null,
        c._bufferView = null,
        c._bufferViewArray = null,
        c._bufferViewArrayArray = null,
        c._size = 0,
        c._extension = "",
        c._files = null,
        c._workingCanvas = null,
        c._workingContext = null,
        c._cachedCoordinatesMode = null,
        c._isDisabled = !1,
        c._compression = null,
        c._sphericalPolynomial = null,
        c._sphericalPolynomialPromise = null,
        c._sphericalPolynomialComputed = !1,
        c._lodGenerationScale = 0,
        c._lodGenerationOffset = 0,
        c._useSRGBBuffer = !1,
        c._lodTextureHigh = null,
        c._lodTextureMid = null,
        c._lodTextureLow = null,
        c._isRGBD = !1,
        c._linearSpecularLOD = !1,
        c._irradianceTexture = null,
        c._hardwareTexture = null,
        c._references = 1,
        c._gammaSpace = null,
        c._engine = i,
        c._source = o,
        c._uniqueId = e._Counter++,
        s || (c._hardwareTexture = i._createHardwareTexture()),
        c
    }
    return Object.defineProperty(e.prototype, "useMipMaps", {
        get: function() {
            return this.generateMipMaps
        },
        set: function(i) {
            this.generateMipMaps = i
        },
        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(i, o, s) {
        s === void 0 && (s = 1),
        this._engine.updateTextureDimensions(this, i, o, s),
        this.width = i,
        this.height = o,
        this.depth = s,
        this.baseWidth = i,
        this.baseHeight = o,
        this.baseDepth = s,
        this._size = i * o * s
    }
    ,
    e.prototype._rebuild = function() {
        var i = this, o;
        if (this.isReady = !1,
        this._cachedCoordinatesMode = null,
        this._cachedWrapU = null,
        this._cachedWrapV = null,
        this._cachedWrapR = null,
        this._cachedAnisotropicFilteringLevel = null,
        this.onRebuildCallback) {
            var s = this.onRebuildCallback(this)
              , c = function(_) {
                _._swapAndDie(i, !1),
                i.isReady = s.isReady
            };
            s.isAsync ? s.proxy.then(c) : c(s.proxy);
            return
        }
        var d;
        switch (this.source) {
        case InternalTextureSource.Temp:
            break;
        case InternalTextureSource.Url:
            d = this._engine.createTexture((o = this._originalUrl) !== null && o !== void 0 ? o : this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function() {
                d._swapAndDie(i, !1),
                i.isReady = !0
            }, null, this._buffer, void 0, this.format, this._extension, void 0, void 0, void 0, this._useSRGBBuffer);
            return;
        case InternalTextureSource.Raw:
            d = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type),
            d._swapAndDie(this, !1),
            this.isReady = !0;
            break;
        case InternalTextureSource.Raw3D:
            d = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type),
            d._swapAndDie(this, !1),
            this.isReady = !0;
            break;
        case InternalTextureSource.Raw2DArray:
            d = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type),
            d._swapAndDie(this, !1),
            this.isReady = !0;
            break;
        case InternalTextureSource.Dynamic:
            d = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode),
            d._swapAndDie(this, !1),
            this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, void 0, void 0, !0);
            break;
        case InternalTextureSource.Cube:
            d = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function() {
                d._swapAndDie(i, !1),
                i.isReady = !0
            }, null, this.format, this._extension, !1, 0, 0, null, void 0, this._useSRGBBuffer);
            return;
        case InternalTextureSource.CubeRaw:
            d = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression),
            d._swapAndDie(this, !1),
            this.isReady = !0;
            break;
        case InternalTextureSource.CubeRawRGBD:
            return;
        case InternalTextureSource.CubePrefiltered:
            d = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function(_) {
                _ && _._swapAndDie(i, !1),
                i.isReady = !0
            }, null, this.format, this._extension),
            d._sphericalPolynomial = this._sphericalPolynomial;
            return
        }
    }
    ,
    e.prototype._swapAndDie = function(i, o) {
        var s;
        o === void 0 && (o = !0),
        (s = this._hardwareTexture) === null || s === void 0 || s.setUsage(i._source, this.generateMipMaps, this.isCube, this.width, this.height),
        i._hardwareTexture = this._hardwareTexture,
        o && (i._isRGBD = this._isRGBD),
        this._lodTextureHigh && (i._lodTextureHigh && i._lodTextureHigh.dispose(),
        i._lodTextureHigh = this._lodTextureHigh),
        this._lodTextureMid && (i._lodTextureMid && i._lodTextureMid.dispose(),
        i._lodTextureMid = this._lodTextureMid),
        this._lodTextureLow && (i._lodTextureLow && i._lodTextureLow.dispose(),
        i._lodTextureLow = this._lodTextureLow),
        this._irradianceTexture && (i._irradianceTexture && i._irradianceTexture.dispose(),
        i._irradianceTexture = this._irradianceTexture);
        var c = this._engine.getLoadedTexturesCache()
          , d = c.indexOf(this);
        d !== -1 && c.splice(d, 1);
        var d = c.indexOf(i);
        d === -1 && c.push(i)
    }
    ,
    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 a() {
        this.shaderLanguage = ShaderLanguage.GLSL
    }
    return a.prototype.postProcessor = function(e, i, o, s, c) {
        if (!c.getCaps().drawBuffersExtension) {
            var d = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g;
            e = e.replace(d, "")
        }
        return e
    }
    ,
    a
}()
  , WebGL2ShaderProcessor = function() {
    function a() {
        this.shaderLanguage = ShaderLanguage.GLSL
    }
    return a.prototype.attributeProcessor = function(e) {
        return e.replace("attribute", "in")
    }
    ,
    a.prototype.varyingProcessor = function(e, i) {
        return e.replace("varying", i ? "in" : "out")
    }
    ,
    a.prototype.postProcessor = function(e, i, o, s, c) {
        var d = e.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1
          , _ = /#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(_, ""),
        e = e.replace(/texture2D\s*\(/g, "texture("),
        o)
            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, (d ? "" : `out vec4 glFragColor;
`) + "void main(");
        else {
            var b = i.indexOf("#define MULTIVIEW") !== -1;
            if (b)
                return `#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
` + e
        }
        return e
    }
    ,
    a
}()
  , DataBuffer = function() {
    function a() {
        this.references = 0,
        this.capacity = 0,
        this.is32Bits = !1,
        this.uniqueId = a._Counter++
    }
    return Object.defineProperty(a.prototype, "underlyingResource", {
        get: function() {
            return null
        },
        enumerable: !1,
        configurable: !0
    }),
    a._Counter = 0,
    a
}()
  , WebGLDataBuffer = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this) || this;
        return o._buffer = i,
        o
    }
    return Object.defineProperty(e.prototype, "underlyingResource", {
        get: function() {
            return this._buffer
        },
        enumerable: !1,
        configurable: !0
    }),
    e
}(DataBuffer)
  , WebGLPipelineContext = function() {
    function a() {
        this._valueCache = {},
        this.vertexCompilationError = null,
        this.fragmentCompilationError = null,
        this.programLinkError = null,
        this.programValidationError = null
    }
    return Object.defineProperty(a.prototype, "isAsync", {
        get: function() {
            return this.isParallelCompiled
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isReady", {
        get: function() {
            return this.program ? this.isParallelCompiled ? this.engine._isRenderingStateCompiled(this) : !0 : !1
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._handlesSpectorRebuildCallback = function(e) {
        e && this.program && e(this.program)
    }
    ,
    a.prototype._fillEffectInformation = function(e, i, o, s, c, d, _, b) {
        var k = this.engine;
        if (k.supportsUniformBuffers)
            for (var j in i)
                e.bindUniformBlock(j, i[j]);
        var $ = this.engine.getUniforms(this, o);
        $.forEach(function(nt, ot) {
            s[o[ot]] = nt
        }),
        this._uniforms = s;
        var _e;
        for (_e = 0; _e < c.length; _e++) {
            var et = e.getUniform(c[_e]);
            et == null && (c.splice(_e, 1),
            _e--)
        }
        c.forEach(function(nt, ot) {
            d[nt] = ot
        });
        for (var tt = 0, rt = k.getAttributes(this, _); tt < rt.length; tt++) {
            var it = rt[tt];
            b.push(it)
        }
    }
    ,
    a.prototype.dispose = function() {
        this._uniforms = {}
    }
    ,
    a.prototype._cacheMatrix = function(e, i) {
        var o = this._valueCache[e]
          , s = i.updateFlag;
        return o !== void 0 && o === s ? !1 : (this._valueCache[e] = s,
        !0)
    }
    ,
    a.prototype._cacheFloat2 = function(e, i, o) {
        var s = this._valueCache[e];
        if (!s || s.length !== 2)
            return s = [i, o],
            this._valueCache[e] = s,
            !0;
        var c = !1;
        return s[0] !== i && (s[0] = i,
        c = !0),
        s[1] !== o && (s[1] = o,
        c = !0),
        c
    }
    ,
    a.prototype._cacheFloat3 = function(e, i, o, s) {
        var c = this._valueCache[e];
        if (!c || c.length !== 3)
            return c = [i, o, s],
            this._valueCache[e] = c,
            !0;
        var d = !1;
        return c[0] !== i && (c[0] = i,
        d = !0),
        c[1] !== o && (c[1] = o,
        d = !0),
        c[2] !== s && (c[2] = s,
        d = !0),
        d
    }
    ,
    a.prototype._cacheFloat4 = function(e, i, o, s, c) {
        var d = this._valueCache[e];
        if (!d || d.length !== 4)
            return d = [i, o, s, c],
            this._valueCache[e] = d,
            !0;
        var _ = !1;
        return d[0] !== i && (d[0] = i,
        _ = !0),
        d[1] !== o && (d[1] = o,
        _ = !0),
        d[2] !== s && (d[2] = s,
        _ = !0),
        d[3] !== c && (d[3] = c,
        _ = !0),
        _
    }
    ,
    a.prototype.setInt = function(e, i) {
        var o = this._valueCache[e];
        o !== void 0 && o === i || this.engine.setInt(this._uniforms[e], i) && (this._valueCache[e] = i)
    }
    ,
    a.prototype.setInt2 = function(e, i, o) {
        this._cacheFloat2(e, i, o) && (this.engine.setInt2(this._uniforms[e], i, o) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setInt3 = function(e, i, o, s) {
        this._cacheFloat3(e, i, o, s) && (this.engine.setInt3(this._uniforms[e], i, o, s) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setInt4 = function(e, i, o, s, c) {
        this._cacheFloat4(e, i, o, s, c) && (this.engine.setInt4(this._uniforms[e], i, o, s, c) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setIntArray = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setIntArray(this._uniforms[e], i)
    }
    ,
    a.prototype.setIntArray2 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setIntArray2(this._uniforms[e], i)
    }
    ,
    a.prototype.setIntArray3 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setIntArray3(this._uniforms[e], i)
    }
    ,
    a.prototype.setIntArray4 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setIntArray4(this._uniforms[e], i)
    }
    ,
    a.prototype.setArray = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setArray(this._uniforms[e], i)
    }
    ,
    a.prototype.setArray2 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setArray2(this._uniforms[e], i)
    }
    ,
    a.prototype.setArray3 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setArray3(this._uniforms[e], i)
    }
    ,
    a.prototype.setArray4 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setArray4(this._uniforms[e], i)
    }
    ,
    a.prototype.setMatrices = function(e, i) {
        !i || (this._valueCache[e] = null,
        this.engine.setMatrices(this._uniforms[e], i))
    }
    ,
    a.prototype.setMatrix = function(e, i) {
        this._cacheMatrix(e, i) && (this.engine.setMatrices(this._uniforms[e], i.toArray()) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setMatrix3x3 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setMatrix3x3(this._uniforms[e], i)
    }
    ,
    a.prototype.setMatrix2x2 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setMatrix2x2(this._uniforms[e], i)
    }
    ,
    a.prototype.setFloat = function(e, i) {
        var o = this._valueCache[e];
        o !== void 0 && o === i || this.engine.setFloat(this._uniforms[e], i) && (this._valueCache[e] = i)
    }
    ,
    a.prototype.setVector2 = function(e, i) {
        this._cacheFloat2(e, i.x, i.y) && (this.engine.setFloat2(this._uniforms[e], i.x, i.y) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setFloat2 = function(e, i, o) {
        this._cacheFloat2(e, i, o) && (this.engine.setFloat2(this._uniforms[e], i, o) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setVector3 = function(e, i) {
        this._cacheFloat3(e, i.x, i.y, i.z) && (this.engine.setFloat3(this._uniforms[e], i.x, i.y, i.z) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setFloat3 = function(e, i, o, s) {
        this._cacheFloat3(e, i, o, s) && (this.engine.setFloat3(this._uniforms[e], i, o, s) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setVector4 = function(e, i) {
        this._cacheFloat4(e, i.x, i.y, i.z, i.w) && (this.engine.setFloat4(this._uniforms[e], i.x, i.y, i.z, i.w) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setFloat4 = function(e, i, o, s, c) {
        this._cacheFloat4(e, i, o, s, c) && (this.engine.setFloat4(this._uniforms[e], i, o, s, c) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setColor3 = function(e, i) {
        this._cacheFloat3(e, i.r, i.g, i.b) && (this.engine.setFloat3(this._uniforms[e], i.r, i.g, i.b) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setColor4 = function(e, i, o) {
        this._cacheFloat4(e, i.r, i.g, i.b, o) && (this.engine.setFloat4(this._uniforms[e], i.r, i.g, i.b, o) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setDirectColor4 = function(e, i) {
        this._cacheFloat4(e, i.r, i.g, i.b, i.a) && (this.engine.setFloat4(this._uniforms[e], i.r, i.g, i.b, i.a) || (this._valueCache[e] = null))
    }
    ,
    a.prototype._getVertexShaderCode = function() {
        return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null
    }
    ,
    a.prototype._getFragmentShaderCode = function() {
        return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null
    }
    ,
    a
}()
  , PerformanceConfigurator = function() {
    function a() {}
    return a.SetMatrixPrecision = function(e) {
        if (a.MatrixTrackPrecisionChange = !1,
        e && !a.MatrixUse64Bits && a.MatrixTrackedMatrices)
            for (var i = 0; i < a.MatrixTrackedMatrices.length; ++i) {
                var o = a.MatrixTrackedMatrices[i]
                  , s = o._m;
                o._m = new Array(16);
                for (var c = 0; c < 16; ++c)
                    o._m[c] = s[c]
            }
        a.MatrixUse64Bits = e,
        a.MatrixCurrentType = a.MatrixUse64Bits ? Array : Float32Array,
        a.MatrixTrackedMatrices = null
    }
    ,
    a.MatrixUse64Bits = !1,
    a.MatrixTrackPrecisionChange = !0,
    a.MatrixCurrentType = Float32Array,
    a.MatrixTrackedMatrices = [],
    a
}()
  , WebGLHardwareTexture = function() {
    function a(e, i) {
        if (e === void 0 && (e = null),
        this._MSAARenderBuffer = null,
        this._context = i,
        !e && (e = i.createTexture(),
        !e))
            throw new Error("Unable to create webGL texture");
        this.set(e)
    }
    return Object.defineProperty(a.prototype, "underlyingResource", {
        get: function() {
            return this._webGLTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setUsage = function(e, i, o, s, c) {}
    ,
    a.prototype.set = function(e) {
        this._webGLTexture = e
    }
    ,
    a.prototype.reset = function() {
        this._webGLTexture = null,
        this._MSAARenderBuffer = null
    }
    ,
    a.prototype.release = function() {
        this._MSAARenderBuffer && (this._context.deleteRenderbuffer(this._MSAARenderBuffer),
        this._MSAARenderBuffer = null),
        this._webGLTexture && this._context.deleteTexture(this._webGLTexture),
        this.reset()
    }
    ,
    a
}()
  , DrawWrapper = function() {
    function a(e, i) {
        i === void 0 && (i = !0),
        this.effect = null,
        this.defines = null,
        this.drawContext = e.createDrawContext(),
        i && (this.materialContext = e.createMaterialContext())
    }
    return a.IsWrapper = function(e) {
        return e.getPipelineContext === void 0
    }
    ,
    a.GetEffect = function(e) {
        return e.getPipelineContext === void 0 ? e.effect : e
    }
    ,
    a.prototype.setEffect = function(e, i, o) {
        var s;
        o === void 0 && (o = !0),
        this.effect = e,
        i !== void 0 && (this.defines = i),
        o && ((s = this.drawContext) === null || s === void 0 || s.reset())
    }
    ,
    a.prototype.dispose = function() {
        var e;
        (e = this.drawContext) === null || e === void 0 || e.dispose()
    }
    ,
    a
}()
  , StencilStateComposer = function() {
    function a(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(a.prototype, "isDirty", {
        get: function() {
            return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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(a.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(a.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(a.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(a.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(a.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(a.prototype, "enabled", {
        get: function() {
            return this._enabled
        },
        set: function(e) {
            this._enabled !== e && (this._enabled = e,
            this._isStencilTestDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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
    }
    ,
    a.prototype.apply = function(e) {
        var i;
        if (!!e) {
            var o = !this.useStencilGlobalOnly && !!(!((i = this.stencilMaterial) === null || i === void 0) && i.enabled);
            this.enabled = o ? this.stencilMaterial.enabled : this.stencilGlobal.enabled,
            this.func = o ? this.stencilMaterial.func : this.stencilGlobal.func,
            this.funcRef = o ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef,
            this.funcMask = o ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask,
            this.opStencilFail = o ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail,
            this.opDepthFail = o ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail,
            this.opStencilDepthPass = o ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass,
            this.mask = o ? 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))
        }
    }
    ,
    a
}()
  , BufferPointer = function() {
    function a() {}
    return a
}()
  , ThinEngine = function() {
    function a(e, i, o, s) {
        var c = 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 d = null;
        if (o = o || {},
        this._stencilStateComposer.stencilGlobal = this._stencilState,
        PerformanceConfigurator.SetMatrixPrecision(!!o.useHighPrecisionMatrix),
        !!e) {
            if (s = s || o.adaptToDeviceRatio || !1,
            e.getContext) {
                if (d = e,
                this._renderingCanvas = d,
                i !== void 0 && (o.antialias = i),
                o.deterministicLockstep === void 0 && (o.deterministicLockstep = !1),
                o.lockstepMaxSteps === void 0 && (o.lockstepMaxSteps = 4),
                o.timeStep === void 0 && (o.timeStep = 1 / 60),
                o.preserveDrawingBuffer === void 0 && (o.preserveDrawingBuffer = !1),
                o.audioEngine === void 0 && (o.audioEngine = !0),
                o.audioEngineOptions !== void 0 && o.audioEngineOptions.audioContext !== void 0 && (this._audioContext = o.audioEngineOptions.audioContext),
                o.audioEngineOptions !== void 0 && o.audioEngineOptions.audioDestination !== void 0 && (this._audioDestination = o.audioEngineOptions.audioDestination),
                o.stencil === void 0 && (o.stencil = !0),
                o.premultipliedAlpha === !1 && (this.premultipliedAlpha = !1),
                o.xrCompatible === void 0 && (o.xrCompatible = !0),
                this._doNotHandleContextLost = !!o.doNotHandleContextLost,
                navigator && navigator.userAgent) {
                    this._checkForMobile = function() {
                        var dt = navigator.userAgent;
                        c.hostInformation.isMobile = dt.indexOf("Mobile") !== -1 || dt.indexOf("Mac") !== -1 && IsDocumentAvailable() && "ontouchend"in document
                    }
                    ,
                    this._checkForMobile(),
                    IsWindowObjectExist() && window.addEventListener("resize", this._checkForMobile);
                    for (var _ = navigator.userAgent, b = 0, k = a.ExceptionList; b < k.length; b++) {
                        var j = k[b]
                          , $ = j.key
                          , _e = j.targets
                          , et = new RegExp($);
                        if (et.test(_)) {
                            if (j.capture && j.captureConstraint) {
                                var tt = j.capture
                                  , rt = j.captureConstraint
                                  , it = new RegExp(tt)
                                  , nt = it.exec(_);
                                if (nt && nt.length > 0) {
                                    var ot = parseInt(nt[nt.length - 1]);
                                    if (ot >= rt)
                                        continue
                                }
                            }
                            for (var at = 0, st = _e; at < st.length; at++) {
                                var ut = st[at];
                                switch (ut) {
                                case "uniformBuffer":
                                    this.disableUniformBuffers = !0;
                                    break;
                                case "vao":
                                    this.disableVertexArrayObjects = !0;
                                    break
                                }
                            }
                        }
                    }
                }
                if (this._doNotHandleContextLost || (this._onContextLost = function(dt) {
                    dt.preventDefault(),
                    c._contextWasLost = !0,
                    Logger$2.Warn("WebGL context lost."),
                    c.onContextLostObservable.notifyObservers(c)
                }
                ,
                this._onContextRestored = function() {
                    c._restoreEngineAfterContextLost(c._initGLContext.bind(c))
                }
                ,
                d.addEventListener("webglcontextlost", this._onContextLost, !1),
                d.addEventListener("webglcontextrestored", this._onContextRestored, !1),
                o.powerPreference = "high-performance"),
                this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent),
                this._badDesktopOS && (o.xrCompatible = !1),
                !o.disableWebGL2Support)
                    try {
                        this._gl = d.getContext("webgl2", o) || d.getContext("experimental-webgl2", o),
                        this._gl && (this._webGLVersion = 2,
                        this._shaderPlatformName = "WEBGL2",
                        this._gl.deleteQuery || (this._webGLVersion = 1,
                        this._shaderPlatformName = "WEBGL1"))
                    } catch {}
                if (!this._gl) {
                    if (!d)
                        throw new Error("The provided canvas is null or undefined.");
                    try {
                        this._gl = d.getContext("webgl", o) || d.getContext("experimental-webgl", o)
                    } 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 ct = this._gl.getContextAttributes();
                ct && (o.stencil = ct.stencil)
            }
            this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE),
            o.useHighPrecisionFloats !== void 0 && (this._highPrecisionShadersAllowed = o.useHighPrecisionFloats);
            var lt = IsWindowObjectExist() && window.devicePixelRatio || 1
              , ft = o.limitDeviceRatio || lt;
            this._hardwareScalingLevel = s ? 1 / Math.min(ft, lt) : 1,
            this.resize(),
            this._isStencilEnable = !!o.stencil,
            this._initGLContext(),
            this._initFeatures();
            for (var ht = 0; ht < this._caps.maxVertexAttribs; ht++)
                this._currentBufferPointers[ht] = 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 = o;
            var pt = "Babylon.js v" + a.Version;
            console.log(pt + (" - " + this.description)),
            this._renderingCanvas && this._renderingCanvas.setAttribute && this._renderingCanvas.setAttribute("data-engine", pt)
        }
    }
    return Object.defineProperty(a, "NpmPackage", {
        get: function() {
            return "babylonjs@5.0.0-alpha.63"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "Version", {
        get: function() {
            return "5.0.0-alpha.63"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "name", {
        get: function() {
            return "WebGL"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "version", {
        get: function() {
            return this._webGLVersion
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ShadersRepository", {
        get: function() {
            return Effect.ShadersRepository
        },
        set: function(e) {
            Effect.ShadersRepository = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._getShaderProcessor = function(e) {
        return this._shaderProcessor
    }
    ,
    Object.defineProperty(a.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(a.prototype, "frameId", {
        get: function() {
            return this._frameId
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "supportsUniformBuffers", {
        get: function() {
            return this.webGLVersion > 1 && !this.disableUniformBuffers
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "_shouldUseHighPrecisionShader", {
        get: function() {
            return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "needPOTTextures", {
        get: function() {
            return this._webGLVersion < 2 || this.forcePOTTextures
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "activeRenderLoops", {
        get: function() {
            return this._activeRenderLoops
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "doNotHandleContextLost", {
        get: function() {
            return this._doNotHandleContextLost
        },
        set: function(e) {
            this._doNotHandleContextLost = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "_supportsHardwareTextureRescaling", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "framebufferDimensionsObject", {
        set: function(e) {
            this._framebufferDimensionsObject = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "currentViewport", {
        get: function() {
            return this._cachedViewport
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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(a.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(a.prototype, "emptyCubeTexture", {
        get: function() {
            if (!this._emptyCubeTexture) {
                var e = new Uint8Array(4)
                  , i = [e, e, e, e, e, e];
                this._emptyCubeTexture = this.createRawCubeTexture(i, 1, 5, 0, !1, !1, 1)
            }
            return this._emptyCubeTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isWebGPU", {
        get: function() {
            return this._isWebGPU
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "shaderPlatformName", {
        get: function() {
            return this._shaderPlatformName
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "snapshotRendering", {
        get: function() {
            return !1
        },
        set: function(e) {},
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "snapshotRenderingMode", {
        get: function() {
            return this._snapshotRenderingMode
        },
        set: function(e) {
            this._snapshotRenderingMode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.snapshotRenderingReset = function() {
        this.snapshotRendering = !1
    }
    ,
    a._createCanvas = function(e, i) {
        if (typeof document == "undefined")
            return new OffscreenCanvas(e,i);
        var o = document.createElement("canvas");
        return o.width = e,
        o.height = i,
        o
    }
    ,
    a.prototype.createCanvas = function(e, i) {
        return a._createCanvas(e, i)
    }
    ,
    a.prototype.createCanvasImage = function() {
        return document.createElement("img")
    }
    ,
    a.prototype._restoreEngineAfterContextLost = function(e) {
        var i = this;
        setTimeout(function() {
            return __awaiter(i, void 0, void 0, function() {
                var o, s, c, d, _;
                return __generator(this, function(b) {
                    switch (b.label) {
                    case 0:
                        return this._dummyFramebuffer = null,
                        o = this._depthCullingState.depthTest,
                        s = this._depthCullingState.depthFunc,
                        c = this._depthCullingState.depthMask,
                        d = this._stencilState.stencilTest,
                        [4, e()];
                    case 1:
                        return b.sent(),
                        this._rebuildEffects(),
                        (_ = this._rebuildComputeEffects) === null || _ === void 0 || _.call(this),
                        this._rebuildInternalTextures(),
                        this._rebuildRenderTargetWrappers(),
                        this._rebuildBuffers(),
                        this.wipeCaches(!0),
                        this._depthCullingState.depthTest = o,
                        this._depthCullingState.depthFunc = s,
                        this._depthCullingState.depthMask = c,
                        this._stencilState.stencilTest = d,
                        Logger$2.Warn(this.name + " context successfully restored."),
                        this.onContextRestoredObservable.notifyObservers(this),
                        this._contextWasLost = !1,
                        [2]
                    }
                })
            })
        }, 0)
    }
    ,
    a.prototype._sharedInit = function(e, i, o) {
        this._renderingCanvas = e
    }
    ,
    a.prototype._getShaderProcessingContext = function(e) {
        return null
    }
    ,
    a.prototype._rebuildInternalTextures = function() {
        for (var e = this._internalTexturesCache.slice(), i = 0, o = e; i < o.length; i++) {
            var s = o[i];
            s._rebuild()
        }
    }
    ,
    a.prototype._rebuildRenderTargetWrappers = function() {
        for (var e = this._renderTargetWrapperCache.slice(), i = 0, o = e; i < o.length; i++) {
            var s = o[i];
            s._rebuild()
        }
    }
    ,
    a.prototype._rebuildEffects = function() {
        for (var e in this._compiledEffects) {
            var i = this._compiledEffects[e];
            i._pipelineContext = null,
            i._wasPreviouslyReady = !1,
            i._prepareEffect()
        }
        Effect.ResetCache()
    }
    ,
    a.prototype.areAllEffectsReady = function() {
        for (var e in this._compiledEffects) {
            var i = this._compiledEffects[e];
            if (!i.isReady())
                return !1
        }
        return !0
    }
    ,
    a.prototype._rebuildBuffers = function() {
        for (var e = 0, i = this._uniformBuffers; e < i.length; e++) {
            var o = i[e];
            o._rebuild()
        }
        for (var s = 0, c = this._storageBuffers; s < c.length; s++) {
            var d = c[s];
            d._rebuild()
        }
    }
    ,
    a.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 i = this._gl.getExtension("WEBGL_draw_buffers");
            if (i !== null) {
                this._caps.drawBuffersExtension = !0,
                this._gl.drawBuffers = i.drawBuffersWEBGL.bind(i),
                this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
                for (var o = 0; o < 16; o++)
                    this._gl["COLOR_ATTACHMENT" + o + "_WEBGL"] = i["COLOR_ATTACHMENT" + o + "_WEBGL"]
            }
        }
        if (this._webGLVersion > 1)
            this._caps.depthTextureExtension = !0;
        else {
            var s = this._gl.getExtension("WEBGL_depth_texture");
            s != null && (this._caps.depthTextureExtension = !0,
            this._gl.UNSIGNED_INT_24_8 = s.UNSIGNED_INT_24_8_WEBGL)
        }
        if (this.disableVertexArrayObjects)
            this._caps.vertexArrayObject = !1;
        else if (this._webGLVersion > 1)
            this._caps.vertexArrayObject = !0;
        else {
            var c = this._gl.getExtension("OES_vertex_array_object");
            c != null && (this._caps.vertexArrayObject = !0,
            this._gl.createVertexArray = c.createVertexArrayOES.bind(c),
            this._gl.bindVertexArray = c.bindVertexArrayOES.bind(c),
            this._gl.deleteVertexArray = c.deleteVertexArrayOES.bind(c))
        }
        if (this._webGLVersion > 1)
            this._caps.instancedArrays = !0;
        else {
            var d = this._gl.getExtension("ANGLE_instanced_arrays");
            d != null ? (this._caps.instancedArrays = !0,
            this._gl.drawArraysInstanced = d.drawArraysInstancedANGLE.bind(d),
            this._gl.drawElementsInstanced = d.drawElementsInstancedANGLE.bind(d),
            this._gl.vertexAttribDivisor = d.vertexAttribDivisorANGLE.bind(d)) : this._caps.instancedArrays = !1
        }
        if (this._gl.getShaderPrecisionFormat) {
            var _ = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT)
              , b = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
            _ && b && (this._caps.highPrecisionShaderSupported = _.precision !== 0 && b.precision !== 0)
        }
        if (this._webGLVersion > 1)
            this._caps.blendMinMax = !0;
        else {
            var k = this._gl.getExtension("EXT_blend_minmax");
            k != null && (this._caps.blendMinMax = !0,
            this._gl.MAX = k.MAX_EXT,
            this._gl.MIN = k.MIN_EXT)
        }
        if (this._webGLVersion > 1)
            this._caps.supportSRGBBuffers = !0;
        else {
            var j = this._gl.getExtension("EXT_sRGB");
            j != null && (this._caps.supportSRGBBuffers = !0,
            this._gl.SRGB = j.SRGB_EXT,
            this._gl.SRGB8 = j.SRGB_ALPHA_EXT,
            this._gl.SRGB8_ALPHA8 = j.SRGB_ALPHA_EXT)
        }
        this._depthCullingState.depthTest = !0,
        this._depthCullingState.depthFunc = this._gl.LEQUAL,
        this._depthCullingState.depthMask = !0,
        this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
        for (var $ = 0; $ < this._maxSimultaneousTextures; $++)
            this._nextFreeTextureSlots.push($)
    }
    ,
    a.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(a.prototype, "webGLVersion", {
        get: function() {
            return this._webGLVersion
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getClassName = function() {
        return "ThinEngine"
    }
    ,
    Object.defineProperty(a.prototype, "isStencilEnable", {
        get: function() {
            return this._isStencilEnable
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._prepareWorkingCanvas = function() {
        if (!this._workingCanvas) {
            this._workingCanvas = this.createCanvas(1, 1);
            var e = this._workingCanvas.getContext("2d");
            e && (this._workingContext = e)
        }
    }
    ,
    a.prototype.resetTextureCache = function() {
        for (var e in this._boundTexturesCache)
            !this._boundTexturesCache.hasOwnProperty(e) || (this._boundTexturesCache[e] = null);
        this._currentTextureChannel = -1
    }
    ,
    a.prototype.getInfo = function() {
        return this.getGlInfo()
    }
    ,
    a.prototype.getGlInfo = function() {
        return {
            vendor: this._glVendor,
            renderer: this._glRenderer,
            version: this._glVersion
        }
    }
    ,
    a.prototype.setHardwareScalingLevel = function(e) {
        this._hardwareScalingLevel = e,
        this.resize()
    }
    ,
    a.prototype.getHardwareScalingLevel = function() {
        return this._hardwareScalingLevel
    }
    ,
    a.prototype.getLoadedTexturesCache = function() {
        return this._internalTexturesCache
    }
    ,
    a.prototype.getCaps = function() {
        return this._caps
    }
    ,
    a.prototype.stopRenderLoop = function(e) {
        if (!e) {
            this._activeRenderLoops = [];
            return
        }
        var i = this._activeRenderLoops.indexOf(e);
        i >= 0 && this._activeRenderLoops.splice(i, 1)
    }
    ,
    a.prototype._renderLoop = function() {
        if (!this._contextWasLost) {
            var e = !0;
            if (!this.renderEvenInBackground && this._windowIsBackground && (e = !1),
            e) {
                this.beginFrame();
                for (var i = 0; i < this._activeRenderLoops.length; i++) {
                    var o = this._activeRenderLoops[i];
                    o()
                }
                this.endFrame()
            }
        }
        this._activeRenderLoops.length > 0 ? this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()) : this._renderingQueueLaunched = !1
    }
    ,
    a.prototype.getRenderingCanvas = function() {
        return this._renderingCanvas
    }
    ,
    a.prototype.getAudioContext = function() {
        return this._audioContext
    }
    ,
    a.prototype.getAudioDestination = function() {
        return this._audioDestination
    }
    ,
    a.prototype.getHostWindow = function() {
        return IsWindowObjectExist() ? this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView ? this._renderingCanvas.ownerDocument.defaultView : window : null
    }
    ,
    a.prototype.getRenderWidth = function(e) {
        return e === void 0 && (e = !1),
        !e && this._currentRenderTarget ? this._currentRenderTarget.width : this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth
    }
    ,
    a.prototype.getRenderHeight = function(e) {
        return e === void 0 && (e = !1),
        !e && this._currentRenderTarget ? this._currentRenderTarget.height : this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight
    }
    ,
    a.prototype._queueNewFrame = function(e, i) {
        return a.QueueNewFrame(e, i)
    }
    ,
    a.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())))
    }
    ,
    a.prototype.clear = function(e, i, o, s) {
        s === void 0 && (s = !1);
        var c = this.stencilStateComposer.useStencilGlobalOnly;
        this.stencilStateComposer.useStencilGlobalOnly = !0,
        this.applyStates(),
        this.stencilStateComposer.useStencilGlobalOnly = c;
        var d = 0;
        i && e && (this._gl.clearColor(e.r, e.g, e.b, e.a !== void 0 ? e.a : 1),
        d |= this._gl.COLOR_BUFFER_BIT),
        o && (this.useReverseDepthBuffer ? (this._depthCullingState.depthFunc = this._gl.GEQUAL,
        this._gl.clearDepth(0)) : this._gl.clearDepth(1),
        d |= this._gl.DEPTH_BUFFER_BIT),
        s && (this._gl.clearStencil(0),
        d |= this._gl.STENCIL_BUFFER_BIT),
        this._gl.clear(d)
    }
    ,
    a.prototype._viewport = function(e, i, o, s) {
        (e !== this._viewportCached.x || i !== this._viewportCached.y || o !== this._viewportCached.z || s !== this._viewportCached.w) && (this._viewportCached.x = e,
        this._viewportCached.y = i,
        this._viewportCached.z = o,
        this._viewportCached.w = s,
        this._gl.viewport(e, i, o, s))
    }
    ,
    a.prototype.setViewport = function(e, i, o) {
        var s = i || this.getRenderWidth()
          , c = o || this.getRenderHeight()
          , d = e.x || 0
          , _ = e.y || 0;
        this._cachedViewport = e,
        this._viewport(d * s, _ * c, s * e.width, c * e.height)
    }
    ,
    a.prototype.beginFrame = function() {}
    ,
    a.prototype.endFrame = function() {
        this._badOS && this.flushFramebuffer(),
        this._frameId++
    }
    ,
    a.prototype.resize = function(e) {
        e === void 0 && (e = !1);
        var i, o;
        IsWindowObjectExist() ? (i = this._renderingCanvas ? this._renderingCanvas.clientWidth || this._renderingCanvas.width : window.innerWidth,
        o = this._renderingCanvas ? this._renderingCanvas.clientHeight || this._renderingCanvas.height : window.innerHeight) : (i = this._renderingCanvas ? this._renderingCanvas.width : 100,
        o = this._renderingCanvas ? this._renderingCanvas.height : 100),
        this.setSize(i / this._hardwareScalingLevel, o / this._hardwareScalingLevel, e)
    }
    ,
    a.prototype.setSize = function(e, i, o) {
        return o === void 0 && (o = !1),
        !this._renderingCanvas || (e = e | 0,
        i = i | 0,
        !o && this._renderingCanvas.width === e && this._renderingCanvas.height === i) ? !1 : (this._renderingCanvas.width = e,
        this._renderingCanvas.height = i,
        !0)
    }
    ,
    a.prototype.bindFramebuffer = function(e, i, o, s, c, d, _) {
        var b, k, j, $, _e;
        i === void 0 && (i = 0),
        d === void 0 && (d = 0),
        _ === void 0 && (_ = 0);
        var et = e;
        this._currentRenderTarget && this.unBindFramebuffer(this._currentRenderTarget),
        this._currentRenderTarget = e,
        this._bindUnboundFramebuffer(et._MSAAFramebuffer ? et._MSAAFramebuffer : et._framebuffer);
        var tt = this._gl;
        e.is2DArray ? tt.framebufferTextureLayer(tt.FRAMEBUFFER, tt.COLOR_ATTACHMENT0, (b = e.texture._hardwareTexture) === null || b === void 0 ? void 0 : b.underlyingResource, d, _) : e.isCube && tt.framebufferTexture2D(tt.FRAMEBUFFER, tt.COLOR_ATTACHMENT0, tt.TEXTURE_CUBE_MAP_POSITIVE_X + i, (k = e.texture._hardwareTexture) === null || k === void 0 ? void 0 : k.underlyingResource, d);
        var rt = e._depthStencilTexture;
        if (rt) {
            var it = e._depthStencilTextureWithStencil ? tt.DEPTH_STENCIL_ATTACHMENT : tt.DEPTH_ATTACHMENT;
            e.is2DArray ? tt.framebufferTextureLayer(tt.FRAMEBUFFER, it, (j = rt._hardwareTexture) === null || j === void 0 ? void 0 : j.underlyingResource, d, _) : e.isCube ? tt.framebufferTexture2D(tt.FRAMEBUFFER, it, tt.TEXTURE_CUBE_MAP_POSITIVE_X + i, ($ = rt._hardwareTexture) === null || $ === void 0 ? void 0 : $.underlyingResource, d) : tt.framebufferTexture2D(tt.FRAMEBUFFER, it, tt.TEXTURE_2D, (_e = rt._hardwareTexture) === null || _e === void 0 ? void 0 : _e.underlyingResource, d)
        }
        this._cachedViewport && !c ? this.setViewport(this._cachedViewport, o, s) : (o || (o = e.width,
        d && (o = o / Math.pow(2, d))),
        s || (s = e.height,
        d && (s = s / Math.pow(2, d))),
        this._viewport(0, 0, o, s)),
        this.wipeCaches()
    }
    ,
    a.prototype.setState = function(e, i, o, s, c, d, _) {
        var b, k;
        i === void 0 && (i = 0),
        s === void 0 && (s = !1),
        _ === void 0 && (_ = 0),
        (this._depthCullingState.cull !== e || o) && (this._depthCullingState.cull = e);
        var j = !((k = (b = this.cullBackFaces) !== null && b !== void 0 ? b : c) !== null && k !== void 0) || k ? this._gl.BACK : this._gl.FRONT;
        (this._depthCullingState.cullFace !== j || o) && (this._depthCullingState.cullFace = j),
        this.setZOffset(i),
        this.setZOffsetUnits(_);
        var $ = s ? this._gl.CW : this._gl.CCW;
        (this._depthCullingState.frontFace !== $ || o) && (this._depthCullingState.frontFace = $),
        this._stencilStateComposer.stencilMaterial = d
    }
    ,
    a.prototype.setZOffset = function(e) {
        this._depthCullingState.zOffset = this.useReverseDepthBuffer ? -e : e
    }
    ,
    a.prototype.getZOffset = function() {
        var e = this._depthCullingState.zOffset;
        return this.useReverseDepthBuffer ? -e : e
    }
    ,
    a.prototype.setZOffsetUnits = function(e) {
        this._depthCullingState.zOffsetUnits = this.useReverseDepthBuffer ? -e : e
    }
    ,
    a.prototype.getZOffsetUnits = function() {
        var e = this._depthCullingState.zOffsetUnits;
        return this.useReverseDepthBuffer ? -e : e
    }
    ,
    a.prototype._bindUnboundFramebuffer = function(e) {
        this._currentFramebuffer !== e && (this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, e),
        this._currentFramebuffer = e)
    }
    ,
    a.prototype._currentFrameBufferIsDefaultFrameBuffer = function() {
        return this._currentFramebuffer === null
    }
    ,
    a.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)
    }
    ,
    a.prototype.unBindFramebuffer = function(e, i, o) {
        var s;
        i === void 0 && (i = !1);
        var c = e;
        this._currentRenderTarget = null;
        var d = this._gl;
        if (c._MSAAFramebuffer) {
            if (e.isMulti) {
                this.unBindMultiColorAttachmentFramebuffer(e, i, o);
                return
            }
            d.bindFramebuffer(d.READ_FRAMEBUFFER, c._MSAAFramebuffer),
            d.bindFramebuffer(d.DRAW_FRAMEBUFFER, c._framebuffer),
            d.blitFramebuffer(0, 0, e.width, e.height, 0, 0, e.width, e.height, d.COLOR_BUFFER_BIT, d.NEAREST)
        }
        ((s = e.texture) === null || s === void 0 ? void 0 : s.generateMipMaps) && !i && !e.isCube && this.generateMipmaps(e.texture),
        o && (c._MSAAFramebuffer && this._bindUnboundFramebuffer(c._framebuffer),
        o()),
        this._bindUnboundFramebuffer(null)
    }
    ,
    a.prototype.flushFramebuffer = function() {
        this._gl.flush()
    }
    ,
    a.prototype.restoreDefaultFramebuffer = function() {
        this._currentRenderTarget ? this.unBindFramebuffer(this._currentRenderTarget) : this._bindUnboundFramebuffer(null),
        this._cachedViewport && this.setViewport(this._cachedViewport),
        this.wipeCaches()
    }
    ,
    a.prototype._resetVertexBufferBinding = function() {
        this.bindArrayBuffer(null),
        this._cachedVertexBuffers = null
    }
    ,
    a.prototype.createVertexBuffer = function(e) {
        return this._createVertexBuffer(e, this._gl.STATIC_DRAW)
    }
    ,
    a.prototype._createVertexBuffer = function(e, i) {
        var o = this._gl.createBuffer();
        if (!o)
            throw new Error("Unable to create vertex buffer");
        var s = new WebGLDataBuffer(o);
        return this.bindArrayBuffer(s),
        e instanceof Array ? this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(e), i) : this._gl.bufferData(this._gl.ARRAY_BUFFER, e, i),
        this._resetVertexBufferBinding(),
        s.references = 1,
        s
    }
    ,
    a.prototype.createDynamicVertexBuffer = function(e) {
        return this._createVertexBuffer(e, this._gl.DYNAMIC_DRAW)
    }
    ,
    a.prototype._resetIndexBufferBinding = function() {
        this.bindIndexBuffer(null),
        this._cachedIndexBuffer = null
    }
    ,
    a.prototype.createIndexBuffer = function(e, i) {
        var o = this._gl.createBuffer()
          , s = new WebGLDataBuffer(o);
        if (!o)
            throw new Error("Unable to create index buffer");
        this.bindIndexBuffer(s);
        var c = this._normalizeIndexData(e);
        return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, c, i ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW),
        this._resetIndexBufferBinding(),
        s.references = 1,
        s.is32Bits = c.BYTES_PER_ELEMENT === 4,
        s
    }
    ,
    a.prototype._normalizeIndexData = function(e) {
        var i = e.BYTES_PER_ELEMENT;
        if (i === 2)
            return e;
        if (this._caps.uintIndices) {
            if (e instanceof Uint32Array)
                return e;
            for (var o = 0; o < e.length; o++)
                if (e[o] >= 65535)
                    return new Uint32Array(e);
            return new Uint16Array(e)
        }
        return new Uint16Array(e)
    }
    ,
    a.prototype.bindArrayBuffer = function(e) {
        this._vaoRecordInProgress || this._unbindVertexArrayObject(),
        this.bindBuffer(e, this._gl.ARRAY_BUFFER)
    }
    ,
    a.prototype.bindUniformBlock = function(e, i, o) {
        var s = e.program
          , c = this._gl.getUniformBlockIndex(s, i);
        this._gl.uniformBlockBinding(s, c, o)
    }
    ,
    a.prototype.bindIndexBuffer = function(e) {
        this._vaoRecordInProgress || this._unbindVertexArrayObject(),
        this.bindBuffer(e, this._gl.ELEMENT_ARRAY_BUFFER)
    }
    ,
    a.prototype.bindBuffer = function(e, i) {
        (this._vaoRecordInProgress || this._currentBoundBuffer[i] !== e) && (this._gl.bindBuffer(i, e ? e.underlyingResource : null),
        this._currentBoundBuffer[i] = e)
    }
    ,
    a.prototype.updateArrayBuffer = function(e) {
        this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, e)
    }
    ,
    a.prototype._vertexAttribPointer = function(e, i, o, s, c, d, _) {
        var b = this._currentBufferPointers[i];
        if (!!b) {
            var k = !1;
            b.active ? (b.buffer !== e && (b.buffer = e,
            k = !0),
            b.size !== o && (b.size = o,
            k = !0),
            b.type !== s && (b.type = s,
            k = !0),
            b.normalized !== c && (b.normalized = c,
            k = !0),
            b.stride !== d && (b.stride = d,
            k = !0),
            b.offset !== _ && (b.offset = _,
            k = !0)) : (k = !0,
            b.active = !0,
            b.index = i,
            b.size = o,
            b.type = s,
            b.normalized = c,
            b.stride = d,
            b.offset = _,
            b.buffer = e),
            (k || this._vaoRecordInProgress) && (this.bindArrayBuffer(e),
            this._gl.vertexAttribPointer(i, o, s, c, d, _))
        }
    }
    ,
    a.prototype._bindIndexBufferWithCache = function(e) {
        e != null && this._cachedIndexBuffer !== e && (this._cachedIndexBuffer = e,
        this.bindIndexBuffer(e),
        this._uintIndicesCurrentlySet = e.is32Bits)
    }
    ,
    a.prototype._bindVertexBuffersAttributes = function(e, i, o) {
        var s = i.getAttributesNames();
        this._vaoRecordInProgress || this._unbindVertexArrayObject(),
        this.unbindAllAttributes();
        for (var c = 0; c < s.length; c++) {
            var d = i.getAttributeLocation(c);
            if (d >= 0) {
                var _ = s[c]
                  , b = null;
                if (o && (b = o[_]),
                b || (b = e[_]),
                !b)
                    continue;
                this._gl.enableVertexAttribArray(d),
                this._vaoRecordInProgress || (this._vertexAttribArraysEnabled[d] = !0);
                var k = b.getBuffer();
                k && (this._vertexAttribPointer(k, d, b.getSize(), b.type, b.normalized, b.byteStride, b.byteOffset),
                b.getIsInstanced() && (this._gl.vertexAttribDivisor(d, b.getInstanceDivisor()),
                this._vaoRecordInProgress || (this._currentInstanceLocations.push(d),
                this._currentInstanceBuffers.push(k))))
            }
        }
    }
    ,
    a.prototype.recordVertexArrayObject = function(e, i, o, s) {
        var c = this._gl.createVertexArray();
        return this._vaoRecordInProgress = !0,
        this._gl.bindVertexArray(c),
        this._mustWipeVertexAttributes = !0,
        this._bindVertexBuffersAttributes(e, o, s),
        this.bindIndexBuffer(i),
        this._vaoRecordInProgress = !1,
        this._gl.bindVertexArray(null),
        c
    }
    ,
    a.prototype.bindVertexArrayObject = function(e, i) {
        this._cachedVertexArrayObject !== e && (this._cachedVertexArrayObject = e,
        this._gl.bindVertexArray(e),
        this._cachedVertexBuffers = null,
        this._cachedIndexBuffer = null,
        this._uintIndicesCurrentlySet = i != null && i.is32Bits,
        this._mustWipeVertexAttributes = !0)
    }
    ,
    a.prototype.bindBuffersDirectly = function(e, i, o, s, c) {
        if (this._cachedVertexBuffers !== e || this._cachedEffectForVertexBuffers !== c) {
            this._cachedVertexBuffers = e,
            this._cachedEffectForVertexBuffers = c;
            var d = c.getAttributesCount();
            this._unbindVertexArrayObject(),
            this.unbindAllAttributes();
            for (var _ = 0, b = 0; b < d; b++)
                if (b < o.length) {
                    var k = c.getAttributeLocation(b);
                    k >= 0 && (this._gl.enableVertexAttribArray(k),
                    this._vertexAttribArraysEnabled[k] = !0,
                    this._vertexAttribPointer(e, k, o[b], this._gl.FLOAT, !1, s, _)),
                    _ += o[b] * 4
                }
        }
        this._bindIndexBufferWithCache(i)
    }
    ,
    a.prototype._unbindVertexArrayObject = function() {
        !this._cachedVertexArrayObject || (this._cachedVertexArrayObject = null,
        this._gl.bindVertexArray(null))
    }
    ,
    a.prototype.bindBuffers = function(e, i, o, s) {
        (this._cachedVertexBuffers !== e || this._cachedEffectForVertexBuffers !== o) && (this._cachedVertexBuffers = e,
        this._cachedEffectForVertexBuffers = o,
        this._bindVertexBuffersAttributes(e, o, s)),
        this._bindIndexBufferWithCache(i)
    }
    ,
    a.prototype.unbindInstanceAttributes = function() {
        for (var e, i = 0, o = this._currentInstanceLocations.length; i < o; i++) {
            var s = this._currentInstanceBuffers[i];
            e != s && s.references && (e = s,
            this.bindArrayBuffer(s));
            var c = this._currentInstanceLocations[i];
            this._gl.vertexAttribDivisor(c, 0)
        }
        this._currentInstanceBuffers.length = 0,
        this._currentInstanceLocations.length = 0
    }
    ,
    a.prototype.releaseVertexArrayObject = function(e) {
        this._gl.deleteVertexArray(e)
    }
    ,
    a.prototype._releaseBuffer = function(e) {
        return e.references--,
        e.references === 0 ? (this._deleteBuffer(e),
        !0) : !1
    }
    ,
    a.prototype._deleteBuffer = function(e) {
        this._gl.deleteBuffer(e.underlyingResource)
    }
    ,
    a.prototype.updateAndBindInstancesBuffer = function(e, i, o) {
        if (this.bindArrayBuffer(e),
        i && this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, i),
        o[0].index !== void 0)
            this.bindInstancesBuffer(e, o, !0);
        else
            for (var s = 0; s < 4; s++) {
                var c = o[s];
                this._vertexAttribArraysEnabled[c] || (this._gl.enableVertexAttribArray(c),
                this._vertexAttribArraysEnabled[c] = !0),
                this._vertexAttribPointer(e, c, 4, this._gl.FLOAT, !1, 64, s * 16),
                this._gl.vertexAttribDivisor(c, 1),
                this._currentInstanceLocations.push(c),
                this._currentInstanceBuffers.push(e)
            }
    }
    ,
    a.prototype.bindInstancesBuffer = function(e, i, o) {
        o === void 0 && (o = !0),
        this.bindArrayBuffer(e);
        var s = 0;
        if (o)
            for (var c = 0; c < i.length; c++) {
                var d = i[c];
                s += d.attributeSize * 4
            }
        for (var c = 0; c < i.length; c++) {
            var d = i[c];
            d.index === void 0 && (d.index = this._currentEffect.getAttributeLocationByName(d.attributeName)),
            !(d.index < 0) && (this._vertexAttribArraysEnabled[d.index] || (this._gl.enableVertexAttribArray(d.index),
            this._vertexAttribArraysEnabled[d.index] = !0),
            this._vertexAttribPointer(e, d.index, d.attributeSize, d.attributeType || this._gl.FLOAT, d.normalized || !1, s, d.offset),
            this._gl.vertexAttribDivisor(d.index, d.divisor === void 0 ? 1 : d.divisor),
            this._currentInstanceLocations.push(d.index),
            this._currentInstanceBuffers.push(e))
        }
    }
    ,
    a.prototype.disableInstanceAttributeByName = function(e) {
        if (!!this._currentEffect) {
            var i = this._currentEffect.getAttributeLocationByName(e);
            this.disableInstanceAttribute(i)
        }
    }
    ,
    a.prototype.disableInstanceAttribute = function(e) {
        for (var i = !1, o; (o = this._currentInstanceLocations.indexOf(e)) !== -1; )
            this._currentInstanceLocations.splice(o, 1),
            this._currentInstanceBuffers.splice(o, 1),
            i = !0,
            o = this._currentInstanceLocations.indexOf(e);
        i && (this._gl.vertexAttribDivisor(e, 0),
        this.disableAttributeByIndex(e))
    }
    ,
    a.prototype.disableAttributeByIndex = function(e) {
        this._gl.disableVertexAttribArray(e),
        this._vertexAttribArraysEnabled[e] = !1,
        this._currentBufferPointers[e].active = !1
    }
    ,
    a.prototype.draw = function(e, i, o, s) {
        this.drawElementsType(e ? 0 : 1, i, o, s)
    }
    ,
    a.prototype.drawPointClouds = function(e, i, o) {
        this.drawArraysType(2, e, i, o)
    }
    ,
    a.prototype.drawUnIndexed = function(e, i, o, s) {
        this.drawArraysType(e ? 0 : 1, i, o, s)
    }
    ,
    a.prototype.drawElementsType = function(e, i, o, s) {
        this.applyStates(),
        this._reportDrawCall();
        var c = this._drawMode(e)
          , d = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT
          , _ = this._uintIndicesCurrentlySet ? 4 : 2;
        s ? this._gl.drawElementsInstanced(c, o, d, i * _, s) : this._gl.drawElements(c, o, d, i * _)
    }
    ,
    a.prototype.drawArraysType = function(e, i, o, s) {
        this.applyStates(),
        this._reportDrawCall();
        var c = this._drawMode(e);
        s ? this._gl.drawArraysInstanced(c, i, o, s) : this._gl.drawArrays(c, i, o)
    }
    ,
    a.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
        }
    }
    ,
    a.prototype._reportDrawCall = function() {}
    ,
    a.prototype._releaseEffect = function(e) {
        if (this._compiledEffects[e._key]) {
            delete this._compiledEffects[e._key];
            var i = e.getPipelineContext();
            i && this._deletePipelineContext(i)
        }
    }
    ,
    a.prototype._deletePipelineContext = function(e) {
        var i = e;
        i && i.program && (i.program.__SPECTOR_rebuildProgram = null,
        this._gl.deleteProgram(i.program))
    }
    ,
    a.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 i = "";
            return this.isNDCHalfZRange && (i += "#define IS_NDC_HALF_ZRANGE"),
            this.useReverseDepthBuffer && (i && (i += `
`),
            i += "#define USE_REVERSE_DEPTHBUFFER"),
            i
        }
    }
    ,
    a.prototype.createEffect = function(e, i, o, s, c, d, _, b, k, j) {
        var $;
        j === void 0 && (j = ShaderLanguage.GLSL);
        var _e = e.vertexElement || e.vertex || e.vertexToken || e.vertexSource || e
          , et = e.fragmentElement || e.fragment || e.fragmentToken || e.fragmentSource || e
          , tt = this._getGlobalDefines()
          , rt = ($ = c != null ? c : i.defines) !== null && $ !== void 0 ? $ : "";
        tt && (rt += tt);
        var it = _e + "+" + et + "@" + rt;
        if (this._compiledEffects[it]) {
            var nt = this._compiledEffects[it];
            return _ && nt.isReady() && _(nt),
            nt
        }
        var ot = new Effect(e,i,o,s,this,c,d,_,b,k,it,j);
        return this._compiledEffects[it] = ot,
        ot
    }
    ,
    a._ConcatenateShader = function(e, i, o) {
        return o === void 0 && (o = ""),
        o + (i ? i + `
` : "") + e
    }
    ,
    a.prototype._compileShader = function(e, i, o, s) {
        return this._compileRawShader(a._ConcatenateShader(e, o, s), i)
    }
    ,
    a.prototype._compileRawShader = function(e, i) {
        for (var o = this._gl; o.getError() != o.NO_ERROR; )
            ;
        var s = o.createShader(i === "vertex" ? o.VERTEX_SHADER : o.FRAGMENT_SHADER);
        if (!s)
            throw new Error("Something went wrong while creating a gl " + i + " shader object. gl error=" + o.getError() + ", gl isContextLost=" + o.isContextLost() + ", _contextWasLost=" + this._contextWasLost);
        return o.shaderSource(s, e),
        o.compileShader(s),
        s
    }
    ,
    a.prototype._getShaderSource = function(e) {
        return this._gl.getShaderSource(e)
    }
    ,
    a.prototype.createRawShaderProgram = function(e, i, o, s, c) {
        c === void 0 && (c = null),
        s = s || this._gl;
        var d = this._compileRawShader(i, "vertex")
          , _ = this._compileRawShader(o, "fragment");
        return this._createShaderProgram(e, d, _, s, c)
    }
    ,
    a.prototype.createShaderProgram = function(e, i, o, s, c, d) {
        d === void 0 && (d = null),
        c = c || this._gl;
        var _ = this._webGLVersion > 1 ? `#version 300 es
#define WEBGL2 
` : ""
          , b = this._compileShader(i, "vertex", s, _)
          , k = this._compileShader(o, "fragment", s, _);
        return this._createShaderProgram(e, b, k, c, d)
    }
    ,
    a.prototype.inlineShaderCode = function(e) {
        return e
    }
    ,
    a.prototype.createPipelineContext = function(e) {
        var i = new WebGLPipelineContext;
        return i.engine = this,
        this._caps.parallelShaderCompile && (i.isParallelCompiled = !0),
        i
    }
    ,
    a.prototype.createMaterialContext = function() {}
    ,
    a.prototype.createDrawContext = function() {}
    ,
    a.prototype._createShaderProgram = function(e, i, o, s, c) {
        var d = s.createProgram();
        if (e.program = d,
        !d)
            throw new Error("Unable to create program");
        return s.attachShader(d, i),
        s.attachShader(d, o),
        s.linkProgram(d),
        e.context = s,
        e.vertexShader = i,
        e.fragmentShader = o,
        e.isParallelCompiled || this._finalizePipelineContext(e),
        d
    }
    ,
    a.prototype._finalizePipelineContext = function(e) {
        var i = e.context
          , o = e.vertexShader
          , s = e.fragmentShader
          , c = e.program
          , d = i.getProgramParameter(c, i.LINK_STATUS);
        if (!d) {
            if (!this._gl.getShaderParameter(o, this._gl.COMPILE_STATUS)) {
                var _ = this._gl.getShaderInfoLog(o);
                if (_)
                    throw e.vertexCompilationError = _,
                    new Error("VERTEX SHADER " + _)
            }
            if (!this._gl.getShaderParameter(s, this._gl.COMPILE_STATUS)) {
                var _ = this._gl.getShaderInfoLog(s);
                if (_)
                    throw e.fragmentCompilationError = _,
                    new Error("FRAGMENT SHADER " + _)
            }
            var b = i.getProgramInfoLog(c);
            if (b)
                throw e.programLinkError = b,
                new Error(b)
        }
        if (this.validateShaderPrograms) {
            i.validateProgram(c);
            var k = i.getProgramParameter(c, i.VALIDATE_STATUS);
            if (!k) {
                var b = i.getProgramInfoLog(c);
                if (b)
                    throw e.programValidationError = b,
                    new Error(b)
            }
        }
        i.deleteShader(o),
        i.deleteShader(s),
        e.vertexShader = void 0,
        e.fragmentShader = void 0,
        e.onCompiled && (e.onCompiled(),
        e.onCompiled = void 0)
    }
    ,
    a.prototype._preparePipelineContext = function(e, i, o, s, c, d, _, b, k, j) {
        var $ = e;
        s ? $.program = this.createRawShaderProgram($, i, o, void 0, k) : $.program = this.createShaderProgram($, i, o, b, void 0, k),
        $.program.__SPECTOR_rebuildProgram = _
    }
    ,
    a.prototype._isRenderingStateCompiled = function(e) {
        var i = e;
        return this._gl.getProgramParameter(i.program, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR) ? (this._finalizePipelineContext(i),
        !0) : !1
    }
    ,
    a.prototype._executeWhenRenderingStateIsCompiled = function(e, i) {
        var o = e;
        if (!o.isParallelCompiled) {
            i();
            return
        }
        var s = o.onCompiled;
        s ? o.onCompiled = function() {
            s(),
            i()
        }
        : o.onCompiled = i
    }
    ,
    a.prototype.getUniforms = function(e, i) {
        for (var o = new Array, s = e, c = 0; c < i.length; c++)
            o.push(this._gl.getUniformLocation(s.program, i[c]));
        return o
    }
    ,
    a.prototype.getAttributes = function(e, i) {
        for (var o = [], s = e, c = 0; c < i.length; c++)
            try {
                o.push(this._gl.getAttribLocation(s.program, i[c]))
            } catch {
                o.push(-1)
            }
        return o
    }
    ,
    a.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))
    }
    ,
    a.prototype.setInt = function(e, i) {
        return e ? (this._gl.uniform1i(e, i),
        !0) : !1
    }
    ,
    a.prototype.setInt2 = function(e, i, o) {
        return e ? (this._gl.uniform2i(e, i, o),
        !0) : !1
    }
    ,
    a.prototype.setInt3 = function(e, i, o, s) {
        return e ? (this._gl.uniform3i(e, i, o, s),
        !0) : !1
    }
    ,
    a.prototype.setInt4 = function(e, i, o, s, c) {
        return e ? (this._gl.uniform4i(e, i, o, s, c),
        !0) : !1
    }
    ,
    a.prototype.setIntArray = function(e, i) {
        return e ? (this._gl.uniform1iv(e, i),
        !0) : !1
    }
    ,
    a.prototype.setIntArray2 = function(e, i) {
        return !e || i.length % 2 !== 0 ? !1 : (this._gl.uniform2iv(e, i),
        !0)
    }
    ,
    a.prototype.setIntArray3 = function(e, i) {
        return !e || i.length % 3 !== 0 ? !1 : (this._gl.uniform3iv(e, i),
        !0)
    }
    ,
    a.prototype.setIntArray4 = function(e, i) {
        return !e || i.length % 4 !== 0 ? !1 : (this._gl.uniform4iv(e, i),
        !0)
    }
    ,
    a.prototype.setArray = function(e, i) {
        return !e || i.length < 1 ? !1 : (this._gl.uniform1fv(e, i),
        !0)
    }
    ,
    a.prototype.setArray2 = function(e, i) {
        return !e || i.length % 2 !== 0 ? !1 : (this._gl.uniform2fv(e, i),
        !0)
    }
    ,
    a.prototype.setArray3 = function(e, i) {
        return !e || i.length % 3 !== 0 ? !1 : (this._gl.uniform3fv(e, i),
        !0)
    }
    ,
    a.prototype.setArray4 = function(e, i) {
        return !e || i.length % 4 !== 0 ? !1 : (this._gl.uniform4fv(e, i),
        !0)
    }
    ,
    a.prototype.setMatrices = function(e, i) {
        return e ? (this._gl.uniformMatrix4fv(e, !1, i),
        !0) : !1
    }
    ,
    a.prototype.setMatrix3x3 = function(e, i) {
        return e ? (this._gl.uniformMatrix3fv(e, !1, i),
        !0) : !1
    }
    ,
    a.prototype.setMatrix2x2 = function(e, i) {
        return e ? (this._gl.uniformMatrix2fv(e, !1, i),
        !0) : !1
    }
    ,
    a.prototype.setFloat = function(e, i) {
        return e ? (this._gl.uniform1f(e, i),
        !0) : !1
    }
    ,
    a.prototype.setFloat2 = function(e, i, o) {
        return e ? (this._gl.uniform2f(e, i, o),
        !0) : !1
    }
    ,
    a.prototype.setFloat3 = function(e, i, o, s) {
        return e ? (this._gl.uniform3f(e, i, o, s),
        !0) : !1
    }
    ,
    a.prototype.setFloat4 = function(e, i, o, s, c) {
        return e ? (this._gl.uniform4f(e, i, o, s, c),
        !0) : !1
    }
    ,
    a.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)
        }
    }
    ,
    a.prototype.setColorWrite = function(e) {
        e !== this._colorWrite && (this._colorWriteChanged = !0,
        this._colorWrite = e)
    }
    ,
    a.prototype.getColorWrite = function() {
        return this._colorWrite
    }
    ,
    Object.defineProperty(a.prototype, "depthCullingState", {
        get: function() {
            return this._depthCullingState
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "alphaState", {
        get: function() {
            return this._alphaState
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilState", {
        get: function() {
            return this._stencilState
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "stencilStateComposer", {
        get: function() {
            return this._stencilStateComposer
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.clearInternalTexturesCache = function() {
        this._internalTexturesCache = []
    }
    ,
    a.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))
    }
    ,
    a.prototype._getSamplingParameters = function(e, i) {
        var o = this._gl
          , s = o.NEAREST
          , c = o.NEAREST;
        switch (e) {
        case 11:
            s = o.LINEAR,
            i ? c = o.LINEAR_MIPMAP_NEAREST : c = o.LINEAR;
            break;
        case 3:
            s = o.LINEAR,
            i ? c = o.LINEAR_MIPMAP_LINEAR : c = o.LINEAR;
            break;
        case 8:
            s = o.NEAREST,
            i ? c = o.NEAREST_MIPMAP_LINEAR : c = o.NEAREST;
            break;
        case 4:
            s = o.NEAREST,
            i ? c = o.NEAREST_MIPMAP_NEAREST : c = o.NEAREST;
            break;
        case 5:
            s = o.NEAREST,
            i ? c = o.LINEAR_MIPMAP_NEAREST : c = o.LINEAR;
            break;
        case 6:
            s = o.NEAREST,
            i ? c = o.LINEAR_MIPMAP_LINEAR : c = o.LINEAR;
            break;
        case 7:
            s = o.NEAREST,
            c = o.LINEAR;
            break;
        case 1:
            s = o.NEAREST,
            c = o.NEAREST;
            break;
        case 9:
            s = o.LINEAR,
            i ? c = o.NEAREST_MIPMAP_NEAREST : c = o.NEAREST;
            break;
        case 10:
            s = o.LINEAR,
            i ? c = o.NEAREST_MIPMAP_LINEAR : c = o.NEAREST;
            break;
        case 2:
            s = o.LINEAR,
            c = o.LINEAR;
            break;
        case 12:
            s = o.LINEAR,
            c = o.NEAREST;
            break
        }
        return {
            min: c,
            mag: s
        }
    }
    ,
    a.prototype._createTexture = function() {
        var e = this._gl.createTexture();
        if (!e)
            throw new Error("Unable to create texture");
        return e
    }
    ,
    a.prototype._createHardwareTexture = function() {
        return new WebGLHardwareTexture(this._createTexture(),this._gl)
    }
    ,
    a.prototype._createInternalTexture = function(e, i, o, s) {
        s === void 0 && (s = InternalTextureSource.Unknown);
        var c = {};
        i !== void 0 && typeof i == "object" ? (c.generateMipMaps = i.generateMipMaps,
        c.type = i.type === void 0 ? 0 : i.type,
        c.samplingMode = i.samplingMode === void 0 ? 3 : i.samplingMode,
        c.format = i.format === void 0 ? 5 : i.format) : (c.generateMipMaps = i,
        c.type = 0,
        c.samplingMode = 3,
        c.format = 5),
        (c.type === 1 && !this._caps.textureFloatLinearFiltering || c.type === 2 && !this._caps.textureHalfFloatLinearFiltering) && (c.samplingMode = 1),
        c.type === 1 && !this._caps.textureFloat && (c.type = 0,
        Logger$2.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));
        var d = this._gl
          , _ = new InternalTexture(this,s)
          , b = e.width || e
          , k = e.height || e
          , j = e.layers || 0
          , $ = this._getSamplingParameters(c.samplingMode, !!c.generateMipMaps)
          , _e = j !== 0 ? d.TEXTURE_2D_ARRAY : d.TEXTURE_2D
          , et = this._getRGBABufferInternalSizedFormat(c.type, c.format)
          , tt = this._getInternalFormat(c.format)
          , rt = this._getWebGLTextureType(c.type);
        return this._bindTextureDirectly(_e, _),
        j !== 0 ? (_.is2DArray = !0,
        d.texImage3D(_e, 0, et, b, k, j, 0, tt, rt, null)) : d.texImage2D(_e, 0, et, b, k, 0, tt, rt, null),
        d.texParameteri(_e, d.TEXTURE_MAG_FILTER, $.mag),
        d.texParameteri(_e, d.TEXTURE_MIN_FILTER, $.min),
        d.texParameteri(_e, d.TEXTURE_WRAP_S, d.CLAMP_TO_EDGE),
        d.texParameteri(_e, d.TEXTURE_WRAP_T, d.CLAMP_TO_EDGE),
        c.generateMipMaps && this._gl.generateMipmap(_e),
        this._bindTextureDirectly(_e, null),
        _.baseWidth = b,
        _.baseHeight = k,
        _.width = b,
        _.height = k,
        _.depth = j,
        _.isReady = !0,
        _.samples = 1,
        _.generateMipMaps = !!c.generateMipMaps,
        _.samplingMode = c.samplingMode,
        _.type = c.type,
        _.format = c.format,
        this._internalTexturesCache.push(_),
        _
    }
    ,
    a.prototype._getUseSRGBBuffer = function(e, i) {
        return e && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || i)
    }
    ,
    a.prototype._createTextureBase = function(e, i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it) {
        var nt = this;
        c === void 0 && (c = 3),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        j === void 0 && (j = null),
        $ === void 0 && ($ = null),
        _e === void 0 && (_e = null),
        et === void 0 && (et = null),
        e = e || "";
        var ot = e.substr(0, 5) === "data:"
          , at = e.substr(0, 5) === "blob:"
          , st = ot && e.indexOf(";base64,") !== -1
          , ut = $ || new InternalTexture(this,InternalTextureSource.Url)
          , ct = e;
        this._transformTextureUrl && !st && !$ && !j && (e = this._transformTextureUrl(e)),
        ct !== e && (ut._originalUrl = ct);
        var lt = e.lastIndexOf(".")
          , ft = et || (lt > -1 ? e.substring(lt).toLowerCase() : "")
          , ht = null
          , pt = ft.indexOf("?");
        pt > -1 && (ft = ft.split("?")[0]);
        for (var dt = 0, _t = a._TextureLoaders; dt < _t.length; dt++) {
            var mt = _t[dt];
            if (mt.canLoad(ft, tt)) {
                ht = mt;
                break
            }
        }
        s && s._addPendingData(ut),
        ut.url = e,
        ut.generateMipMaps = !i,
        ut.samplingMode = c,
        ut.invertY = o,
        ut._useSRGBBuffer = this._getUseSRGBBuffer(!!it, i),
        this._doNotHandleContextLost || (ut._buffer = j);
        var vt = null;
        d && !$ && (vt = ut.onLoadedObservable.add(d)),
        $ || this._internalTexturesCache.push(ut);
        var yt = function(gt, St) {
            s && s._removePendingData(ut),
            e === ct ? (vt && ut.onLoadedObservable.remove(vt),
            EngineStore.UseFallbackTexture && nt._createTextureBase(EngineStore.FallbackTexture, i, ut.invertY, s, c, null, _, b, k, j, ut),
            gt = (gt || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""),
            ut.onErrorObservable.notifyObservers({
                message: gt,
                exception: St
            }),
            _ && _(gt, St)) : (Logger$2.Warn("Failed to load " + e + ", falling back to " + ct),
            nt._createTextureBase(ct, i, ut.invertY, s, c, d, _, b, k, j, ut, _e, et, tt, rt, it))
        };
        if (ht) {
            var Et = function(gt) {
                ht.loadData(gt, ut, function(St, xt, bt, Rt, Mt, Pt) {
                    Pt ? yt("TextureLoader failed to load data") : b(ut, ft, s, {
                        width: St,
                        height: xt
                    }, ut.invertY, !bt, Rt, function() {
                        return Mt(),
                        !1
                    }, c)
                }, rt)
            };
            j ? j instanceof ArrayBuffer ? Et(new Uint8Array(j)) : ArrayBuffer.isView(j) ? Et(j) : _ && _("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null) : this._loadFile(e, function(gt) {
                return Et(new Uint8Array(gt))
            }, void 0, s ? s.offlineProvider : void 0, !0, function(gt, St) {
                yt("Unable to load " + (gt && gt.responseURL,
                St))
            })
        } else {
            var At = function(gt) {
                at && !nt._doNotHandleContextLost && (ut._buffer = gt),
                b(ut, ft, s, gt, ut.invertY, i, !1, k, c)
            };
            !ot || st ? j && (typeof j.decoding == "string" || j.close) ? At(j) : a._FileToolsLoadImage(e, At, yt, s ? s.offlineProvider : null, tt, ut.invertY && this._features.needsInvertingBitmap ? {
                imageOrientation: "flipY"
            } : void 0) : typeof j == "string" || j instanceof ArrayBuffer || ArrayBuffer.isView(j) || j instanceof Blob ? a._FileToolsLoadImage(j, At, yt, s ? s.offlineProvider : null, tt, ut.invertY && this._features.needsInvertingBitmap ? {
                imageOrientation: "flipY"
            } : void 0) : j && At(j)
        }
        return ut
    }
    ,
    a.prototype.createTexture = function(e, i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt) {
        var it = this;
        return c === void 0 && (c = 3),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null),
        k === void 0 && (k = null),
        j === void 0 && (j = null),
        $ === void 0 && ($ = null),
        this._createTextureBase(e, i, o, s, c, d, _, this._prepareWebGLTexture.bind(this), function(nt, ot, at, st, ut, ct) {
            var lt = it._gl
              , ft = at.width === nt && at.height === ot
              , ht = j ? it._getInternalFormat(j, ut._useSRGBBuffer) : st === ".jpg" && !ut._useSRGBBuffer ? lt.RGB : ut._useSRGBBuffer ? lt.SRGB8_ALPHA8 : lt.RGBA
              , pt = j ? it._getInternalFormat(j) : st === ".jpg" && !ut._useSRGBBuffer ? lt.RGB : lt.RGBA;
            if (ut._useSRGBBuffer && it.webGLVersion === 1 && (pt = ht),
            ft)
                return lt.texImage2D(lt.TEXTURE_2D, 0, ht, pt, lt.UNSIGNED_BYTE, at),
                !1;
            var dt = it._caps.maxTextureSize;
            if (at.width > dt || at.height > dt || !it._supportsHardwareTextureRescaling)
                return it._prepareWorkingCanvas(),
                !it._workingCanvas || !it._workingContext || (it._workingCanvas.width = nt,
                it._workingCanvas.height = ot,
                it._workingContext.drawImage(at, 0, 0, at.width, at.height, 0, 0, nt, ot),
                lt.texImage2D(lt.TEXTURE_2D, 0, ht, pt, lt.UNSIGNED_BYTE, it._workingCanvas),
                ut.width = nt,
                ut.height = ot),
                !1;
            var _t = new InternalTexture(it,InternalTextureSource.Temp);
            return it._bindTextureDirectly(lt.TEXTURE_2D, _t, !0),
            lt.texImage2D(lt.TEXTURE_2D, 0, ht, pt, lt.UNSIGNED_BYTE, at),
            it._rescaleTexture(_t, ut, s, ht, function() {
                it._releaseTexture(_t),
                it._bindTextureDirectly(lt.TEXTURE_2D, ut, !0),
                ct()
            }),
            !0
        }, b, k, j, $, _e, et, rt)
    }
    ,
    a._FileToolsLoadImage = function(e, i, o, s, c, d) {
        throw _WarnImport("FileTools")
    }
    ,
    a.prototype._rescaleTexture = function(e, i, o, s, c) {}
    ,
    a.prototype.createRawTexture = function(e, i, o, s, c, d, _, b, k) {
        throw _WarnImport("Engine.RawTexture")
    }
    ,
    a.prototype.createRawCubeTexture = function(e, i, o, s, c, d, _, b) {
        throw _WarnImport("Engine.RawTexture")
    }
    ,
    a.prototype.createRawTexture3D = function(e, i, o, s, c, d, _, b, k, j) {
        throw _WarnImport("Engine.RawTexture")
    }
    ,
    a.prototype.createRawTexture2DArray = function(e, i, o, s, c, d, _, b, k, j) {
        throw _WarnImport("Engine.RawTexture")
    }
    ,
    a.prototype._unpackFlipY = function(e) {
        this._unpackFlipYCached !== e && (this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, e ? 1 : 0),
        this.enableUnpackFlipYCached && (this._unpackFlipYCached = e))
    }
    ,
    a.prototype._getUnpackAlignement = function() {
        return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)
    }
    ,
    a.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
    }
    ,
    a.prototype.updateTextureSamplingMode = function(e, i, o) {
        o === void 0 && (o = !1);
        var s = this._getTextureTarget(i)
          , c = this._getSamplingParameters(e, i.generateMipMaps || o);
        this._setTextureParameterInteger(s, this._gl.TEXTURE_MAG_FILTER, c.mag, i),
        this._setTextureParameterInteger(s, this._gl.TEXTURE_MIN_FILTER, c.min),
        o && (i.generateMipMaps = !0,
        this._gl.generateMipmap(s)),
        this._bindTextureDirectly(s, null),
        i.samplingMode = e
    }
    ,
    a.prototype.updateTextureDimensions = function(e, i, o, s) {}
    ,
    a.prototype.updateTextureWrappingMode = function(e, i, o, s) {
        o === void 0 && (o = null),
        s === void 0 && (s = null);
        var c = this._getTextureTarget(e);
        i !== null && (this._setTextureParameterInteger(c, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(i), e),
        e._cachedWrapU = i),
        o !== null && (this._setTextureParameterInteger(c, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(o), e),
        e._cachedWrapV = o),
        (e.is2DArray || e.is3D) && s !== null && (this._setTextureParameterInteger(c, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(s), e),
        e._cachedWrapR = s),
        this._bindTextureDirectly(c, null)
    }
    ,
    a.prototype._setupDepthStencilTexture = function(e, i, o, s, c, d) {
        d === void 0 && (d = 1);
        var _ = i.width || i
          , b = i.height || i
          , k = i.layers || 0;
        e.baseWidth = _,
        e.baseHeight = b,
        e.width = _,
        e.height = b,
        e.is2DArray = k > 0,
        e.depth = k,
        e.isReady = !0,
        e.samples = d,
        e.generateMipMaps = !1,
        e.samplingMode = s ? 2 : 1,
        e.type = 0,
        e._comparisonFunction = c;
        var j = this._gl
          , $ = this._getTextureTarget(e)
          , _e = this._getSamplingParameters(e.samplingMode, !1);
        j.texParameteri($, j.TEXTURE_MAG_FILTER, _e.mag),
        j.texParameteri($, j.TEXTURE_MIN_FILTER, _e.min),
        j.texParameteri($, j.TEXTURE_WRAP_S, j.CLAMP_TO_EDGE),
        j.texParameteri($, j.TEXTURE_WRAP_T, j.CLAMP_TO_EDGE),
        c === 0 ? (j.texParameteri($, j.TEXTURE_COMPARE_FUNC, 515),
        j.texParameteri($, j.TEXTURE_COMPARE_MODE, j.NONE)) : (j.texParameteri($, j.TEXTURE_COMPARE_FUNC, c),
        j.texParameteri($, j.TEXTURE_COMPARE_MODE, j.COMPARE_REF_TO_TEXTURE))
    }
    ,
    a.prototype._uploadCompressedDataToTextureDirectly = function(e, i, o, s, c, d, _) {
        d === void 0 && (d = 0),
        _ === void 0 && (_ = 0);
        var b = this._gl
          , k = b.TEXTURE_2D;
        if (e.isCube && (k = b.TEXTURE_CUBE_MAP_POSITIVE_X + d),
        e._useSRGBBuffer)
            switch (i) {
            case 36492:
                i = b.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;
                break;
            case 37808:
                i = b.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
                break;
            case 33776:
                this._caps.s3tc_srgb ? i = b.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT : e._useSRGBBuffer = !1;
                break;
            case 33779:
                this._caps.s3tc_srgb ? i = b.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT : e._useSRGBBuffer = !1;
                break;
            default:
                e._useSRGBBuffer = !1;
                break
            }
        this._gl.compressedTexImage2D(k, _, i, o, s, 0, c)
    }
    ,
    a.prototype._uploadDataToTextureDirectly = function(e, i, o, s, c, d) {
        o === void 0 && (o = 0),
        s === void 0 && (s = 0),
        d === void 0 && (d = !1);
        var _ = this._gl
          , b = this._getWebGLTextureType(e.type)
          , k = this._getInternalFormat(e.format)
          , j = c === void 0 ? this._getRGBABufferInternalSizedFormat(e.type, e.format, e._useSRGBBuffer) : this._getInternalFormat(c, e._useSRGBBuffer);
        this._unpackFlipY(e.invertY);
        var $ = _.TEXTURE_2D;
        e.isCube && ($ = _.TEXTURE_CUBE_MAP_POSITIVE_X + o);
        var _e = Math.round(Math.log(e.width) * Math.LOG2E)
          , et = Math.round(Math.log(e.height) * Math.LOG2E)
          , tt = d ? e.width : Math.pow(2, Math.max(_e - s, 0))
          , rt = d ? e.height : Math.pow(2, Math.max(et - s, 0));
        _.texImage2D($, s, j, tt, rt, 0, k, b, i)
    }
    ,
    a.prototype.updateTextureData = function(e, i, o, s, c, d, _, b) {
        _ === void 0 && (_ = 0),
        b === void 0 && (b = 0);
        var k = this._gl
          , j = this._getWebGLTextureType(e.type)
          , $ = this._getInternalFormat(e.format);
        this._unpackFlipY(e.invertY);
        var _e = k.TEXTURE_2D;
        e.isCube && (_e = k.TEXTURE_CUBE_MAP_POSITIVE_X + _),
        k.texSubImage2D(_e, b, o, s, c, d, $, j, i)
    }
    ,
    a.prototype._uploadArrayBufferViewToTexture = function(e, i, o, s) {
        o === void 0 && (o = 0),
        s === void 0 && (s = 0);
        var c = this._gl
          , d = e.isCube ? c.TEXTURE_CUBE_MAP : c.TEXTURE_2D;
        this._bindTextureDirectly(d, e, !0),
        this._uploadDataToTextureDirectly(e, i, o, s),
        this._bindTextureDirectly(d, null, !0)
    }
    ,
    a.prototype._prepareWebGLTextureContinuation = function(e, i, o, s, c) {
        var d = this._gl;
        if (!!d) {
            var _ = this._getSamplingParameters(c, !o);
            d.texParameteri(d.TEXTURE_2D, d.TEXTURE_MAG_FILTER, _.mag),
            d.texParameteri(d.TEXTURE_2D, d.TEXTURE_MIN_FILTER, _.min),
            !o && !s && d.generateMipmap(d.TEXTURE_2D),
            this._bindTextureDirectly(d.TEXTURE_2D, null),
            i && i._removePendingData(e),
            e.onLoadedObservable.notifyObservers(e),
            e.onLoadedObservable.clear()
        }
    }
    ,
    a.prototype._prepareWebGLTexture = function(e, i, o, s, c, d, _, b, k) {
        var j = this;
        k === void 0 && (k = 3);
        var $ = this.getCaps().maxTextureSize
          , _e = Math.min($, this.needPOTTextures ? a.GetExponentOfTwo(s.width, $) : s.width)
          , et = Math.min($, this.needPOTTextures ? a.GetExponentOfTwo(s.height, $) : s.height)
          , tt = this._gl;
        if (!!tt) {
            if (!e._hardwareTexture) {
                o && o._removePendingData(e);
                return
            }
            this._bindTextureDirectly(tt.TEXTURE_2D, e, !0),
            this._unpackFlipY(c === void 0 ? !0 : !!c),
            e.baseWidth = s.width,
            e.baseHeight = s.height,
            e.width = _e,
            e.height = et,
            e.isReady = !0,
            !b(_e, et, s, i, e, function() {
                j._prepareWebGLTextureContinuation(e, o, d, _, k)
            }) && this._prepareWebGLTextureContinuation(e, o, d, _, k)
        }
    }
    ,
    a.prototype._setupFramebufferDepthAttachments = function(e, i, o, s, c) {
        c === void 0 && (c = 1);
        var d = this._gl;
        if (e && i)
            return this._createRenderBuffer(o, s, c, d.DEPTH_STENCIL, d.DEPTH24_STENCIL8, d.DEPTH_STENCIL_ATTACHMENT);
        if (i) {
            var _ = d.DEPTH_COMPONENT16;
            return this._webGLVersion > 1 && (_ = d.DEPTH_COMPONENT32F),
            this._createRenderBuffer(o, s, c, _, _, d.DEPTH_ATTACHMENT)
        }
        return e ? this._createRenderBuffer(o, s, c, d.STENCIL_INDEX8, d.STENCIL_INDEX8, d.STENCIL_ATTACHMENT) : null
    }
    ,
    a.prototype._createRenderBuffer = function(e, i, o, s, c, d, _) {
        _ === void 0 && (_ = !0);
        var b = this._gl
          , k = b.createRenderbuffer();
        return b.bindRenderbuffer(b.RENDERBUFFER, k),
        o > 1 && b.renderbufferStorageMultisample ? b.renderbufferStorageMultisample(b.RENDERBUFFER, o, c, e, i) : b.renderbufferStorage(b.RENDERBUFFER, s, e, i),
        b.framebufferRenderbuffer(b.FRAMEBUFFER, d, b.RENDERBUFFER, k),
        _ && b.bindRenderbuffer(b.RENDERBUFFER, null),
        k
    }
    ,
    a.prototype._releaseTexture = function(e) {
        var i;
        this._deleteTexture((i = e._hardwareTexture) === null || i === void 0 ? void 0 : i.underlyingResource),
        this.unbindAllTextures();
        var o = this._internalTexturesCache.indexOf(e);
        o !== -1 && this._internalTexturesCache.splice(o, 1),
        e._lodTextureHigh && e._lodTextureHigh.dispose(),
        e._lodTextureMid && e._lodTextureMid.dispose(),
        e._lodTextureLow && e._lodTextureLow.dispose(),
        e._irradianceTexture && e._irradianceTexture.dispose()
    }
    ,
    a.prototype._releaseRenderTargetWrapper = function(e) {
        var i = this._renderTargetWrapperCache.indexOf(e);
        i !== -1 && this._renderTargetWrapperCache.splice(i, 1)
    }
    ,
    a.prototype._deleteTexture = function(e) {
        e && this._gl.deleteTexture(e)
    }
    ,
    a.prototype._setProgram = function(e) {
        this._currentProgram !== e && (this._gl.useProgram(e),
        this._currentProgram = e)
    }
    ,
    a.prototype.bindSamplers = function(e) {
        var i = e.getPipelineContext();
        this._setProgram(i.program);
        for (var o = e.getSamplers(), s = 0; s < o.length; s++) {
            var c = e.getUniform(o[s]);
            c && (this._boundUniforms[s] = c)
        }
        this._currentEffect = null
    }
    ,
    a.prototype._activateCurrentTexture = function() {
        this._currentTextureChannel !== this._activeChannel && (this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel),
        this._currentTextureChannel = this._activeChannel)
    }
    ,
    a.prototype._bindTextureDirectly = function(e, i, o, s) {
        var c, d;
        o === void 0 && (o = !1),
        s === void 0 && (s = !1);
        var _ = !1
          , b = i && i._associatedChannel > -1;
        o && b && (this._activeChannel = i._associatedChannel);
        var k = this._boundTexturesCache[this._activeChannel];
        if (k !== i || s) {
            if (this._activateCurrentTexture(),
            i && i.isMultiview)
                throw console.error(e, i),
                "_bindTextureDirectly called with a multiview texture!";
            this._gl.bindTexture(e, (d = (c = i == null ? void 0 : i._hardwareTexture) === null || c === void 0 ? void 0 : c.underlyingResource) !== null && d !== void 0 ? d : null),
            this._boundTexturesCache[this._activeChannel] = i,
            i && (i._associatedChannel = this._activeChannel)
        } else
            o && (_ = !0,
            this._activateCurrentTexture());
        return b && !o && this._bindSamplerUniformToChannel(i._associatedChannel, this._activeChannel),
        _
    }
    ,
    a.prototype._bindTexture = function(e, i, o) {
        if (e !== void 0) {
            i && (i._associatedChannel = e),
            this._activeChannel = e;
            var s = i ? this._getTextureTarget(i) : this._gl.TEXTURE_2D;
            this._bindTextureDirectly(s, i)
        }
    }
    ,
    a.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))
    }
    ,
    a.prototype.setTexture = function(e, i, o, s) {
        e !== void 0 && (i && (this._boundUniforms[e] = i),
        this._setTexture(e, o))
    }
    ,
    a.prototype._bindSamplerUniformToChannel = function(e, i) {
        var o = this._boundUniforms[e];
        !o || o._currentState === i || (this._gl.uniform1i(o, i),
        o._currentState = i)
    }
    ,
    a.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
    }
    ,
    a.prototype._setTexture = function(e, i, o, s, c) {
        if (o === void 0 && (o = !1),
        s === void 0 && (s = !1),
        !i)
            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 (i.video)
            this._activeChannel = e,
            i.update();
        else if (i.delayLoadState === 4)
            return i.delayLoad(),
            !1;
        var d;
        s ? d = i.depthStencilTexture : i.isReady() ? d = i.getInternalTexture() : i.isCube ? d = this.emptyCubeTexture : i.is3D ? d = this.emptyTexture3D : i.is2DArray ? d = this.emptyTexture2DArray : d = this.emptyTexture,
        !o && d && (d._associatedChannel = e);
        var _ = !0;
        this._boundTexturesCache[e] === d && (o || this._bindSamplerUniformToChannel(d._associatedChannel, e),
        _ = !1),
        this._activeChannel = e;
        var b = this._getTextureTarget(d);
        if (_ && this._bindTextureDirectly(b, d, o),
        d && !d.isMultiview) {
            if (d.isCube && d._cachedCoordinatesMode !== i.coordinatesMode) {
                d._cachedCoordinatesMode = i.coordinatesMode;
                var k = i.coordinatesMode !== 3 && i.coordinatesMode !== 5 ? 1 : 0;
                i.wrapU = k,
                i.wrapV = k
            }
            d._cachedWrapU !== i.wrapU && (d._cachedWrapU = i.wrapU,
            this._setTextureParameterInteger(b, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(i.wrapU), d)),
            d._cachedWrapV !== i.wrapV && (d._cachedWrapV = i.wrapV,
            this._setTextureParameterInteger(b, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(i.wrapV), d)),
            d.is3D && d._cachedWrapR !== i.wrapR && (d._cachedWrapR = i.wrapR,
            this._setTextureParameterInteger(b, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(i.wrapR), d)),
            this._setAnisotropicLevel(b, d, i.anisotropicFilteringLevel)
        }
        return !0
    }
    ,
    a.prototype.setTextureArray = function(e, i, o, s) {
        if (!(e === void 0 || !i)) {
            (!this._textureUnits || this._textureUnits.length !== o.length) && (this._textureUnits = new Int32Array(o.length));
            for (var c = 0; c < o.length; c++) {
                var d = o[c].getInternalTexture();
                d ? (this._textureUnits[c] = e + c,
                d._associatedChannel = e + c) : this._textureUnits[c] = -1
            }
            this._gl.uniform1iv(i, this._textureUnits);
            for (var _ = 0; _ < o.length; _++)
                this._setTexture(this._textureUnits[_], o[_], !0)
        }
    }
    ,
    a.prototype._setAnisotropicLevel = function(e, i, o) {
        var s = this._caps.textureAnisotropicFilterExtension;
        i.samplingMode !== 11 && i.samplingMode !== 3 && i.samplingMode !== 2 && (o = 1),
        s && i._cachedAnisotropicFilteringLevel !== o && (this._setTextureParameterFloat(e, s.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(o, this._caps.maxAnisotropy), i),
        i._cachedAnisotropicFilteringLevel = o)
    }
    ,
    a.prototype._setTextureParameterFloat = function(e, i, o, s) {
        this._bindTextureDirectly(e, s, !0, !0),
        this._gl.texParameterf(e, i, o)
    }
    ,
    a.prototype._setTextureParameterInteger = function(e, i, o, s) {
        s && this._bindTextureDirectly(e, s, !0, !0),
        this._gl.texParameteri(e, i, o)
    }
    ,
    a.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, i = this._vertexAttribArraysEnabled.length; e < i; e++)
            e >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[e] || this.disableAttributeByIndex(e)
    }
    ,
    a.prototype.releaseEffects = function() {
        for (var e in this._compiledEffects) {
            var i = this._compiledEffects[e].getPipelineContext();
            this._deletePipelineContext(i)
        }
        this._compiledEffects = {}
    }
    ,
    a.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 i = 0, o = this._activeRequests; i < o.length; i++) {
            var s = o[i];
            s.abort()
        }
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear()
    }
    ,
    a.prototype.attachContextLostEvent = function(e) {
        this._renderingCanvas && this._renderingCanvas.addEventListener("webglcontextlost", e, !1)
    }
    ,
    a.prototype.attachContextRestoredEvent = function(e) {
        this._renderingCanvas && this._renderingCanvas.addEventListener("webglcontextrestored", e, !1)
    }
    ,
    a.prototype.getError = function() {
        return this._gl.getError()
    }
    ,
    a.prototype._canRenderToFloatFramebuffer = function() {
        return this._webGLVersion > 1 ? this._caps.colorBufferFloat : this._canRenderToFramebuffer(1)
    }
    ,
    a.prototype._canRenderToHalfFloatFramebuffer = function() {
        return this._webGLVersion > 1 ? this._caps.colorBufferFloat : this._canRenderToFramebuffer(2)
    }
    ,
    a.prototype._canRenderToFramebuffer = function(e) {
        for (var i = this._gl; i.getError() !== i.NO_ERROR; )
            ;
        var o = !0
          , s = i.createTexture();
        i.bindTexture(i.TEXTURE_2D, s),
        i.texImage2D(i.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(e), 1, 1, 0, i.RGBA, this._getWebGLTextureType(e), null),
        i.texParameteri(i.TEXTURE_2D, i.TEXTURE_MIN_FILTER, i.NEAREST),
        i.texParameteri(i.TEXTURE_2D, i.TEXTURE_MAG_FILTER, i.NEAREST);
        var c = i.createFramebuffer();
        i.bindFramebuffer(i.FRAMEBUFFER, c),
        i.framebufferTexture2D(i.FRAMEBUFFER, i.COLOR_ATTACHMENT0, i.TEXTURE_2D, s, 0);
        var d = i.checkFramebufferStatus(i.FRAMEBUFFER);
        if (o = o && d === i.FRAMEBUFFER_COMPLETE,
        o = o && i.getError() === i.NO_ERROR,
        o && (i.clear(i.COLOR_BUFFER_BIT),
        o = o && i.getError() === i.NO_ERROR),
        o) {
            i.bindFramebuffer(i.FRAMEBUFFER, null);
            var _ = i.RGBA
              , b = i.UNSIGNED_BYTE
              , k = new Uint8Array(4);
            i.readPixels(0, 0, 1, 1, _, b, k),
            o = o && i.getError() === i.NO_ERROR
        }
        for (i.deleteTexture(s),
        i.deleteFramebuffer(c),
        i.bindFramebuffer(i.FRAMEBUFFER, null); !o && i.getError() !== i.NO_ERROR; )
            ;
        return o
    }
    ,
    a.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
    }
    ,
    a.prototype._getInternalFormat = function(e, i) {
        i === void 0 && (i = !1);
        var o = i ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA;
        switch (e) {
        case 0:
            o = this._gl.ALPHA;
            break;
        case 1:
            o = this._gl.LUMINANCE;
            break;
        case 2:
            o = this._gl.LUMINANCE_ALPHA;
            break;
        case 6:
            o = this._gl.RED;
            break;
        case 7:
            o = this._gl.RG;
            break;
        case 4:
            o = i ? this._gl.SRGB : this._gl.RGB;
            break;
        case 5:
            o = i ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA;
            break
        }
        if (this._webGLVersion > 1)
            switch (e) {
            case 8:
                o = this._gl.RED_INTEGER;
                break;
            case 9:
                o = this._gl.RG_INTEGER;
                break;
            case 10:
                o = this._gl.RGB_INTEGER;
                break;
            case 11:
                o = this._gl.RGBA_INTEGER;
                break
            }
        return o
    }
    ,
    a.prototype._getRGBABufferInternalSizedFormat = function(e, i, o) {
        if (o === void 0 && (o = !1),
        this._webGLVersion === 1) {
            if (i !== void 0)
                switch (i) {
                case 0:
                    return this._gl.ALPHA;
                case 1:
                    return this._gl.LUMINANCE;
                case 2:
                    return this._gl.LUMINANCE_ALPHA;
                case 4:
                    return o ? this._gl.SRGB : this._gl.RGB
                }
            return this._gl.RGBA
        }
        switch (e) {
        case 3:
            switch (i) {
            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 (i) {
            case 6:
                return this._gl.R8;
            case 7:
                return this._gl.RG8;
            case 4:
                return o ? this._gl.SRGB8 : this._gl.RGB8;
            case 5:
                return o ? 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 (i) {
            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 (i) {
            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 (i) {
            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 (i) {
            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 (i) {
            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 (i) {
            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 (i) {
            case 5:
                return this._gl.RGB10_A2;
            case 11:
                return this._gl.RGB10_A2UI;
            default:
                return this._gl.RGB10_A2
            }
        }
        return o ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA8
    }
    ,
    a.prototype._getRGBAMultiSampleBufferFormat = function(e) {
        return e === 1 ? this._gl.RGBA32F : e === 2 ? this._gl.RGBA16F : this._gl.RGBA8
    }
    ,
    a.prototype._loadFile = function(e, i, o, s, c, d) {
        var _ = this
          , b = a._FileToolsLoadFile(e, i, o, s, c, d);
        return this._activeRequests.push(b),
        b.onCompleteObservable.add(function(k) {
            _._activeRequests.splice(_._activeRequests.indexOf(k), 1)
        }),
        b
    }
    ,
    a._FileToolsLoadFile = function(e, i, o, s, c, d) {
        throw _WarnImport("FileTools")
    }
    ,
    a.prototype.readPixels = function(e, i, o, s, c, d) {
        c === void 0 && (c = !0),
        d === void 0 && (d = !0);
        var _ = c ? 4 : 3
          , b = c ? this._gl.RGBA : this._gl.RGB
          , k = new Uint8Array(s * o * _);
        return d && this.flushFramebuffer(),
        this._gl.readPixels(e, i, o, s, b, this._gl.UNSIGNED_BYTE, k),
        Promise.resolve(k)
    }
    ,
    Object.defineProperty(a, "IsSupportedAsync", {
        get: function() {
            return Promise.resolve(this.isSupported())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "IsSupported", {
        get: function() {
            return this.isSupported()
        },
        enumerable: !1,
        configurable: !0
    }),
    a.isSupported = function() {
        if (this._HasMajorPerformanceCaveat !== null)
            return !this._HasMajorPerformanceCaveat;
        if (this._IsSupported === null)
            try {
                var e = this._createCanvas(1, 1)
                  , i = e.getContext("webgl") || e.getContext("experimental-webgl");
                this._IsSupported = i != null && !!window.WebGLRenderingContext
            } catch {
                this._IsSupported = !1
            }
        return this._IsSupported
    }
    ,
    Object.defineProperty(a, "HasMajorPerformanceCaveat", {
        get: function() {
            if (this._HasMajorPerformanceCaveat === null)
                try {
                    var e = this._createCanvas(1, 1)
                      , i = e.getContext("webgl", {
                        failIfMajorPerformanceCaveat: !0
                    }) || e.getContext("experimental-webgl", {
                        failIfMajorPerformanceCaveat: !0
                    });
                    this._HasMajorPerformanceCaveat = !i
                } catch {
                    this._HasMajorPerformanceCaveat = !1
                }
            return this._HasMajorPerformanceCaveat
        },
        enumerable: !1,
        configurable: !0
    }),
    a.CeilingPOT = function(e) {
        return e--,
        e |= e >> 1,
        e |= e >> 2,
        e |= e >> 4,
        e |= e >> 8,
        e |= e >> 16,
        e++,
        e
    }
    ,
    a.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)
    }
    ,
    a.NearestPOT = function(e) {
        var i = a.CeilingPOT(e)
          , o = a.FloorPOT(e);
        return i - e > e - o ? o : i
    }
    ,
    a.GetExponentOfTwo = function(e, i, o) {
        o === void 0 && (o = 2);
        var s;
        switch (o) {
        case 1:
            s = a.FloorPOT(e);
            break;
        case 2:
            s = a.NearestPOT(e);
            break;
        case 3:
        default:
            s = a.CeilingPOT(e);
            break
        }
        return Math.min(s, i)
    }
    ,
    a.QueueNewFrame = function(e, i) {
        return IsWindowObjectExist() ? (i || (i = window),
        i.requestPostAnimationFrame ? i.requestPostAnimationFrame(e) : i.requestAnimationFrame ? i.requestAnimationFrame(e) : i.msRequestAnimationFrame ? i.msRequestAnimationFrame(e) : i.webkitRequestAnimationFrame ? i.webkitRequestAnimationFrame(e) : i.mozRequestAnimationFrame ? i.mozRequestAnimationFrame(e) : i.oRequestAnimationFrame ? i.oRequestAnimationFrame(e) : window.setTimeout(e, 16)) : typeof requestAnimationFrame != "undefined" ? requestAnimationFrame(e) : setTimeout(e, 16)
    }
    ,
    a.prototype.getHostDocument = function() {
        return this._renderingCanvas && this._renderingCanvas.ownerDocument ? this._renderingCanvas.ownerDocument : document
    }
    ,
    a.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"]
    }],
    a._TextureLoaders = [],
    a.CollisionsEpsilon = .001,
    a._IsSupported = null,
    a._HasMajorPerformanceCaveat = null,
    a
}()
  , PrecisionDate = function() {
    function a() {}
    return Object.defineProperty(a, "Now", {
        get: function() {
            return DomManagement.IsWindowObjectExist() && window.performance && window.performance.now ? window.performance.now() : Date.now()
        },
        enumerable: !1,
        configurable: !0
    }),
    a
}()
  , PerformanceMonitor = function() {
    function a(e) {
        e === void 0 && (e = 30),
        this._enabled = !0,
        this._rollingFrameTime = new RollingAverage(e)
    }
    return a.prototype.sampleFrame = function(e) {
        if (e === void 0 && (e = PrecisionDate.Now),
        !!this._enabled) {
            if (this._lastFrameTimeMs != null) {
                var i = e - this._lastFrameTimeMs;
                this._rollingFrameTime.add(i)
            }
            this._lastFrameTimeMs = e
        }
    }
    ,
    Object.defineProperty(a.prototype, "averageFrameTime", {
        get: function() {
            return this._rollingFrameTime.average
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "averageFrameTimeVariance", {
        get: function() {
            return this._rollingFrameTime.variance
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "instantaneousFrameTime", {
        get: function() {
            return this._rollingFrameTime.history(0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "averageFPS", {
        get: function() {
            return 1e3 / this._rollingFrameTime.average
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "instantaneousFPS", {
        get: function() {
            var e = this._rollingFrameTime.history(0);
            return e === 0 ? 0 : 1e3 / e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isSaturated", {
        get: function() {
            return this._rollingFrameTime.isSaturated()
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.enable = function() {
        this._enabled = !0
    }
    ,
    a.prototype.disable = function() {
        this._enabled = !1,
        this._lastFrameTimeMs = null
    }
    ,
    Object.defineProperty(a.prototype, "isEnabled", {
        get: function() {
            return this._enabled
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.reset = function() {
        this._lastFrameTimeMs = null,
        this._rollingFrameTime.reset()
    }
    ,
    a
}()
  , RollingAverage = function() {
    function a(e) {
        this._samples = new Array(e),
        this.reset()
    }
    return a.prototype.add = function(e) {
        var i;
        if (this.isSaturated()) {
            var o = this._samples[this._pos];
            i = o - this.average,
            this.average -= i / (this._sampleCount - 1),
            this._m2 -= i * (o - this.average)
        } else
            this._sampleCount++;
        i = e - this.average,
        this.average += i / this._sampleCount,
        this._m2 += i * (e - this.average),
        this.variance = this._m2 / (this._sampleCount - 1),
        this._samples[this._pos] = e,
        this._pos++,
        this._pos %= this._samples.length
    }
    ,
    a.prototype.history = function(e) {
        if (e >= this._sampleCount || e >= this._samples.length)
            return 0;
        var i = this._wrapPosition(this._pos - 1);
        return this._samples[this._wrapPosition(i - e)]
    }
    ,
    a.prototype.isSaturated = function() {
        return this._sampleCount >= this._samples.length
    }
    ,
    a.prototype.reset = function() {
        this.average = 0,
        this.variance = 0,
        this._sampleCount = 0,
        this._pos = 0,
        this._m2 = 0
    }
    ,
    a.prototype._wrapPosition = function(e) {
        var i = this._samples.length;
        return (e % i + i) % i
    }
    ,
    a
}()
  , PerfCounter = function() {
    function a() {
        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(a.prototype, "min", {
        get: function() {
            return this._min
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "max", {
        get: function() {
            return this._max
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "average", {
        get: function() {
            return this._average
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "lastSecAverage", {
        get: function() {
            return this._lastSecAverage
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "current", {
        get: function() {
            return this._current
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "total", {
        get: function() {
            return this._totalAccumulated
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "count", {
        get: function() {
            return this._totalValueCount
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.fetchNewFrame = function() {
        this._totalValueCount++,
        this._current = 0,
        this._lastSecValueCount++
    }
    ,
    a.prototype.addCount = function(e, i) {
        !a.Enabled || (this._current += e,
        i && this._fetchResult())
    }
    ,
    a.prototype.beginMonitoring = function() {
        !a.Enabled || (this._startMonitoringTime = PrecisionDate.Now)
    }
    ,
    a.prototype.endMonitoring = function(e) {
        if (e === void 0 && (e = !0),
        !!a.Enabled) {
            e && this.fetchNewFrame();
            var i = PrecisionDate.Now;
            this._current = i - this._startMonitoringTime,
            e && this._fetchResult()
        }
    }
    ,
    a.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)
    }
    ,
    a.Enabled = !0,
    a
}();
ThinEngine.prototype.setAlphaConstants = function(a, e, i, o) {
    this._alphaState.setAlphaBlendConstants(a, e, i, o)
}
;
ThinEngine.prototype.setAlphaMode = function(a, e) {
    if (e === void 0 && (e = !1),
    this._alphaMode !== a) {
        switch (a) {
        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 = a === 0),
        this._alphaMode = a
    }
}
;
ThinEngine.prototype.getAlphaMode = function() {
    return this._alphaMode
}
;
ThinEngine.prototype.setAlphaEquation = function(a) {
    if (this._alphaEquation !== a) {
        switch (a) {
        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 = a
    }
}
;
ThinEngine.prototype.getAlphaEquation = function() {
    return this._alphaEquation
}
;
function allocateAndCopyTypedBuffer(a, e, i, o) {
    switch (i === void 0 && (i = !1),
    a) {
    case 3:
        {
            var s = e instanceof ArrayBuffer ? new Int8Array(e) : new Int8Array(e);
            return o && s.set(new Int8Array(o)),
            s
        }
    case 0:
        {
            var c = e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(e);
            return o && c.set(new Uint8Array(o)),
            c
        }
    case 4:
        {
            var d = e instanceof ArrayBuffer ? new Int16Array(e) : new Int16Array(i ? e / 2 : e);
            return o && d.set(new Int16Array(o)),
            d
        }
    case 5:
    case 8:
    case 9:
    case 10:
    case 2:
        {
            var _ = e instanceof ArrayBuffer ? new Uint16Array(e) : new Uint16Array(i ? e / 2 : e);
            return o && _.set(new Uint16Array(o)),
            _
        }
    case 6:
        {
            var b = e instanceof ArrayBuffer ? new Int32Array(e) : new Int32Array(i ? e / 4 : e);
            return o && b.set(new Int32Array(o)),
            b
        }
    case 7:
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
        {
            var k = e instanceof ArrayBuffer ? new Uint32Array(e) : new Uint32Array(i ? e / 4 : e);
            return o && k.set(new Uint32Array(o)),
            k
        }
    case 1:
        {
            var j = e instanceof ArrayBuffer ? new Float32Array(e) : new Float32Array(i ? e / 4 : e);
            return o && j.set(new Float32Array(o)),
            j
        }
    }
    var $ = e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(e);
    return o && $.set(new Uint8Array(o)),
    $
}
ThinEngine.prototype._readTexturePixelsSync = function(a, e, i, o, s, c, d, _) {
    var b, k;
    o === void 0 && (o = -1),
    s === void 0 && (s = 0),
    c === void 0 && (c = null),
    d === void 0 && (d = !0),
    _ === void 0 && (_ = !1);
    var j = this._gl;
    if (!j)
        throw new Error("Engine does not have gl rendering context.");
    if (!this._dummyFramebuffer) {
        var $ = j.createFramebuffer();
        if (!$)
            throw new Error("Unable to create dummy framebuffer");
        this._dummyFramebuffer = $
    }
    j.bindFramebuffer(j.FRAMEBUFFER, this._dummyFramebuffer),
    o > -1 ? j.framebufferTexture2D(j.FRAMEBUFFER, j.COLOR_ATTACHMENT0, j.TEXTURE_CUBE_MAP_POSITIVE_X + o, (b = a._hardwareTexture) === null || b === void 0 ? void 0 : b.underlyingResource, s) : j.framebufferTexture2D(j.FRAMEBUFFER, j.COLOR_ATTACHMENT0, j.TEXTURE_2D, (k = a._hardwareTexture) === null || k === void 0 ? void 0 : k.underlyingResource, s);
    var _e = a.type !== void 0 ? this._getWebGLTextureType(a.type) : j.UNSIGNED_BYTE;
    if (_)
        c || (c = allocateAndCopyTypedBuffer(a.type, 4 * e * i));
    else
        switch (_e) {
        case j.UNSIGNED_BYTE:
            c || (c = new Uint8Array(4 * e * i)),
            _e = j.UNSIGNED_BYTE;
            break;
        default:
            c || (c = new Float32Array(4 * e * i)),
            _e = j.FLOAT;
            break
        }
    return d && this.flushFramebuffer(),
    j.readPixels(0, 0, e, i, j.RGBA, _e, c),
    j.bindFramebuffer(j.FRAMEBUFFER, this._currentFramebuffer),
    c
}
;
ThinEngine.prototype._readTexturePixels = function(a, e, i, o, s, c, d, _) {
    return o === void 0 && (o = -1),
    s === void 0 && (s = 0),
    c === void 0 && (c = null),
    d === void 0 && (d = !0),
    _ === void 0 && (_ = !1),
    Promise.resolve(this._readTexturePixelsSync(a, e, i, o, s, c, d, _))
}
;
ThinEngine.prototype.updateDynamicIndexBuffer = function(a, e, i) {
    this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null,
    this.bindIndexBuffer(a);
    var o;
    e instanceof Uint16Array || e instanceof Uint32Array ? o = e : o = a.is32Bits ? new Uint32Array(e) : new Uint16Array(e),
    this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, o, this._gl.DYNAMIC_DRAW),
    this._resetIndexBufferBinding()
}
;
ThinEngine.prototype.updateDynamicVertexBuffer = function(a, e, i, o) {
    this.bindArrayBuffer(a),
    i === void 0 && (i = 0);
    var s = e.length || e.byteLength;
    o === void 0 || o >= s && i === 0 ? e instanceof Array ? this._gl.bufferSubData(this._gl.ARRAY_BUFFER, i, new Float32Array(e)) : this._gl.bufferSubData(this._gl.ARRAY_BUFFER, i, e) : e instanceof Array ? this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(e).subarray(i, i + o)) : (e instanceof ArrayBuffer ? e = new Uint8Array(e,i,o) : e = new Uint8Array(e.buffer,e.byteOffset + i,o),
    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, e)),
    this._resetVertexBufferBinding()
}
;
var Engine = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        c === void 0 && (c = !1);
        var d = a.call(this, i, o, s, c) || this;
        if (d.enableOfflineSupport = !1,
        d.disableManifestCheck = !1,
        d.scenes = new Array,
        d._virtualScenes = new Array,
        d.onNewSceneAddedObservable = new Observable,
        d.postProcesses = new Array,
        d.isPointerLock = !1,
        d.onResizeObservable = new Observable,
        d.onCanvasBlurObservable = new Observable,
        d.onCanvasFocusObservable = new Observable,
        d.onCanvasPointerOutObservable = new Observable,
        d.onBeginFrameObservable = new Observable,
        d.customAnimationFrameRequester = null,
        d.onEndFrameObservable = new Observable,
        d.onBeforeShaderCompilationObservable = new Observable,
        d.onAfterShaderCompilationObservable = new Observable,
        d._deterministicLockstep = !1,
        d._lockstepMaxSteps = 4,
        d._timeStep = 1 / 60,
        d._fps = 60,
        d._deltaTime = 0,
        d._drawCalls = new PerfCounter,
        d.canvasTabIndex = 1,
        d.disablePerformanceMonitorInBackground = !1,
        d._performanceMonitor = new PerformanceMonitor,
        d._compatibilityMode = !0,
        d.currentRenderPassId = 0,
        d._renderPassNames = ["main"],
        e.Instances.push(d),
        !i)
            return d;
        if (d._features.supportRenderPasses = !0,
        s = d._creationOptions,
        i.getContext) {
            var _ = i;
            if (d._sharedInit(_, !!s.doNotHandleTouchAction, s.audioEngine),
            IsWindowObjectExist()) {
                var b = document;
                d._onFullscreenChange = function() {
                    b.fullscreen !== void 0 ? d.isFullscreen = b.fullscreen : b.mozFullScreen !== void 0 ? d.isFullscreen = b.mozFullScreen : b.webkitIsFullScreen !== void 0 ? d.isFullscreen = b.webkitIsFullScreen : b.msIsFullScreen !== void 0 && (d.isFullscreen = b.msIsFullScreen),
                    d.isFullscreen && d._pointerLockRequested && _ && e._RequestPointerlock(_)
                }
                ,
                document.addEventListener("fullscreenchange", d._onFullscreenChange, !1),
                document.addEventListener("mozfullscreenchange", d._onFullscreenChange, !1),
                document.addEventListener("webkitfullscreenchange", d._onFullscreenChange, !1),
                document.addEventListener("msfullscreenchange", d._onFullscreenChange, !1),
                d._onPointerLockChange = function() {
                    d.isPointerLock = b.mozPointerLockElement === _ || b.webkitPointerLockElement === _ || b.msPointerLockElement === _ || b.pointerLockElement === _
                }
                ,
                document.addEventListener("pointerlockchange", d._onPointerLockChange, !1),
                document.addEventListener("mspointerlockchange", d._onPointerLockChange, !1),
                document.addEventListener("mozpointerlockchange", d._onPointerLockChange, !1),
                document.addEventListener("webkitpointerlockchange", d._onPointerLockChange, !1),
                !e.audioEngine && s.audioEngine && e.AudioEngineFactory && (e.audioEngine = e.AudioEngineFactory(d.getRenderingCanvas(), d.getAudioContext(), d.getAudioDestination()))
            }
            d._connectVREvents(),
            d.enableOfflineSupport = e.OfflineProviderFactory !== void 0,
            d._deterministicLockstep = !!s.deterministicLockstep,
            d._lockstepMaxSteps = s.lockstepMaxSteps || 0,
            d._timeStep = s.timeStep || 1 / 60
        }
        return d._prepareVRComponent(),
        s.autoEnableWebVR && d.initWebVR(),
        d
    }
    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(i, o) {
        return createImageBitmap(i, o)
    }
    ,
    e.prototype.resizeImageBitmap = function(i, o, s) {
        var c = this.createCanvas(o, s)
          , d = c.getContext("2d");
        if (!d)
            throw new Error("Unable to get 2d context for resizeImageBitmap");
        d.drawImage(i, 0, 0);
        var _ = d.getImageData(0, 0, o, s).data;
        return _
    }
    ,
    e.MarkAllMaterialsAsDirty = function(i, o) {
        for (var s = 0; s < e.Instances.length; s++)
            for (var c = e.Instances[s], d = 0; d < c.scenes.length; d++)
                c.scenes[d].markAllMaterialsAsDirty(i, o)
    }
    ,
    e.DefaultLoadingScreenFactory = function(i) {
        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(i) {
            this._compatibilityMode = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getInputElement = function() {
        return this._renderingCanvas
    }
    ,
    e.prototype._sharedInit = function(i, o, s) {
        var c = this;
        if (a.prototype._sharedInit.call(this, i, o, s),
        this._onCanvasFocus = function() {
            c.onCanvasFocusObservable.notifyObservers(c)
        }
        ,
        this._onCanvasBlur = function() {
            c.onCanvasBlurObservable.notifyObservers(c)
        }
        ,
        i.addEventListener("focus", this._onCanvasFocus),
        i.addEventListener("blur", this._onCanvasBlur),
        this._onBlur = function() {
            c.disablePerformanceMonitorInBackground && c._performanceMonitor.disable(),
            c._windowIsBackground = !0
        }
        ,
        this._onFocus = function() {
            c.disablePerformanceMonitorInBackground && c._performanceMonitor.enable(),
            c._windowIsBackground = !1
        }
        ,
        this._onCanvasPointerOut = function(_) {
            document.elementFromPoint(_.clientX, _.clientY) !== i && c.onCanvasPointerOutObservable.notifyObservers(_)
        }
        ,
        IsWindowObjectExist()) {
            var d = this.getHostWindow();
            d && (d.addEventListener("blur", this._onBlur),
            d.addEventListener("focus", this._onFocus))
        }
        i.addEventListener("pointerout", this._onCanvasPointerOut),
        o || this._disableTouchAction(),
        !e.audioEngine && s && e.AudioEngineFactory && (e.audioEngine = e.AudioEngineFactory(this.getRenderingCanvas(), this.getAudioContext(), this.getAudioDestination()))
    }
    ,
    e.prototype.getAspectRatio = function(i, o) {
        o === void 0 && (o = !1);
        var s = i.viewport;
        return this.getRenderWidth(o) * s.width / (this.getRenderHeight(o) * s.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(i, o) {
        if (o === void 0 && (o = !0),
        i.generateMipMaps) {
            var s = this._gl;
            this._bindTextureDirectly(s.TEXTURE_CUBE_MAP, i, !0),
            s.generateMipmap(s.TEXTURE_CUBE_MAP),
            o && this._bindTextureDirectly(s.TEXTURE_CUBE_MAP, null)
        }
    }
    ,
    e.prototype.getDepthBuffer = function() {
        return this._depthCullingState.depthTest
    }
    ,
    e.prototype.setDepthBuffer = function(i) {
        this._depthCullingState.depthTest = i
    }
    ,
    e.prototype.getDepthWrite = function() {
        return this._depthCullingState.depthMask
    }
    ,
    e.prototype.setDepthWrite = function(i) {
        this._depthCullingState.depthMask = i
    }
    ,
    e.prototype.getStencilBuffer = function() {
        return this._stencilState.stencilTest
    }
    ,
    e.prototype.setStencilBuffer = function(i) {
        this._stencilState.stencilTest = i
    }
    ,
    e.prototype.getStencilMask = function() {
        return this._stencilState.stencilMask
    }
    ,
    e.prototype.setStencilMask = function(i) {
        this._stencilState.stencilMask = i
    }
    ,
    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(i) {
        this._stencilState.stencilFunc = i
    }
    ,
    e.prototype.setStencilFunctionReference = function(i) {
        this._stencilState.stencilFuncRef = i
    }
    ,
    e.prototype.setStencilFunctionMask = function(i) {
        this._stencilState.stencilFuncMask = i
    }
    ,
    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(i) {
        this._stencilState.stencilOpStencilFail = i
    }
    ,
    e.prototype.setStencilOperationDepthFail = function(i) {
        this._stencilState.stencilOpDepthFail = i
    }
    ,
    e.prototype.setStencilOperationPass = function(i) {
        this._stencilState.stencilOpStencilDepthPass = i
    }
    ,
    e.prototype.setDitheringState = function(i) {
        i ? this._gl.enable(this._gl.DITHER) : this._gl.disable(this._gl.DITHER)
    }
    ,
    e.prototype.setRasterizerState = function(i) {
        i ? 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(i) {
        this._depthCullingState.depthFunc = i
    }
    ,
    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(i, o, s, c) {
        var d = this._cachedViewport;
        return this._cachedViewport = null,
        this._viewport(i, o, s, c),
        d
    }
    ,
    e.prototype.scissorClear = function(i, o, s, c, d) {
        this.enableScissor(i, o, s, c),
        this.clear(d, !0, !0, !0),
        this.disableScissor()
    }
    ,
    e.prototype.enableScissor = function(i, o, s, c) {
        var d = this._gl;
        d.enable(d.SCISSOR_TEST),
        d.scissor(i, o, s, c)
    }
    ,
    e.prototype.disableScissor = function() {
        var i = this._gl;
        i.disable(i.SCISSOR_TEST)
    }
    ,
    e.prototype._reportDrawCall = function(i) {
        i === void 0 && (i = 1),
        this._drawCalls.addCount(i, !1)
    }
    ,
    e.prototype.initWebVR = function() {
        throw _WarnImport("WebVRCamera")
    }
    ,
    e.prototype._prepareVRComponent = function() {}
    ,
    e.prototype._connectVREvents = function(i, o) {}
    ,
    e.prototype._submitVRFrame = function() {}
    ,
    e.prototype.disableVR = function() {}
    ,
    e.prototype.isVRPresenting = function() {
        return !1
    }
    ,
    e.prototype._requestVRFrame = function() {}
    ,
    e.prototype._loadFileAsync = function(i, o, s) {
        var c = this;
        return new Promise(function(d, _) {
            c._loadFile(i, function(b) {
                d(b)
            }, void 0, o, s, function(b, k) {
                _(k)
            })
        }
        )
    }
    ,
    e.prototype.getVertexShaderSource = function(i) {
        var o = this._gl.getAttachedShaders(i);
        return o ? this._gl.getShaderSource(o[0]) : null
    }
    ,
    e.prototype.getFragmentShaderSource = function(i) {
        var o = this._gl.getAttachedShaders(i);
        return o ? this._gl.getShaderSource(o[1]) : null
    }
    ,
    e.prototype.setDepthStencilTexture = function(i, o, s, c) {
        i !== void 0 && (o && (this._boundUniforms[i] = o),
        !s || !s.depthStencilTexture ? this._setTexture(i, null, void 0, void 0, c) : this._setTexture(i, s, !1, !0, c))
    }
    ,
    e.prototype.setTextureFromPostProcess = function(i, o, s) {
        var c, d = null;
        o && (o._textures.data[o._currentRenderTextureInd] ? d = o._textures.data[o._currentRenderTextureInd] : o._forcedOutputTexture && (d = o._forcedOutputTexture)),
        this._bindTexture(i, (c = d == null ? void 0 : d.texture) !== null && c !== void 0 ? c : null, s)
    }
    ,
    e.prototype.setTextureFromPostProcessOutput = function(i, o, s) {
        var c, d;
        this._bindTexture(i, (d = (c = o == null ? void 0 : o._outputTexture) === null || c === void 0 ? void 0 : c.texture) !== null && d !== void 0 ? d : null, s)
    }
    ,
    e.prototype._rebuildBuffers = function() {
        for (var i = 0, o = this.scenes; i < o.length; i++) {
            var s = o[i];
            s.resetCachedMaterial(),
            s._rebuildGeometries(),
            s._rebuildTextures()
        }
        for (var c = 0, d = this._virtualScenes; c < d.length; c++) {
            var s = d[c];
            s.resetCachedMaterial(),
            s._rebuildGeometries(),
            s._rebuildTextures()
        }
        a.prototype._rebuildBuffers.call(this)
    }
    ,
    e.prototype._renderFrame = function() {
        for (var i = 0; i < this._activeRenderLoops.length; i++) {
            var o = this._activeRenderLoops[i];
            o()
        }
    }
    ,
    e.prototype._renderLoop = function() {
        if (!this._contextWasLost) {
            var i = !0;
            !this.renderEvenInBackground && this._windowIsBackground && (i = !1),
            i && (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(i) {
        this.isFullscreen ? this.exitFullscreen() : this.enterFullscreen(i)
    }
    ,
    e.prototype.enterFullscreen = function(i) {
        this.isFullscreen || (this._pointerLockRequested = i,
        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),
        a.prototype.beginFrame.call(this)
    }
    ,
    e.prototype.endFrame = function() {
        a.prototype.endFrame.call(this),
        this._submitVRFrame(),
        this.onEndFrameObservable.notifyObservers(this)
    }
    ,
    e.prototype.resize = function(i) {
        i === void 0 && (i = !1),
        !this.isVRPresenting() && a.prototype.resize.call(this, i)
    }
    ,
    e.prototype.setSize = function(i, o, s) {
        if (s === void 0 && (s = !1),
        !this._renderingCanvas || !a.prototype.setSize.call(this, i, o, s))
            return !1;
        if (this.scenes) {
            for (var c = 0; c < this.scenes.length; c++)
                for (var d = this.scenes[c], _ = 0; _ < d.cameras.length; _++) {
                    var b = d.cameras[_];
                    b._currentRenderId = 0
                }
            this.onResizeObservable.hasObservers() && this.onResizeObservable.notifyObservers(this)
        }
        return !0
    }
    ,
    e.prototype._deletePipelineContext = function(i) {
        var o = i;
        o && o.program && o.transformFeedback && (this.deleteTransformFeedback(o.transformFeedback),
        o.transformFeedback = null),
        a.prototype._deletePipelineContext.call(this, i)
    }
    ,
    e.prototype.createShaderProgram = function(i, o, s, c, d, _) {
        _ === void 0 && (_ = null),
        d = d || this._gl,
        this.onBeforeShaderCompilationObservable.notifyObservers(this);
        var b = a.prototype.createShaderProgram.call(this, i, o, s, c, d, _);
        return this.onAfterShaderCompilationObservable.notifyObservers(this),
        b
    }
    ,
    e.prototype._createShaderProgram = function(i, o, s, c, d) {
        d === void 0 && (d = null);
        var _ = c.createProgram();
        if (i.program = _,
        !_)
            throw new Error("Unable to create program");
        if (c.attachShader(_, o),
        c.attachShader(_, s),
        this.webGLVersion > 1 && d) {
            var b = this.createTransformFeedback();
            this.bindTransformFeedback(b),
            this.setTranformFeedbackVaryings(_, d),
            i.transformFeedback = b
        }
        return c.linkProgram(_),
        this.webGLVersion > 1 && d && this.bindTransformFeedback(null),
        i.context = c,
        i.vertexShader = o,
        i.fragmentShader = s,
        i.isParallelCompiled || this._finalizePipelineContext(i),
        _
    }
    ,
    e.prototype._releaseTexture = function(i) {
        a.prototype._releaseTexture.call(this, i)
    }
    ,
    e.prototype._releaseRenderTargetWrapper = function(i) {
        a.prototype._releaseRenderTargetWrapper.call(this, i),
        this.scenes.forEach(function(o) {
            o.postProcesses.forEach(function(s) {
                s._outputTexture === i && (s._outputTexture = null)
            }),
            o.cameras.forEach(function(s) {
                s._postProcesses.forEach(function(c) {
                    c && c._outputTexture === i && (c._outputTexture = null)
                })
            })
        })
    }
    ,
    e.prototype.getRenderPassNames = function() {
        return this._renderPassNames
    }
    ,
    e.prototype.getCurrentRenderPassName = function() {
        return this._renderPassNames[this.currentRenderPassId]
    }
    ,
    e.prototype.createRenderPassId = function(i) {
        var o = ++e._RenderPassIdCounter;
        return this._renderPassNames[o] = i != null ? i : "NONAME",
        o
    }
    ,
    e.prototype.releaseRenderPassId = function(i) {
        this._renderPassNames[i] = void 0;
        for (var o = 0; o < this.scenes.length; ++o)
            for (var s = this.scenes[o], c = 0; c < s.meshes.length; ++c) {
                var d = s.meshes[c];
                if (d.subMeshes)
                    for (var _ = 0; _ < d.subMeshes.length; ++_) {
                        var b = d.subMeshes[_];
                        b._removeDrawWrapper(i)
                    }
            }
    }
    ,
    e.prototype._rescaleTexture = function(i, o, s, c, d) {
        var _ = 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 b = this.createRenderTargetTexture({
            width: o.width,
            height: o.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() {
            _._rescalePostProcess.onApply = function(j) {
                j._bindTexture("textureSampler", i)
            }
            ;
            var k = s;
            k || (k = _.scenes[_.scenes.length - 1]),
            k.postProcessManager.directRender([_._rescalePostProcess], b, !0),
            _._bindTextureDirectly(_._gl.TEXTURE_2D, o, !0),
            _._gl.copyTexImage2D(_._gl.TEXTURE_2D, 0, c, 0, 0, o.width, o.height, 0),
            _.unBindFramebuffer(b),
            b.dispose(),
            d && d()
        })
    }
    ,
    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(i, o, s, c) {
        s === void 0 && (s = 0),
        c === void 0 && (c = 0);
        var d = this._gl
          , _ = this._getWebGLTextureType(i.type)
          , b = this._getInternalFormat(i.format)
          , k = this._getRGBABufferInternalSizedFormat(i.type, b)
          , j = i.isCube ? d.TEXTURE_CUBE_MAP : d.TEXTURE_2D;
        this._bindTextureDirectly(j, i, !0),
        this._unpackFlipY(i.invertY);
        var $ = d.TEXTURE_2D;
        i.isCube && ($ = d.TEXTURE_CUBE_MAP_POSITIVE_X + s),
        d.texImage2D($, c, k, b, _, o),
        this._bindTextureDirectly(j, null, !0)
    }
    ,
    e.prototype.updateTextureComparisonFunction = function(i, o) {
        if (this.webGLVersion === 1) {
            Logger$2.Error("WebGL 1 does not support texture comparison.");
            return
        }
        var s = this._gl;
        i.isCube ? (this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, i, !0),
        o === 0 ? (s.texParameteri(s.TEXTURE_CUBE_MAP, s.TEXTURE_COMPARE_FUNC, 515),
        s.texParameteri(s.TEXTURE_CUBE_MAP, s.TEXTURE_COMPARE_MODE, s.NONE)) : (s.texParameteri(s.TEXTURE_CUBE_MAP, s.TEXTURE_COMPARE_FUNC, o),
        s.texParameteri(s.TEXTURE_CUBE_MAP, s.TEXTURE_COMPARE_MODE, s.COMPARE_REF_TO_TEXTURE)),
        this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null)) : (this._bindTextureDirectly(this._gl.TEXTURE_2D, i, !0),
        o === 0 ? (s.texParameteri(s.TEXTURE_2D, s.TEXTURE_COMPARE_FUNC, 515),
        s.texParameteri(s.TEXTURE_2D, s.TEXTURE_COMPARE_MODE, s.NONE)) : (s.texParameteri(s.TEXTURE_2D, s.TEXTURE_COMPARE_FUNC, o),
        s.texParameteri(s.TEXTURE_2D, s.TEXTURE_COMPARE_MODE, s.COMPARE_REF_TO_TEXTURE)),
        this._bindTextureDirectly(this._gl.TEXTURE_2D, null)),
        i._comparisonFunction = o
    }
    ,
    e.prototype.createInstancesBuffer = function(i) {
        var o = this._gl.createBuffer();
        if (!o)
            throw new Error("Unable to create instance buffer");
        var s = new WebGLDataBuffer(o);
        return s.capacity = i,
        this.bindArrayBuffer(s),
        this._gl.bufferData(this._gl.ARRAY_BUFFER, i, this._gl.DYNAMIC_DRAW),
        s.references = 1,
        s
    }
    ,
    e.prototype.deleteInstancesBuffer = function(i) {
        this._gl.deleteBuffer(i)
    }
    ,
    e.prototype._clientWaitAsync = function(i, o, s) {
        o === void 0 && (o = 0),
        s === void 0 && (s = 10);
        var c = this._gl;
        return new Promise(function(d, _) {
            var b = function() {
                var k = c.clientWaitSync(i, o, 0);
                if (k == c.WAIT_FAILED) {
                    _();
                    return
                }
                if (k == c.TIMEOUT_EXPIRED) {
                    setTimeout(b, s);
                    return
                }
                d()
            };
            b()
        }
        )
    }
    ,
    e.prototype._readPixelsAsync = function(i, o, s, c, d, _, b) {
        if (this._webGLVersion < 2)
            throw new Error("_readPixelsAsync only work on WebGL2+");
        var k = this._gl
          , j = k.createBuffer();
        k.bindBuffer(k.PIXEL_PACK_BUFFER, j),
        k.bufferData(k.PIXEL_PACK_BUFFER, b.byteLength, k.STREAM_READ),
        k.readPixels(i, o, s, c, d, _, 0),
        k.bindBuffer(k.PIXEL_PACK_BUFFER, null);
        var $ = k.fenceSync(k.SYNC_GPU_COMMANDS_COMPLETE, 0);
        return $ ? (k.flush(),
        this._clientWaitAsync($, 0, 10).then(function() {
            return k.deleteSync($),
            k.bindBuffer(k.PIXEL_PACK_BUFFER, j),
            k.getBufferSubData(k.PIXEL_PACK_BUFFER, 0, b),
            k.bindBuffer(k.PIXEL_PACK_BUFFER, null),
            k.deleteBuffer(j),
            b
        })) : 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))),
        a.prototype.dispose.call(this);
        var i = e.Instances.indexOf(this);
        i >= 0 && e.Instances.splice(i, 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 i = this.loadingScreen;
            i && i.displayLoadingUI()
        }
    }
    ,
    e.prototype.hideLoadingUI = function() {
        if (!!IsWindowObjectExist()) {
            var i = this._loadingScreen;
            i && i.hideLoadingUI()
        }
    }
    ,
    Object.defineProperty(e.prototype, "loadingScreen", {
        get: function() {
            return !this._loadingScreen && this._renderingCanvas && (this._loadingScreen = e.DefaultLoadingScreenFactory(this._renderingCanvas)),
            this._loadingScreen
        },
        set: function(i) {
            this._loadingScreen = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "loadingUIText", {
        set: function(i) {
            this.loadingScreen.loadingUIText = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "loadingUIBackgroundColor", {
        set: function(i) {
            this.loadingScreen.loadingUIBackgroundColor = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.createVideoElement = function(i) {
        return document.createElement("video")
    }
    ,
    e._RequestPointerlock = function(i) {
        i.requestPointerLock = i.requestPointerLock || i.msRequestPointerLock || i.mozRequestPointerLock || i.webkitRequestPointerLock,
        i.requestPointerLock && i.requestPointerLock()
    }
    ,
    e._ExitPointerlock = function() {
        var i = document;
        document.exitPointerLock = document.exitPointerLock || i.msExitPointerLock || i.mozExitPointerLock || i.webkitExitPointerLock,
        document.exitPointerLock && document.exitPointerLock()
    }
    ,
    e._RequestFullscreen = function(i) {
        var o = i.requestFullscreen || i.msRequestFullscreen || i.webkitRequestFullscreen || i.mozRequestFullScreen;
        !o || o.call(i)
    }
    ,
    e._ExitFullscreen = function() {
        var i = document;
        document.exitFullscreen ? document.exitFullscreen() : i.mozCancelFullScreen ? i.mozCancelFullScreen() : i.webkitCancelFullScreen ? i.webkitCancelFullScreen() : i.msCancelFullScreen && i.msCancelFullScreen()
    }
    ,
    e.prototype.getFontOffset = function(i) {
        var o = document.createElement("span");
        o.innerHTML = "Hg",
        o.setAttribute("style", "font: " + i + " !important");
        var s = document.createElement("div");
        s.style.display = "inline-block",
        s.style.width = "1px",
        s.style.height = "0px",
        s.style.verticalAlign = "bottom";
        var c = document.createElement("div");
        c.style.whiteSpace = "nowrap",
        c.appendChild(o),
        c.appendChild(s),
        document.body.appendChild(c);
        var d = 0
          , _ = 0;
        try {
            _ = s.getBoundingClientRect().top - o.getBoundingClientRect().top,
            s.style.verticalAlign = "baseline",
            d = s.getBoundingClientRect().top - o.getBoundingClientRect().top
        } finally {
            document.body.removeChild(c)
        }
        return {
            ascent: d,
            height: _,
            descent: _ - d
        }
    }
    ,
    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)
  , RenderTargetWrapper = function() {
    function a(e, i, o, s) {
        this._textures = null,
        this._attachments = null,
        this._generateStencilBuffer = !1,
        this._generateDepthBuffer = !1,
        this._depthStencilTextureWithStencil = !1,
        this._isMulti = e,
        this._isCube = i,
        this._size = o,
        this._engine = s,
        this._depthStencilTexture = null
    }
    return Object.defineProperty(a.prototype, "isCube", {
        get: function() {
            return this._isCube
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isMulti", {
        get: function() {
            return this._isMulti
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "is2DArray", {
        get: function() {
            return this.layers > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "size", {
        get: function() {
            return this.width
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "width", {
        get: function() {
            return this._size.width || this._size
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "height", {
        get: function() {
            return this._size.height || this._size
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "layers", {
        get: function() {
            return this._size.layers || 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "texture", {
        get: function() {
            var e, i;
            return (i = (e = this._textures) === null || e === void 0 ? void 0 : e[0]) !== null && i !== void 0 ? i : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "textures", {
        get: function() {
            return this._textures
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "samples", {
        get: function() {
            var e, i;
            return (i = (e = this.texture) === null || e === void 0 ? void 0 : e.samples) !== null && i !== void 0 ? i : 1
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setSamples = function(e, i, o) {
        return i === void 0 && (i = !0),
        o === void 0 && (o = !1),
        this.samples === e && !o ? e : this._isMulti ? this._engine.updateMultipleRenderTargetTextureSampleCount(this, e, i) : this._engine.updateRenderTargetTextureSampleCount(this, e)
    }
    ,
    a.prototype.setTextures = function(e) {
        Array.isArray(e) ? this._textures = e : e ? this._textures = [e] : this._textures = null
    }
    ,
    a.prototype.setTexture = function(e, i, o) {
        i === void 0 && (i = 0),
        o === void 0 && (o = !0),
        this._textures || (this._textures = []),
        this._textures[i] && o && this._textures[i].dispose(),
        this._textures[i] = e
    }
    ,
    a.prototype.createDepthStencilTexture = function(e, i, o, s, c) {
        var d;
        return e === void 0 && (e = 0),
        i === void 0 && (i = !0),
        o === void 0 && (o = !1),
        s === void 0 && (s = 1),
        c === void 0 && (c = 15),
        (d = this._depthStencilTexture) === null || d === void 0 || d.dispose(),
        this._depthStencilTextureWithStencil = o,
        this._depthStencilTexture = this._engine.createDepthStencilTexture(this._size, {
            bilinearFiltering: i,
            comparisonFunction: e,
            generateStencil: o,
            isCube: this._isCube,
            samples: s,
            depthTextureFormat: c
        }, this),
        this._depthStencilTexture
    }
    ,
    a.prototype._shareDepth = function(e) {
        this._depthStencilTexture && (e._depthStencilTexture && e._depthStencilTexture.dispose(),
        e._depthStencilTexture = this._depthStencilTexture,
        this._depthStencilTexture.incrementReferences())
    }
    ,
    a.prototype._swapAndDie = function(e) {
        this.texture && this.texture._swapAndDie(e),
        this._textures = null,
        this.dispose(!0)
    }
    ,
    a.prototype._cloneRenderTargetWrapper = function() {
        var e, i, o, s, c, d, _ = null;
        if (this._isMulti) {
            var b = this.textures;
            if (b && b.length > 0) {
                var k = !1
                  , j = b.length
                  , $ = b[b.length - 1]._source;
                ($ === InternalTextureSource.Depth || $ === InternalTextureSource.DepthStencil) && (k = !0,
                j--);
                for (var _e = [], et = [], tt = 0; tt < j; ++tt) {
                    var rt = b[tt];
                    _e.push(rt.samplingMode),
                    et.push(rt.type)
                }
                var it = {
                    samplingModes: _e,
                    generateMipMaps: b[0].generateMipMaps,
                    generateDepthBuffer: this._generateDepthBuffer,
                    generateStencilBuffer: this._generateStencilBuffer,
                    generateDepthTexture: k,
                    types: et,
                    textureCount: j
                }
                  , nt = {
                    width: this.width,
                    height: this.height
                };
                _ = this._engine.createMultipleRenderTarget(nt, it)
            }
        } else {
            var ot = {};
            if (ot.generateDepthBuffer = this._generateDepthBuffer,
            ot.generateMipMaps = (i = (e = this.texture) === null || e === void 0 ? void 0 : e.generateMipMaps) !== null && i !== void 0 ? i : !1,
            ot.generateStencilBuffer = this._generateStencilBuffer,
            ot.samplingMode = (o = this.texture) === null || o === void 0 ? void 0 : o.samplingMode,
            ot.type = (s = this.texture) === null || s === void 0 ? void 0 : s.type,
            ot.format = (c = this.texture) === null || c === void 0 ? void 0 : c.format,
            this.isCube)
                _ = this._engine.createRenderTargetCubeTexture(this.width, ot);
            else {
                var nt = {
                    width: this.width,
                    height: this.height,
                    layers: this.is2DArray ? (d = this.texture) === null || d === void 0 ? void 0 : d.depth : void 0
                };
                _ = this._engine.createRenderTargetTexture(nt, ot)
            }
            _.texture.isReady = !0
        }
        return _
    }
    ,
    a.prototype._swapRenderTargetWrapper = function(e) {
        if (this._textures && e._textures)
            for (var i = 0; i < this._textures.length; ++i)
                this._textures[i]._swapAndDie(e._textures[i], !1),
                e._textures[i].isReady = !0;
        this._depthStencilTexture && e._depthStencilTexture && (this._depthStencilTexture._swapAndDie(e._depthStencilTexture),
        e._depthStencilTexture.isReady = !0),
        this._textures = null,
        this._depthStencilTexture = null
    }
    ,
    a.prototype._rebuild = function() {
        var e = this._cloneRenderTargetWrapper();
        if (!!e) {
            if (this._depthStencilTexture) {
                var i = this._depthStencilTexture.samplingMode
                  , o = i === 2 || i === 3 || i === 11;
                e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction, o, this._depthStencilTextureWithStencil, this._depthStencilTexture.samples)
            }
            this.samples > 1 && e.setSamples(this.samples),
            e._swapRenderTargetWrapper(this),
            e.dispose()
        }
    }
    ,
    a.prototype.releaseTextures = function() {
        var e, i;
        if (this._textures)
            for (var o = 0; (i = o < ((e = this._textures) === null || e === void 0 ? void 0 : e.length)) !== null && i !== void 0 && i; ++o)
                this._textures[o].dispose();
        this._textures = null
    }
    ,
    a.prototype.dispose = function(e) {
        var i;
        e === void 0 && (e = !1),
        e || ((i = this._depthStencilTexture) === null || i === void 0 || i.dispose(),
        this._depthStencilTexture = null,
        this.releaseTextures()),
        this._engine._releaseRenderTargetWrapper(this)
    }
    ,
    a
}()
  , NullEngineOptions = function() {
    function a() {
        this.renderWidth = 512,
        this.renderHeight = 256,
        this.textureSize = 512,
        this.deterministicLockstep = !1,
        this.lockstepMaxSteps = 4
    }
    return a
}();
(function(a) {
    __extends(e, a);
    function e(i) {
        i === void 0 && (i = new NullEngineOptions);
        var o = a.call(this, null) || this;
        Engine.Instances.push(o),
        i.deterministicLockstep === void 0 && (i.deterministicLockstep = !1),
        i.lockstepMaxSteps === void 0 && (i.lockstepMaxSteps = 4),
        o._options = i,
        PerformanceConfigurator.SetMatrixPrecision(!!i.useHighPrecisionMatrix),
        o._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
        },
        o._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 s = typeof self != "undefined" ? self : typeof global != "undefined" ? global : window;
        return typeof URL == "undefined" && (s.URL = {
            createObjectURL: function() {},
            revokeObjectURL: function() {}
        }),
        typeof Blob == "undefined" && (s.Blob = function() {}
        ),
        o
    }
    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(i) {
        var o = new DataBuffer;
        return o.references = 1,
        o
    }
    ,
    e.prototype.createIndexBuffer = function(i) {
        var o = new DataBuffer;
        return o.references = 1,
        o
    }
    ,
    e.prototype.clear = function(i, o, s, c) {}
    ,
    e.prototype.getRenderWidth = function(i) {
        return i === void 0 && (i = !1),
        !i && this._currentRenderTarget ? this._currentRenderTarget.width : this._options.renderWidth
    }
    ,
    e.prototype.getRenderHeight = function(i) {
        return i === void 0 && (i = !1),
        !i && this._currentRenderTarget ? this._currentRenderTarget.height : this._options.renderHeight
    }
    ,
    e.prototype.setViewport = function(i, o, s) {
        this._cachedViewport = i
    }
    ,
    e.prototype.createShaderProgram = function(i, o, s, c, d) {
        return {
            __SPECTOR_rebuildProgram: null
        }
    }
    ,
    e.prototype.getUniforms = function(i, o) {
        return []
    }
    ,
    e.prototype.getAttributes = function(i, o) {
        return []
    }
    ,
    e.prototype.bindSamplers = function(i) {
        this._currentEffect = null
    }
    ,
    e.prototype.enableEffect = function(i) {
        i = i !== null && DrawWrapper.IsWrapper(i) ? i.effect : i,
        this._currentEffect = i,
        i && (i.onBind && i.onBind(i),
        i._onBindObservable && i._onBindObservable.notifyObservers(i))
    }
    ,
    e.prototype.setState = function(i, o, s, c, d, _, b) {}
    ,
    e.prototype.setIntArray = function(i, o) {
        return !0
    }
    ,
    e.prototype.setIntArray2 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setIntArray3 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setIntArray4 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setFloatArray = function(i, o) {
        return !0
    }
    ,
    e.prototype.setFloatArray2 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setFloatArray3 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setFloatArray4 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setArray = function(i, o) {
        return !0
    }
    ,
    e.prototype.setArray2 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setArray3 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setArray4 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setMatrices = function(i, o) {
        return !0
    }
    ,
    e.prototype.setMatrix3x3 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setMatrix2x2 = function(i, o) {
        return !0
    }
    ,
    e.prototype.setFloat = function(i, o) {
        return !0
    }
    ,
    e.prototype.setFloat2 = function(i, o, s) {
        return !0
    }
    ,
    e.prototype.setFloat3 = function(i, o, s, c) {
        return !0
    }
    ,
    e.prototype.setBool = function(i, o) {
        return !0
    }
    ,
    e.prototype.setFloat4 = function(i, o, s, c, d) {
        return !0
    }
    ,
    e.prototype.setAlphaMode = function(i, o) {
        o === void 0 && (o = !1),
        this._alphaMode !== i && (this.alphaState.alphaBlend = i !== 0,
        o || this.setDepthWrite(i === 0),
        this._alphaMode = i)
    }
    ,
    e.prototype.bindBuffers = function(i, o, s) {}
    ,
    e.prototype.wipeCaches = function(i) {
        this.preventCacheWipeBetweenFrames || (this.resetTextureCache(),
        this._currentEffect = null,
        i && (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(i, o, s, c) {}
    ,
    e.prototype.drawElementsType = function(i, o, s, c) {}
    ,
    e.prototype.drawArraysType = function(i, o, s, c) {}
    ,
    e.prototype._createTexture = function() {
        return {}
    }
    ,
    e.prototype._releaseTexture = function(i) {}
    ,
    e.prototype.createTexture = function(i, o, s, c, d, _, b, k, j, $, _e, et) {
        d === void 0 && (d = 3),
        _ === void 0 && (_ = null),
        $ === void 0 && ($ = null);
        var tt = new InternalTexture(this,InternalTextureSource.Url)
          , rt = String(i);
        return tt.url = rt,
        tt.generateMipMaps = !o,
        tt.samplingMode = d,
        tt.invertY = s,
        tt.baseWidth = this._options.textureSize,
        tt.baseHeight = this._options.textureSize,
        tt.width = this._options.textureSize,
        tt.height = this._options.textureSize,
        $ && (tt.format = $),
        tt.isReady = !0,
        _ && _(),
        this._internalTexturesCache.push(tt),
        tt
    }
    ,
    e.prototype._createHardwareRenderTargetWrapper = function(i, o, s) {
        var c = new RenderTargetWrapper(i,o,s,this);
        return this._renderTargetWrapperCache.push(c),
        c
    }
    ,
    e.prototype.createRenderTargetTexture = function(i, o) {
        var s = this._createHardwareRenderTargetWrapper(!1, !1, i)
          , c = {};
        o !== void 0 && typeof o == "object" ? (c.generateMipMaps = o.generateMipMaps,
        c.generateDepthBuffer = o.generateDepthBuffer === void 0 ? !0 : o.generateDepthBuffer,
        c.generateStencilBuffer = c.generateDepthBuffer && o.generateStencilBuffer,
        c.type = o.type === void 0 ? 0 : o.type,
        c.samplingMode = o.samplingMode === void 0 ? 3 : o.samplingMode) : (c.generateMipMaps = o,
        c.generateDepthBuffer = !0,
        c.generateStencilBuffer = !1,
        c.type = 0,
        c.samplingMode = 3);
        var d = new InternalTexture(this,InternalTextureSource.RenderTarget)
          , _ = i.width || i
          , b = i.height || i;
        return s._generateDepthBuffer = c.generateDepthBuffer,
        s._generateStencilBuffer = !!c.generateStencilBuffer,
        d.baseWidth = _,
        d.baseHeight = b,
        d.width = _,
        d.height = b,
        d.isReady = !0,
        d.samples = 1,
        d.generateMipMaps = !!c.generateMipMaps,
        d.samplingMode = c.samplingMode,
        d.type = c.type,
        this._internalTexturesCache.push(d),
        s
    }
    ,
    e.prototype.updateTextureSamplingMode = function(i, o) {
        o.samplingMode = i
    }
    ,
    e.prototype.createRawTexture = function(i, o, s, c, d, _, b, k, j, $) {
        k === void 0 && (k = null),
        j === void 0 && (j = 0);
        var _e = new InternalTexture(this,InternalTextureSource.Raw);
        return _e.baseWidth = o,
        _e.baseHeight = s,
        _e.width = o,
        _e.height = s,
        _e.format = c,
        _e.generateMipMaps = d,
        _e.samplingMode = b,
        _e.invertY = _,
        _e._compression = k,
        _e.type = j,
        this._doNotHandleContextLost || (_e._bufferView = i),
        _e
    }
    ,
    e.prototype.updateRawTexture = function(i, o, s, c, d, _) {
        d === void 0 && (d = null),
        _ === void 0 && (_ = 0),
        i && (i._bufferView = o,
        i.format = s,
        i.invertY = c,
        i._compression = d,
        i.type = _)
    }
    ,
    e.prototype.bindFramebuffer = function(i, o, s, c, d) {
        this._currentRenderTarget && this.unBindFramebuffer(this._currentRenderTarget),
        this._currentRenderTarget = i,
        this._currentFramebuffer = null,
        this._cachedViewport && !d && this.setViewport(this._cachedViewport, s, c)
    }
    ,
    e.prototype.unBindFramebuffer = function(i, o, s) {
        this._currentRenderTarget = null,
        s && s(),
        this._currentFramebuffer = null
    }
    ,
    e.prototype.createDynamicVertexBuffer = function(i) {
        var o = new DataBuffer;
        return o.references = 1,
        o.capacity = 1,
        o
    }
    ,
    e.prototype.updateDynamicTexture = function(i, o, s, c, d) {}
    ,
    e.prototype.areAllEffectsReady = function() {
        return !0
    }
    ,
    e.prototype.getError = function() {
        return 0
    }
    ,
    e.prototype._getUnpackAlignement = function() {
        return 1
    }
    ,
    e.prototype._unpackFlipY = function(i) {}
    ,
    e.prototype.updateDynamicIndexBuffer = function(i, o, s) {}
    ,
    e.prototype.updateDynamicVertexBuffer = function(i, o, s, c) {}
    ,
    e.prototype._bindTextureDirectly = function(i, o) {
        return this._boundTexturesCache[this._activeChannel] !== o ? (this._boundTexturesCache[this._activeChannel] = o,
        !0) : !1
    }
    ,
    e.prototype._bindTexture = function(i, o) {
        i < 0 || this._bindTextureDirectly(0, o)
    }
    ,
    e.prototype._deleteBuffer = function(i) {}
    ,
    e.prototype.releaseEffects = function() {}
    ,
    e.prototype.displayLoadingUI = function() {}
    ,
    e.prototype.hideLoadingUI = function() {}
    ,
    e.prototype._uploadCompressedDataToTextureDirectly = function(i, o, s, c, d, _, b) {}
    ,
    e.prototype._uploadDataToTextureDirectly = function(i, o, s, c) {}
    ,
    e.prototype._uploadArrayBufferViewToTexture = function(i, o, s, c) {}
    ,
    e.prototype._uploadImageToTexture = function(i, o, s, c) {}
    ,
    e
}
)(Engine);
ThinEngine.prototype._debugPushGroup = function(a, e) {}
;
ThinEngine.prototype._debugPopGroup = function(a) {}
;
ThinEngine.prototype._debugInsertMarker = function(a, e) {}
;
ThinEngine.prototype._debugFlushPendingCommands = function() {}
;
var cloneValue = function(a, e) {
    return !a || a.getClassName && a.getClassName() === "Mesh" ? null : a.getClassName && a.getClassName() === "SubMesh" ? a.clone(e) : a.clone ? a.clone() : null
};
function getAllPropertyNames(a) {
    var e = [];
    do
        Object.getOwnPropertyNames(a).forEach(function(i) {
            e.indexOf(i) === -1 && e.push(i)
        });
    while (a = Object.getPrototypeOf(a));
    return e
}
var DeepCopier = function() {
    function a() {}
    return a.DeepCopy = function(e, i, o, s) {
        for (var c = getAllPropertyNames(e), d = 0, _ = c; d < _.length; d++) {
            var b = _[d];
            if (!(b[0] === "_" && (!s || s.indexOf(b) === -1)) && !EndsWith(b, "Observable") && !(o && o.indexOf(b) !== -1)) {
                var k = e[b]
                  , j = typeof k;
                if (j !== "function")
                    try {
                        if (j === "object")
                            if (k instanceof Array) {
                                if (i[b] = [],
                                k.length > 0)
                                    if (typeof k[0] == "object")
                                        for (var $ = 0; $ < k.length; $++) {
                                            var _e = cloneValue(k[$], i);
                                            i[b].indexOf(_e) === -1 && i[b].push(_e)
                                        }
                                    else
                                        i[b] = k.slice(0)
                            } else
                                i[b] = cloneValue(k, i);
                        else
                            i[b] = k
                    } catch (et) {
                        Logger$2.Warn(et.message)
                    }
            }
        }
    }
    ,
    a
}();
function createXMLHttpRequest() {
    return typeof _native != "undefined" && _native.XMLHttpRequest ? new _native.XMLHttpRequest : new XMLHttpRequest
}
var WebRequest = function() {
    function a() {
        this._xhr = createXMLHttpRequest()
    }
    return a.prototype._injectCustomRequestHeaders = function() {
        for (var e in a.CustomRequestHeaders) {
            var i = a.CustomRequestHeaders[e];
            i && this._xhr.setRequestHeader(e, i)
        }
    }
    ,
    Object.defineProperty(a.prototype, "onprogress", {
        get: function() {
            return this._xhr.onprogress
        },
        set: function(e) {
            this._xhr.onprogress = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "readyState", {
        get: function() {
            return this._xhr.readyState
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "status", {
        get: function() {
            return this._xhr.status
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "statusText", {
        get: function() {
            return this._xhr.statusText
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "response", {
        get: function() {
            return this._xhr.response
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "responseURL", {
        get: function() {
            return this._xhr.responseURL
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "responseText", {
        get: function() {
            return this._xhr.responseText
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "responseType", {
        get: function() {
            return this._xhr.responseType
        },
        set: function(e) {
            this._xhr.responseType = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "timeout", {
        get: function() {
            return this._xhr.timeout
        },
        set: function(e) {
            this._xhr.timeout = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.addEventListener = function(e, i, o) {
        this._xhr.addEventListener(e, i, o)
    }
    ,
    a.prototype.removeEventListener = function(e, i, o) {
        this._xhr.removeEventListener(e, i, o)
    }
    ,
    a.prototype.abort = function() {
        this._xhr.abort()
    }
    ,
    a.prototype.send = function(e) {
        a.CustomRequestHeaders && this._injectCustomRequestHeaders(),
        this._xhr.send(e)
    }
    ,
    a.prototype.open = function(e, i) {
        for (var o = 0, s = a.CustomRequestModifiers; o < s.length; o++) {
            var c = s[o];
            c(this._xhr, i)
        }
        return i = i.replace("file:http:", "http:"),
        i = i.replace("file:https:", "https:"),
        this._xhr.open(e, i, !0)
    }
    ,
    a.prototype.setRequestHeader = function(e, i) {
        this._xhr.setRequestHeader(e, i)
    }
    ,
    a.prototype.getResponseHeader = function(e) {
        return this._xhr.getResponseHeader(e)
    }
    ,
    a.CustomRequestHeaders = {},
    a.CustomRequestModifiers = new Array,
    a
}(), FilesInputStore = function() {
    function a() {}
    return a.FilesToLoad = {},
    a
}(), RetryStrategy = function() {
    function a() {}
    return a.ExponentialBackoff = function(e, i) {
        return e === void 0 && (e = 3),
        i === void 0 && (i = 500),
        function(o, s, c) {
            return s.status !== 0 || c >= e || o.indexOf("file:") !== -1 ? -1 : Math.pow(2, c) * i
        }
    }
    ,
    a
}(), BaseError = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e._setPrototypeOf = Object.setPrototypeOf || function(i, o) {
        return i.__proto__ = o,
        i
    }
    ,
    e
}(Error), TimingTools = function() {
    function a() {}
    return a.SetImmediate = function(e) {
        IsWindowObjectExist() && window.setImmediate ? window.setImmediate(e) : setTimeout(e, 1)
    }
    ,
    a
}(), FileTools, _injectLTSFileTools = function(a, e, i, o, s, c, d, _, b, k) {
    FileTools = {
        DecodeBase64UrlToBinary: a,
        DecodeBase64UrlToString: e,
        DefaultRetryStrategy: i.DefaultRetryStrategy,
        BaseUrl: i.BaseUrl,
        CorsBehavior: i.CorsBehavior,
        PreprocessUrl: i.PreprocessUrl,
        IsBase64DataUrl: o,
        IsFileURL: s,
        LoadFile: c,
        LoadImage: d,
        ReadFile: _,
        RequestFile: b,
        SetCorsBehavior: k
    },
    Object.defineProperty(FileTools, "DefaultRetryStrategy", {
        get: function() {
            return i.DefaultRetryStrategy
        },
        set: function(j) {
            i.DefaultRetryStrategy = j
        }
    }),
    Object.defineProperty(FileTools, "BaseUrl", {
        get: function() {
            return i.BaseUrl
        },
        set: function(j) {
            i.BaseUrl = j
        }
    }),
    Object.defineProperty(FileTools, "PreprocessUrl", {
        get: function() {
            return i.PreprocessUrl
        },
        set: function(j) {
            i.PreprocessUrl = j
        }
    }),
    Object.defineProperty(FileTools, "CorsBehavior", {
        get: function() {
            return i.CorsBehavior
        },
        set: function(j) {
            i.CorsBehavior = j
        }
    })
}, base64DataUrlRegEx = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i), LoadFileError = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i) || this;
        return s.name = "LoadFileError",
        BaseError._setPrototypeOf(s, e.prototype),
        o instanceof WebRequest ? s.request = o : s.file = o,
        s
    }
    return e
}(BaseError), RequestFileError = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i) || this;
        return s.request = o,
        s.name = "RequestFileError",
        BaseError._setPrototypeOf(s, e.prototype),
        s
    }
    return e
}(BaseError), ReadFileError = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i) || this;
        return s.file = o,
        s.name = "ReadFileError",
        BaseError._setPrototypeOf(s, e.prototype),
        s
    }
    return e
}(BaseError), FileToolsOptions = {
    DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(),
    BaseUrl: "",
    CorsBehavior: "anonymous",
    PreprocessUrl: function(a) {
        return a
    }
}, _CleanUrl = function(a) {
    return a = a.replace(/#/mg, "%23"),
    a
}, SetCorsBehavior = function(a, e) {
    if (!(a && a.indexOf("data:") === 0) && FileToolsOptions.CorsBehavior)
        if (typeof FileToolsOptions.CorsBehavior == "string" || FileToolsOptions.CorsBehavior instanceof String)
            e.crossOrigin = FileToolsOptions.CorsBehavior;
        else {
            var i = FileToolsOptions.CorsBehavior(a);
            i && (e.crossOrigin = i)
        }
}, LoadImage = function(a, e, i, o, s, c) {
    var d;
    s === void 0 && (s = "");
    var _, b = !1;
    a instanceof ArrayBuffer || ArrayBuffer.isView(a) ? typeof Blob != "undefined" ? (_ = URL.createObjectURL(new Blob([a],{
        type: s
    })),
    b = !0) : _ = "data:" + s + ";base64," + EncodeArrayBufferToBase64(a) : a instanceof Blob ? (_ = URL.createObjectURL(a),
    b = !0) : (_ = _CleanUrl(a),
    _ = FileToolsOptions.PreprocessUrl(a));
    var k = EngineStore.LastCreatedEngine
      , j = function(ot) {
        if (i) {
            var at = _ || a.toString();
            i("Error while trying to load image: " + (at.indexOf("http") === 0 || at.length <= 128 ? at : at.slice(0, 128) + "..."), ot)
        }
    };
    if (typeof Image == "undefined" || ((d = k == null ? void 0 : k._features.forceBitmapOverHTMLImageElement) !== null && d !== void 0 ? d : !1))
        return LoadFile(_, function(ot) {
            k.createImageBitmap(new Blob([ot],{
                type: s
            }), __assign({
                premultiplyAlpha: "none"
            }, c)).then(function(at) {
                e(at),
                b && URL.revokeObjectURL(_)
            }).catch(function(at) {
                i && i("Error while trying to load image: " + a, at)
            })
        }, void 0, o || void 0, !0, function(ot, at) {
            j(at)
        }),
        null;
    var $ = new Image;
    SetCorsBehavior(_, $);
    var _e = function() {
        $.removeEventListener("load", _e),
        $.removeEventListener("error", et),
        e($),
        b && $.src && URL.revokeObjectURL($.src)
    }
      , et = function(ot) {
        $.removeEventListener("load", _e),
        $.removeEventListener("error", et),
        j(ot),
        b && $.src && URL.revokeObjectURL($.src)
    };
    $.addEventListener("load", _e),
    $.addEventListener("error", et);
    var tt = function() {
        $.src = _
    }
      , rt = function() {
        o && o.loadImage(_, $)
    };
    if (_.substr(0, 5) !== "data:" && o && o.enableTexturesOffline)
        o.open(rt, tt);
    else {
        if (_.indexOf("file:") !== -1) {
            var it = decodeURIComponent(_.substring(5).toLowerCase());
            if (FilesInputStore.FilesToLoad[it]) {
                try {
                    var nt;
                    try {
                        nt = URL.createObjectURL(FilesInputStore.FilesToLoad[it])
                    } catch {
                        nt = URL.createObjectURL(FilesInputStore.FilesToLoad[it])
                    }
                    $.src = nt,
                    b = !0
                } catch {
                    $.src = ""
                }
                return $
            }
        }
        tt()
    }
    return $
}, ReadFile = function(a, e, i, o, s) {
    var c = new FileReader
      , d = {
        onCompleteObservable: new Observable,
        abort: function() {
            return c.abort()
        }
    };
    return c.onloadend = function(_) {
        return d.onCompleteObservable.notifyObservers(d)
    }
    ,
    s && (c.onerror = function(_) {
        s(new ReadFileError("Unable to read " + a.name,a))
    }
    ),
    c.onload = function(_) {
        e(_.target.result)
    }
    ,
    i && (c.onprogress = i),
    o ? c.readAsArrayBuffer(a) : c.readAsText(a),
    d
}, LoadFile = function(a, e, i, o, s, c, d) {
    if (a.name)
        return ReadFile(a, e, i, s, c ? function($) {
            c(void 0, $)
        }
        : void 0);
    var _ = a;
    if (_.indexOf("file:") !== -1) {
        var b = decodeURIComponent(_.substring(5).toLowerCase());
        b.indexOf("./") === 0 && (b = b.substring(2));
        var k = FilesInputStore.FilesToLoad[b];
        if (k)
            return ReadFile(k, e, i, s, c ? function($) {
                return c(void 0, new LoadFileError($.message,$.file))
            }
            : void 0)
    }
    if (IsBase64DataUrl(_)) {
        var j = {
            onCompleteObservable: new Observable,
            abort: function() {
                return function() {}
            }
        };
        try {
            e(s ? DecodeBase64UrlToBinary(_) : DecodeBase64UrlToString(_))
        } catch ($) {
            c ? c(void 0, $) : Logger$2.Error($.message || "Failed to parse the Data URL")
        }
        return TimingTools.SetImmediate(function() {
            j.onCompleteObservable.notifyObservers(j)
        }),
        j
    }
    return RequestFile(_, function($, _e) {
        e($, _e ? _e.responseURL : void 0)
    }, i, o, s, c ? function($) {
        c($.request, new LoadFileError($.message,$.request))
    }
    : void 0, d)
}, RequestFile = function(a, e, i, o, s, c, d) {
    a = _CleanUrl(a),
    a = FileToolsOptions.PreprocessUrl(a);
    var _ = FileToolsOptions.BaseUrl + a
      , b = !1
      , k = {
        onCompleteObservable: new Observable,
        abort: function() {
            return b = !0
        }
    }
      , j = function() {
        var et = new WebRequest
          , tt = null;
        k.abort = function() {
            b = !0,
            et.readyState !== (XMLHttpRequest.DONE || 4) && et.abort(),
            tt !== null && (clearTimeout(tt),
            tt = null)
        }
        ;
        var rt = function(nt) {
            var ot = nt.message || "Unknown error";
            c ? c(new RequestFileError(ot,et)) : Logger$2.Error(ot)
        }
          , it = function(nt) {
            if (et.open("GET", _),
            d)
                try {
                    d(et)
                } catch (st) {
                    rt(st);
                    return
                }
            s && (et.responseType = "arraybuffer"),
            i && et.addEventListener("progress", i);
            var ot = function() {
                et.removeEventListener("loadend", ot),
                k.onCompleteObservable.notifyObservers(k),
                k.onCompleteObservable.clear()
            };
            et.addEventListener("loadend", ot);
            var at = function() {
                if (!b && et.readyState === (XMLHttpRequest.DONE || 4)) {
                    if (et.removeEventListener("readystatechange", at),
                    et.status >= 200 && et.status < 300 || et.status === 0 && (!IsWindowObjectExist() || IsFileURL())) {
                        try {
                            e(s ? et.response : et.responseText, et)
                        } catch (lt) {
                            rt(lt)
                        }
                        return
                    }
                    var st = FileToolsOptions.DefaultRetryStrategy;
                    if (st) {
                        var ut = st(_, et, nt);
                        if (ut !== -1) {
                            et.removeEventListener("loadend", ot),
                            et = new WebRequest,
                            tt = setTimeout(function() {
                                return it(nt + 1)
                            }, ut);
                            return
                        }
                    }
                    var ct = new RequestFileError("Error status: " + et.status + " " + et.statusText + " - Unable to load " + _,et);
                    c && c(ct)
                }
            };
            et.addEventListener("readystatechange", at),
            et.send()
        };
        it(0)
    };
    if (o && o.enableSceneOffline) {
        var $ = function(et) {
            et && et.status > 400 ? c && c(et) : j()
        }
          , _e = function() {
            o && o.loadFile(FileToolsOptions.BaseUrl + a, function(et) {
                b || e(et),
                k.onCompleteObservable.notifyObservers(k)
            }, i ? function(et) {
                b || i(et)
            }
            : void 0, $, s)
        };
        o.open(_e, $)
    } else
        j();
    return k
}, IsFileURL = function() {
    return typeof location != "undefined" && location.protocol === "file:"
}, IsBase64DataUrl = function(a) {
    return base64DataUrlRegEx.test(a)
};
function DecodeBase64UrlToBinary(a) {
    return DecodeBase64ToBinary(a.split(",")[1])
}
var DecodeBase64UrlToString = function(a) {
    return DecodeBase64ToString(a.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(a) {
    a[a.Pending = 0] = "Pending",
    a[a.Fulfilled = 1] = "Fulfilled",
    a[a.Rejected = 2] = "Rejected"
}
)(PromiseStates || (PromiseStates = {}));
var FulFillmentAgregator = function() {
    function a() {
        this.count = 0,
        this.target = 0,
        this.results = []
    }
    return a
}()
  , InternalPromise = function() {
    function a(e) {
        var i = this;
        if (this._state = PromiseStates.Pending,
        this._children = new Array,
        this._rejectWasConsumed = !1,
        !!e)
            try {
                e(function(o) {
                    i._resolve(o)
                }, function(o) {
                    i._reject(o)
                })
            } catch (o) {
                this._reject(o)
            }
    }
    return Object.defineProperty(a.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
    }),
    a.prototype.catch = function(e) {
        return this.then(void 0, e)
    }
    ,
    a.prototype.then = function(e, i) {
        var o = this
          , s = new a;
        return s._onFulfilled = e,
        s._onRejected = i,
        this._children.push(s),
        s._parent = this,
        this._state !== PromiseStates.Pending && setTimeout(function() {
            o._state === PromiseStates.Fulfilled || o._rejectWasConsumed ? s._resolve(o._result) : s._reject(o._reason)
        }),
        s
    }
    ,
    a.prototype._moveChildren = function(e) {
        var i, o = this;
        if ((i = this._children).push.apply(i, e.splice(0, e.length)),
        this._children.forEach(function(k) {
            k._parent = o
        }),
        this._state === PromiseStates.Fulfilled)
            for (var s = 0, c = this._children; s < c.length; s++) {
                var d = c[s];
                d._resolve(this._result)
            }
        else if (this._state === PromiseStates.Rejected)
            for (var _ = 0, b = this._children; _ < b.length; _++) {
                var d = b[_];
                d._reject(this._reason)
            }
    }
    ,
    a.prototype._resolve = function(e) {
        try {
            this._state = PromiseStates.Fulfilled;
            var i = null;
            if (this._onFulfilled && (i = this._onFulfilled(e)),
            i != null)
                if (i._state !== void 0) {
                    var o = i;
                    o._parent = this,
                    o._moveChildren(this._children),
                    e = o._result
                } else
                    e = i;
            this._result = e;
            for (var s = 0, c = this._children; s < c.length; s++) {
                var d = c[s];
                d._resolve(e)
            }
            this._children.length = 0,
            delete this._onFulfilled,
            delete this._onRejected
        } catch (_) {
            this._reject(_, !0)
        }
    }
    ,
    a.prototype._reject = function(e, i) {
        if (i === void 0 && (i = !1),
        this._state = PromiseStates.Rejected,
        this._reason = e,
        this._onRejected && !i)
            try {
                this._onRejected(e),
                this._rejectWasConsumed = !0
            } catch (d) {
                e = d
            }
        for (var o = 0, s = this._children; o < s.length; o++) {
            var c = s[o];
            this._rejectWasConsumed ? c._resolve(null) : c._reject(e)
        }
        this._children.length = 0,
        delete this._onFulfilled,
        delete this._onRejected
    }
    ,
    a.resolve = function(e) {
        var i = new a;
        return i._resolve(e),
        i
    }
    ,
    a._RegisterForFulfillment = function(e, i, o) {
        e.then(function(s) {
            return i.results[o] = s,
            i.count++,
            i.count === i.target && i.rootPromise._resolve(i.results),
            null
        }, function(s) {
            i.rootPromise._state !== PromiseStates.Rejected && i.rootPromise._reject(s)
        })
    }
    ,
    a.all = function(e) {
        var i = new a
          , o = new FulFillmentAgregator;
        if (o.target = e.length,
        o.rootPromise = i,
        e.length)
            for (var s = 0; s < e.length; s++)
                a._RegisterForFulfillment(e[s], o, s);
        else
            i._resolve([]);
        return i
    }
    ,
    a.race = function(e) {
        var i = new a;
        if (e.length)
            for (var o = 0, s = e; o < s.length; o++) {
                var c = s[o];
                c.then(function(d) {
                    return i && (i._resolve(d),
                    i = null),
                    null
                }, function(d) {
                    i && (i._reject(d),
                    i = null)
                })
            }
        return i
    }
    ,
    a
}()
  , PromisePolyfill = function() {
    function a() {}
    return a.Apply = function(e) {
        if (e === void 0 && (e = !1),
        e || typeof Promise == "undefined") {
            var i = window;
            i.Promise = InternalPromise
        }
    }
    ,
    a
}()
  , _RegisteredTypes = {};
function RegisterClass(a, e) {
    _RegisteredTypes[a] = e
}
function GetClass(a) {
    return _RegisteredTypes[a]
}
var InstantiationTools = function() {
    function a() {}
    return a.Instantiate = function(e) {
        if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[e])
            return this.RegisteredExternalClasses[e];
        var i = GetClass(e);
        if (i)
            return i;
        Logger$2.Warn(e + " not found, you may have missed an import.");
        for (var o = e.split("."), s = window || this, c = 0, d = o.length; c < d; c++)
            s = s[o[c]];
        return typeof s != "function" ? null : s
    }
    ,
    a.RegisteredExternalClasses = {},
    a
}();
function RandomGUID() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(a) {
        var e = Math.random() * 16 | 0
          , i = a === "x" ? e : e & 3 | 8;
        return i.toString(16)
    })
}
var SliceTools = function() {
    function a() {}
    return a.Slice = function(e, i, o) {
        return e.slice ? e.slice(i, o) : Array.prototype.slice.call(e, i, o)
    }
    ,
    a.SliceToArray = function(e, i, o) {
        return Array.isArray(e) ? e.slice(i, o) : Array.prototype.slice.call(e, i, o)
    }
    ,
    a
}()
  , Tools = function() {
    function a() {}
    return Object.defineProperty(a, "BaseUrl", {
        get: function() {
            return FileToolsOptions.BaseUrl
        },
        set: function(e) {
            FileToolsOptions.BaseUrl = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "DefaultRetryStrategy", {
        get: function() {
            return FileToolsOptions.DefaultRetryStrategy
        },
        set: function(e) {
            FileToolsOptions.DefaultRetryStrategy = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "CorsBehavior", {
        get: function() {
            return FileToolsOptions.CorsBehavior
        },
        set: function(e) {
            FileToolsOptions.CorsBehavior = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "UseFallbackTexture", {
        get: function() {
            return EngineStore.UseFallbackTexture
        },
        set: function(e) {
            EngineStore.UseFallbackTexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "RegisteredExternalClasses", {
        get: function() {
            return InstantiationTools.RegisteredExternalClasses
        },
        set: function(e) {
            InstantiationTools.RegisteredExternalClasses = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "fallbackTexture", {
        get: function() {
            return EngineStore.FallbackTexture
        },
        set: function(e) {
            EngineStore.FallbackTexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.FetchToRef = function(e, i, o, s, c, d) {
        var _ = Math.abs(e) * o % o | 0
          , b = Math.abs(i) * s % s | 0
          , k = (_ + b * o) * 4;
        d.r = c[k] / 255,
        d.g = c[k + 1] / 255,
        d.b = c[k + 2] / 255,
        d.a = c[k + 3] / 255
    }
    ,
    a.Mix = function(e, i, o) {
        return e * (1 - o) + i * o
    }
    ,
    a.Instantiate = function(e) {
        return InstantiationTools.Instantiate(e)
    }
    ,
    a.Slice = function(e, i, o) {
        return SliceTools.Slice(e, i, o)
    }
    ,
    a.SliceToArray = function(e, i, o) {
        return SliceTools.SliceToArray(e, i, o)
    }
    ,
    a.SetImmediate = function(e) {
        TimingTools.SetImmediate(e)
    }
    ,
    a.IsExponentOfTwo = function(e) {
        var i = 1;
        do
            i *= 2;
        while (i < e);
        return i === e
    }
    ,
    a.FloatRound = function(e) {
        return Math.fround ? Math.fround(e) : (a._tmpFloatArray[0] = e,
        a._tmpFloatArray[0])
    }
    ,
    a.GetFilename = function(e) {
        var i = e.lastIndexOf("/");
        return i < 0 ? e : e.substring(i + 1)
    }
    ,
    a.GetFolderPath = function(e, i) {
        i === void 0 && (i = !1);
        var o = e.lastIndexOf("/");
        return o < 0 ? i ? e : "" : e.substring(0, o + 1)
    }
    ,
    a.ToDegrees = function(e) {
        return e * 180 / Math.PI
    }
    ,
    a.ToRadians = function(e) {
        return e * Math.PI / 180
    }
    ,
    a.MakeArray = function(e, i) {
        return i !== !0 && (e === void 0 || e == null) ? null : Array.isArray(e) ? e : [e]
    }
    ,
    a.GetPointerPrefix = function(e) {
        var i = "pointer";
        return IsWindowObjectExist() && !window.PointerEvent && IsNavigatorAvailable() && !navigator.pointerEnabled && (i = "mouse"),
        e._badDesktopOS && !e._badOS && !(document && "ontouchend"in document) && (i = "mouse"),
        i
    }
    ,
    a.SetCorsBehavior = function(e, i) {
        SetCorsBehavior(e, i)
    }
    ,
    a.CleanUrl = function(e) {
        return e = e.replace(/#/gm, "%23"),
        e
    }
    ,
    Object.defineProperty(a, "PreprocessUrl", {
        get: function() {
            return FileToolsOptions.PreprocessUrl
        },
        set: function(e) {
            FileToolsOptions.PreprocessUrl = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.LoadImage = function(e, i, o, s, c, d) {
        return LoadImage(e, i, o, s, c, d)
    }
    ,
    a.LoadFile = function(e, i, o, s, c, d) {
        return LoadFile(e, i, o, s, c, d)
    }
    ,
    a.LoadFileAsync = function(e, i) {
        return i === void 0 && (i = !0),
        new Promise(function(o, s) {
            LoadFile(e, function(c) {
                o(c)
            }, void 0, void 0, i, function(c, d) {
                s(d)
            })
        }
        )
    }
    ,
    a.LoadScript = function(e, i, o, s) {
        if (!!IsWindowObjectExist()) {
            var c = document.getElementsByTagName("head")[0]
              , d = document.createElement("script");
            d.setAttribute("type", "text/javascript"),
            d.setAttribute("src", e),
            s && (d.id = s),
            d.onload = function() {
                i && i()
            }
            ,
            d.onerror = function(_) {
                o && o("Unable to load script '" + e + "'", _)
            }
            ,
            c.appendChild(d)
        }
    }
    ,
    a.LoadScriptAsync = function(e, i) {
        var o = this;
        return new Promise(function(s, c) {
            o.LoadScript(e, function() {
                s()
            }, function(d, _) {
                c(_)
            })
        }
        )
    }
    ,
    a.ReadFileAsDataURL = function(e, i, o) {
        var s = new FileReader
          , c = {
            onCompleteObservable: new Observable,
            abort: function() {
                return s.abort()
            }
        };
        return s.onloadend = function(d) {
            c.onCompleteObservable.notifyObservers(c)
        }
        ,
        s.onload = function(d) {
            i(d.target.result)
        }
        ,
        s.onprogress = o,
        s.readAsDataURL(e),
        c
    }
    ,
    a.ReadFile = function(e, i, o, s, c) {
        return ReadFile(e, i, o, s, c)
    }
    ,
    a.FileAsURL = function(e) {
        var i = new Blob([e])
          , o = window.URL || window.webkitURL
          , s = o.createObjectURL(i);
        return s
    }
    ,
    a.Format = function(e, i) {
        return i === void 0 && (i = 2),
        e.toFixed(i)
    }
    ,
    a.DeepCopy = function(e, i, o, s) {
        DeepCopier.DeepCopy(e, i, o, s)
    }
    ,
    a.IsEmpty = function(e) {
        for (var i in e)
            if (e.hasOwnProperty(i))
                return !1;
        return !0
    }
    ,
    a.RegisterTopRootEvents = function(e, i) {
        for (var o = 0; o < i.length; o++) {
            var s = i[o];
            e.addEventListener(s.name, s.handler, !1);
            try {
                window.parent && window.parent.addEventListener(s.name, s.handler, !1)
            } catch {}
        }
    }
    ,
    a.UnregisterTopRootEvents = function(e, i) {
        for (var o = 0; o < i.length; o++) {
            var s = i[o];
            e.removeEventListener(s.name, s.handler);
            try {
                e.parent && e.parent.removeEventListener(s.name, s.handler)
            } catch {}
        }
    }
    ,
    a.DumpFramebuffer = function(e, i, o, s, c, d) {
        return c === void 0 && (c = "image/png"),
        __awaiter(this, void 0, void 0, function() {
            var _, b;
            return __generator(this, function(k) {
                switch (k.label) {
                case 0:
                    return [4, o.readPixels(0, 0, e, i)];
                case 1:
                    return _ = k.sent(),
                    b = new Uint8Array(_.buffer),
                    a.DumpData(e, i, b, s, c, d, !0),
                    [2]
                }
            })
        })
    }
    ,
    a.DumpData = function(e, i, o, s, c, d, _, b, k) {
        c === void 0 && (c = "image/png"),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = !1),
        a._ScreenshotCanvas || (a._ScreenshotCanvas = document.createElement("canvas")),
        a._ScreenshotCanvas.width = e,
        a._ScreenshotCanvas.height = i;
        var j = a._ScreenshotCanvas.getContext("2d");
        if (j) {
            if (o instanceof Float32Array) {
                for (var $ = new Uint8Array(o.length), _e = o.length; _e--; ) {
                    var et = o[_e];
                    $[_e] = et < 0 ? 0 : et > 1 ? 1 : Math.round(et * 255)
                }
                o = $
            }
            var tt = j.createImageData(e, i)
              , rt = tt.data;
            rt.set(o),
            j.putImageData(tt, 0, 0);
            var it = a._ScreenshotCanvas;
            if (_) {
                var nt = document.createElement("canvas");
                nt.width = e,
                nt.height = i;
                var ot = nt.getContext("2d");
                if (!ot)
                    return;
                ot.translate(0, i),
                ot.scale(1, -1),
                ot.drawImage(a._ScreenshotCanvas, 0, 0),
                it = nt
            }
            b ? a.ToBlob(it, function(at) {
                var st = new FileReader;
                st.onload = function(ut) {
                    var ct = ut.target.result;
                    s && s(ct)
                }
                ,
                st.readAsArrayBuffer(at)
            }, c, k) : a.EncodeScreenshotCanvasData(s, c, d, it, k)
        }
    }
    ,
    a.DumpDataAsync = function(e, i, o, s, c, d, _, b) {
        return s === void 0 && (s = "image/png"),
        d === void 0 && (d = !1),
        _ === void 0 && (_ = !1),
        new Promise(function(k) {
            a.DumpData(e, i, o, function(j) {
                return k(j)
            }, s, c, d, _, b)
        }
        )
    }
    ,
    a.ToBlob = function(e, i, o, s) {
        o === void 0 && (o = "image/png"),
        e.toBlob || (e.toBlob = function(c, d, _) {
            var b = this;
            setTimeout(function() {
                for (var k = atob(b.toDataURL(d, _).split(",")[1]), j = k.length, $ = new Uint8Array(j), _e = 0; _e < j; _e++)
                    $[_e] = k.charCodeAt(_e);
                c(new Blob([$]))
            })
        }
        ),
        e.toBlob(function(c) {
            i(c)
        }, o, s)
    }
    ,
    a.EncodeScreenshotCanvasData = function(e, i, o, s, c) {
        if (i === void 0 && (i = "image/png"),
        e) {
            var d = (s != null ? s : a._ScreenshotCanvas).toDataURL(i, c);
            e(d)
        } else
            this.ToBlob(s != null ? s : a._ScreenshotCanvas, function(_) {
                if ("download"in document.createElement("a")) {
                    if (!o) {
                        var b = new Date
                          , k = (b.getFullYear() + "-" + (b.getMonth() + 1)).slice(2) + "-" + b.getDate() + "_" + b.getHours() + "-" + ("0" + b.getMinutes()).slice(-2);
                        o = "screenshot_" + k + ".png"
                    }
                    a.Download(_, o)
                } else {
                    var j = URL.createObjectURL(_)
                      , $ = window.open("");
                    if (!$)
                        return;
                    var _e = $.document.createElement("img");
                    _e.onload = function() {
                        URL.revokeObjectURL(j)
                    }
                    ,
                    _e.src = j,
                    $.document.body.appendChild(_e)
                }
            }, i, c)
    }
    ,
    a.Download = function(e, i) {
        if (navigator && navigator.msSaveBlob) {
            navigator.msSaveBlob(e, i);
            return
        }
        var o = window.URL.createObjectURL(e)
          , s = document.createElement("a");
        document.body.appendChild(s),
        s.style.display = "none",
        s.href = o,
        s.download = i,
        s.addEventListener("click", function() {
            s.parentElement && s.parentElement.removeChild(s)
        }),
        s.click(),
        window.URL.revokeObjectURL(o)
    }
    ,
    a.BackCompatCameraNoPreventDefault = function(e) {
        return typeof e[0] == "boolean" ? e[0] : typeof e[1] == "boolean" ? e[1] : !1
    }
    ,
    a.CreateScreenshot = function(e, i, o, s, c) {
        throw _WarnImport("ScreenshotTools")
    }
    ,
    a.CreateScreenshotAsync = function(e, i, o, s) {
        throw _WarnImport("ScreenshotTools")
    }
    ,
    a.CreateScreenshotUsingRenderTarget = function(e, i, o, s, c, d, _, b) {
        throw _WarnImport("ScreenshotTools")
    }
    ,
    a.CreateScreenshotUsingRenderTargetAsync = function(e, i, o, s, c, d, _) {
        throw _WarnImport("ScreenshotTools")
    }
    ,
    a.RandomId = function() {
        return RandomGUID()
    }
    ,
    a.IsBase64 = function(e) {
        return IsBase64DataUrl(e)
    }
    ,
    a.DecodeBase64 = function(e) {
        return DecodeBase64UrlToBinary(e)
    }
    ,
    Object.defineProperty(a, "errorsCount", {
        get: function() {
            return Logger$2.errorsCount
        },
        enumerable: !1,
        configurable: !0
    }),
    a.Log = function(e) {
        Logger$2.Log(e)
    }
    ,
    a.Warn = function(e) {
        Logger$2.Warn(e)
    }
    ,
    a.Error = function(e) {
        Logger$2.Error(e)
    }
    ,
    Object.defineProperty(a, "LogCache", {
        get: function() {
            return Logger$2.LogCache
        },
        enumerable: !1,
        configurable: !0
    }),
    a.ClearLogCache = function() {
        Logger$2.ClearLogCache()
    }
    ,
    Object.defineProperty(a, "LogLevels", {
        set: function(e) {
            Logger$2.LogLevels = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "PerformanceLogLevel", {
        set: function(e) {
            if ((e & a.PerformanceUserMarkLogLevel) === a.PerformanceUserMarkLogLevel) {
                a.StartPerformanceCounter = a._StartUserMark,
                a.EndPerformanceCounter = a._EndUserMark;
                return
            }
            if ((e & a.PerformanceConsoleLogLevel) === a.PerformanceConsoleLogLevel) {
                a.StartPerformanceCounter = a._StartPerformanceConsole,
                a.EndPerformanceCounter = a._EndPerformanceConsole;
                return
            }
            a.StartPerformanceCounter = a._StartPerformanceCounterDisabled,
            a.EndPerformanceCounter = a._EndPerformanceCounterDisabled
        },
        enumerable: !1,
        configurable: !0
    }),
    a._StartPerformanceCounterDisabled = function(e, i) {}
    ,
    a._EndPerformanceCounterDisabled = function(e, i) {}
    ,
    a._StartUserMark = function(e, i) {
        if (i === void 0 && (i = !0),
        !a._performance) {
            if (!IsWindowObjectExist())
                return;
            a._performance = window.performance
        }
        !i || !a._performance.mark || a._performance.mark(e + "-Begin")
    }
    ,
    a._EndUserMark = function(e, i) {
        i === void 0 && (i = !0),
        !(!i || !a._performance.mark) && (a._performance.mark(e + "-End"),
        a._performance.measure(e, e + "-Begin", e + "-End"))
    }
    ,
    a._StartPerformanceConsole = function(e, i) {
        i === void 0 && (i = !0),
        i && (a._StartUserMark(e, i),
        console.time && console.time(e))
    }
    ,
    a._EndPerformanceConsole = function(e, i) {
        i === void 0 && (i = !0),
        i && (a._EndUserMark(e, i),
        console.timeEnd(e))
    }
    ,
    Object.defineProperty(a, "Now", {
        get: function() {
            return PrecisionDate.Now
        },
        enumerable: !1,
        configurable: !0
    }),
    a.GetClassName = function(e, i) {
        i === void 0 && (i = !1);
        var o = null;
        if (!i && e.getClassName)
            o = e.getClassName();
        else {
            if (e instanceof Object) {
                var s = i ? e : Object.getPrototypeOf(e);
                o = s.constructor.__bjsclassName__
            }
            o || (o = typeof e)
        }
        return o
    }
    ,
    a.First = function(e, i) {
        for (var o = 0, s = e; o < s.length; o++) {
            var c = s[o];
            if (i(c))
                return c
        }
        return null
    }
    ,
    a.getFullClassName = function(e, i) {
        i === void 0 && (i = !1);
        var o = null
          , s = null;
        if (!i && e.getClassName)
            o = e.getClassName();
        else {
            if (e instanceof Object) {
                var c = i ? e : Object.getPrototypeOf(e);
                o = c.constructor.__bjsclassName__,
                s = c.constructor.__bjsmoduleName__
            }
            o || (o = typeof e)
        }
        return o ? (s != null ? s + "." : "") + o : null
    }
    ,
    a.DelayAsync = function(e) {
        return new Promise(function(i) {
            setTimeout(function() {
                i()
            }, e)
        }
        )
    }
    ,
    a.IsSafari = function() {
        return IsNavigatorAvailable() ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : !1
    }
    ,
    a.UseCustomRequestHeaders = !1,
    a.CustomRequestHeaders = WebRequest.CustomRequestHeaders,
    a._tmpFloatArray = new Float32Array(1),
    a.GetDOMTextContent = GetDOMTextContent,
    a.GetAbsoluteUrl = typeof document == "object" ? function(e) {
        var i = document.createElement("a");
        return i.href = e,
        i.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.")
    }
    ,
    a.NoneLogLevel = Logger$2.NoneLogLevel,
    a.MessageLogLevel = Logger$2.MessageLogLevel,
    a.WarningLogLevel = Logger$2.WarningLogLevel,
    a.ErrorLogLevel = Logger$2.ErrorLogLevel,
    a.AllLogLevel = Logger$2.AllLogLevel,
    a.IsWindowObjectExist = IsWindowObjectExist,
    a.PerformanceNoneLogLevel = 0,
    a.PerformanceUserMarkLogLevel = 1,
    a.PerformanceConsoleLogLevel = 2,
    a.StartPerformanceCounter = a._StartPerformanceCounterDisabled,
    a.EndPerformanceCounter = a._EndPerformanceCounterDisabled,
    a
}()
  , AsyncLoop = function() {
    function a(e, i, o, s) {
        s === void 0 && (s = 0),
        this.iterations = e,
        this.index = s - 1,
        this._done = !1,
        this._fn = i,
        this._successCallback = o
    }
    return a.prototype.executeNext = function() {
        this._done || (this.index + 1 < this.iterations ? (++this.index,
        this._fn(this)) : this.breakLoop())
    }
    ,
    a.prototype.breakLoop = function() {
        this._done = !0,
        this._successCallback()
    }
    ,
    a.Run = function(e, i, o, s) {
        s === void 0 && (s = 0);
        var c = new a(e,i,o,s);
        return c.executeNext(),
        c
    }
    ,
    a.SyncAsyncForLoop = function(e, i, o, s, c, d) {
        return d === void 0 && (d = 0),
        a.Run(Math.ceil(e / i), function(_) {
            c && c() ? _.breakLoop() : setTimeout(function() {
                for (var b = 0; b < i; ++b) {
                    var k = _.index * i + b;
                    if (k >= e)
                        break;
                    if (o(k),
                    c && c()) {
                        _.breakLoop();
                        break
                    }
                }
                _.executeNext()
            }, d)
        }, s)
    }
    ,
    a
}();
EngineStore.FallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
PromisePolyfill.Apply();
var Scalar = function() {
    function a() {}
    return a.WithinEpsilon = function(e, i, o) {
        return o === void 0 && (o = 1401298e-51),
        Math.abs(e - i) <= o
    }
    ,
    a.ToHex = function(e) {
        var i = e.toString(16);
        return e <= 15 ? ("0" + i).toUpperCase() : i.toUpperCase()
    }
    ,
    a.Sign = function(e) {
        return e = +e,
        e === 0 || isNaN(e) ? e : e > 0 ? 1 : -1
    }
    ,
    a.Clamp = function(e, i, o) {
        return i === void 0 && (i = 0),
        o === void 0 && (o = 1),
        Math.min(o, Math.max(i, e))
    }
    ,
    a.Log2 = function(e) {
        return Math.log(e) * Math.LOG2E
    }
    ,
    a.ILog2 = function(e) {
        if (Math.log2)
            return Math.floor(Math.log2(e));
        if (e < 0)
            return NaN;
        if (e === 0)
            return -1 / 0;
        var i = 0;
        if (e < 1) {
            for (; e < 1; )
                i++,
                e = e * 2;
            i = -i
        } else if (e > 1)
            for (; e > 1; )
                i++,
                e = Math.floor(e / 2);
        return i
    }
    ,
    a.Repeat = function(e, i) {
        return e - Math.floor(e / i) * i
    }
    ,
    a.Normalize = function(e, i, o) {
        return (e - i) / (o - i)
    }
    ,
    a.Denormalize = function(e, i, o) {
        return e * (o - i) + i
    }
    ,
    a.DeltaAngle = function(e, i) {
        var o = a.Repeat(i - e, 360);
        return o > 180 && (o -= 360),
        o
    }
    ,
    a.PingPong = function(e, i) {
        var o = a.Repeat(e, i * 2);
        return i - Math.abs(o - i)
    }
    ,
    a.SmoothStep = function(e, i, o) {
        var s = a.Clamp(o);
        return s = -2 * s * s * s + 3 * s * s,
        i * s + e * (1 - s)
    }
    ,
    a.MoveTowards = function(e, i, o) {
        var s = 0;
        return Math.abs(i - e) <= o ? s = i : s = e + a.Sign(i - e) * o,
        s
    }
    ,
    a.MoveTowardsAngle = function(e, i, o) {
        var s = a.DeltaAngle(e, i)
          , c = 0;
        return -o < s && s < o ? c = i : (i = e + s,
        c = a.MoveTowards(e, i, o)),
        c
    }
    ,
    a.Lerp = function(e, i, o) {
        return e + (i - e) * o
    }
    ,
    a.LerpAngle = function(e, i, o) {
        var s = a.Repeat(i - e, 360);
        return s > 180 && (s -= 360),
        e + s * a.Clamp(o)
    }
    ,
    a.InverseLerp = function(e, i, o) {
        var s = 0;
        return e != i ? s = a.Clamp((o - e) / (i - e)) : s = 0,
        s
    }
    ,
    a.Hermite = function(e, i, o, s, c) {
        var d = c * c
          , _ = c * d
          , b = 2 * _ - 3 * d + 1
          , k = -2 * _ + 3 * d
          , j = _ - 2 * d + c
          , $ = _ - d;
        return e * b + o * k + i * j + s * $
    }
    ,
    a.Hermite1stDerivative = function(e, i, o, s, c) {
        var d = c * c;
        return (d - c) * 6 * e + (3 * d - 4 * c + 1) * i + (-d + c) * 6 * o + (3 * d - 2 * c) * s
    }
    ,
    a.RandomRange = function(e, i) {
        return e === i ? e : Math.random() * (i - e) + e
    }
    ,
    a.RangeToPercent = function(e, i, o) {
        return (e - i) / (o - i)
    }
    ,
    a.PercentToRange = function(e, i, o) {
        return (o - i) * e + i
    }
    ,
    a.NormalizeRadians = function(e) {
        return e -= a.TwoPi * Math.floor((e + Math.PI) / a.TwoPi),
        e
    }
    ,
    a.HCF = function(e, i) {
        var o = e % i;
        return o === 0 ? i : a.HCF(i, o)
    }
    ,
    a.TwoPi = Math.PI * 2,
    a
}()
  , ToGammaSpace = 1 / 2.2
  , ToLinearSpace = 2.2
  , PHI = (1 + Math.sqrt(5)) / 2
  , Epsilon = .001
  , ArrayTools = function() {
    function a() {}
    return a.BuildArray = function(e, i) {
        for (var o = [], s = 0; s < e; ++s)
            o.push(i());
        return o
    }
    ,
    a.BuildTuple = function(e, i) {
        return a.BuildArray(e, i)
    }
    ,
    a
}()
  , Vector2 = function() {
    function a(e, i) {
        e === void 0 && (e = 0),
        i === void 0 && (i = 0),
        this.x = e,
        this.y = i
    }
    return a.prototype.toString = function() {
        return "{X: " + this.x + " Y: " + this.y + "}"
    }
    ,
    a.prototype.getClassName = function() {
        return "Vector2"
    }
    ,
    a.prototype.getHashCode = function() {
        var e = this.x | 0;
        return e = e * 397 ^ (this.y | 0),
        e
    }
    ,
    a.prototype.toArray = function(e, i) {
        return i === void 0 && (i = 0),
        e[i] = this.x,
        e[i + 1] = this.y,
        this
    }
    ,
    a.prototype.fromArray = function(e, i) {
        return i === void 0 && (i = 0),
        a.FromArrayToRef(e, i, this),
        this
    }
    ,
    a.prototype.asArray = function() {
        var e = new Array;
        return this.toArray(e, 0),
        e
    }
    ,
    a.prototype.copyFrom = function(e) {
        return this.x = e.x,
        this.y = e.y,
        this
    }
    ,
    a.prototype.copyFromFloats = function(e, i) {
        return this.x = e,
        this.y = i,
        this
    }
    ,
    a.prototype.set = function(e, i) {
        return this.copyFromFloats(e, i)
    }
    ,
    a.prototype.add = function(e) {
        return new a(this.x + e.x,this.y + e.y)
    }
    ,
    a.prototype.addToRef = function(e, i) {
        return i.x = this.x + e.x,
        i.y = this.y + e.y,
        this
    }
    ,
    a.prototype.addInPlace = function(e) {
        return this.x += e.x,
        this.y += e.y,
        this
    }
    ,
    a.prototype.addVector3 = function(e) {
        return new a(this.x + e.x,this.y + e.y)
    }
    ,
    a.prototype.subtract = function(e) {
        return new a(this.x - e.x,this.y - e.y)
    }
    ,
    a.prototype.subtractToRef = function(e, i) {
        return i.x = this.x - e.x,
        i.y = this.y - e.y,
        this
    }
    ,
    a.prototype.subtractInPlace = function(e) {
        return this.x -= e.x,
        this.y -= e.y,
        this
    }
    ,
    a.prototype.multiplyInPlace = function(e) {
        return this.x *= e.x,
        this.y *= e.y,
        this
    }
    ,
    a.prototype.multiply = function(e) {
        return new a(this.x * e.x,this.y * e.y)
    }
    ,
    a.prototype.multiplyToRef = function(e, i) {
        return i.x = this.x * e.x,
        i.y = this.y * e.y,
        this
    }
    ,
    a.prototype.multiplyByFloats = function(e, i) {
        return new a(this.x * e,this.y * i)
    }
    ,
    a.prototype.divide = function(e) {
        return new a(this.x / e.x,this.y / e.y)
    }
    ,
    a.prototype.divideToRef = function(e, i) {
        return i.x = this.x / e.x,
        i.y = this.y / e.y,
        this
    }
    ,
    a.prototype.divideInPlace = function(e) {
        return this.divideToRef(e, this)
    }
    ,
    a.prototype.negate = function() {
        return new a(-this.x,-this.y)
    }
    ,
    a.prototype.negateInPlace = function() {
        return this.x *= -1,
        this.y *= -1,
        this
    }
    ,
    a.prototype.negateToRef = function(e) {
        return e.copyFromFloats(this.x * -1, this.y * -1)
    }
    ,
    a.prototype.scaleInPlace = function(e) {
        return this.x *= e,
        this.y *= e,
        this
    }
    ,
    a.prototype.scale = function(e) {
        var i = new a(0,0);
        return this.scaleToRef(e, i),
        i
    }
    ,
    a.prototype.scaleToRef = function(e, i) {
        return i.x = this.x * e,
        i.y = this.y * e,
        this
    }
    ,
    a.prototype.scaleAndAddToRef = function(e, i) {
        return i.x += this.x * e,
        i.y += this.y * e,
        this
    }
    ,
    a.prototype.equals = function(e) {
        return e && this.x === e.x && this.y === e.y
    }
    ,
    a.prototype.equalsWithEpsilon = function(e, i) {
        return i === void 0 && (i = Epsilon),
        e && Scalar.WithinEpsilon(this.x, e.x, i) && Scalar.WithinEpsilon(this.y, e.y, i)
    }
    ,
    a.prototype.floor = function() {
        return new a(Math.floor(this.x),Math.floor(this.y))
    }
    ,
    a.prototype.fract = function() {
        return new a(this.x - Math.floor(this.x),this.y - Math.floor(this.y))
    }
    ,
    a.prototype.rotateToRef = function(e, i) {
        var o = Math.cos(e)
          , s = Math.sin(e);
        return i.x = o * this.x - s * this.y,
        i.y = s * this.x + o * this.y,
        this
    }
    ,
    a.prototype.length = function() {
        return Math.sqrt(this.x * this.x + this.y * this.y)
    }
    ,
    a.prototype.lengthSquared = function() {
        return this.x * this.x + this.y * this.y
    }
    ,
    a.prototype.normalize = function() {
        return a.NormalizeToRef(this, this),
        this
    }
    ,
    a.prototype.clone = function() {
        return new a(this.x,this.y)
    }
    ,
    a.Zero = function() {
        return new a(0,0)
    }
    ,
    a.One = function() {
        return new a(1,1)
    }
    ,
    a.FromArray = function(e, i) {
        return i === void 0 && (i = 0),
        new a(e[i],e[i + 1])
    }
    ,
    a.FromArrayToRef = function(e, i, o) {
        o.x = e[i],
        o.y = e[i + 1]
    }
    ,
    a.CatmullRom = function(e, i, o, s, c) {
        var d = c * c
          , _ = c * d
          , b = .5 * (2 * i.x + (-e.x + o.x) * c + (2 * e.x - 5 * i.x + 4 * o.x - s.x) * d + (-e.x + 3 * i.x - 3 * o.x + s.x) * _)
          , k = .5 * (2 * i.y + (-e.y + o.y) * c + (2 * e.y - 5 * i.y + 4 * o.y - s.y) * d + (-e.y + 3 * i.y - 3 * o.y + s.y) * _);
        return new a(b,k)
    }
    ,
    a.Clamp = function(e, i, o) {
        var s = e.x;
        s = s > o.x ? o.x : s,
        s = s < i.x ? i.x : s;
        var c = e.y;
        return c = c > o.y ? o.y : c,
        c = c < i.y ? i.y : c,
        new a(s,c)
    }
    ,
    a.Hermite = function(e, i, o, s, c) {
        var d = c * c
          , _ = c * d
          , b = 2 * _ - 3 * d + 1
          , k = -2 * _ + 3 * d
          , j = _ - 2 * d + c
          , $ = _ - d
          , _e = e.x * b + o.x * k + i.x * j + s.x * $
          , et = e.y * b + o.y * k + i.y * j + s.y * $;
        return new a(_e,et)
    }
    ,
    a.Hermite1stDerivative = function(e, i, o, s, c) {
        var d = a.Zero();
        return this.Hermite1stDerivativeToRef(e, i, o, s, c, d),
        d
    }
    ,
    a.Hermite1stDerivativeToRef = function(e, i, o, s, c, d) {
        var _ = c * c;
        d.x = (_ - c) * 6 * e.x + (3 * _ - 4 * c + 1) * i.x + (-_ + c) * 6 * o.x + (3 * _ - 2 * c) * s.x,
        d.y = (_ - c) * 6 * e.y + (3 * _ - 4 * c + 1) * i.y + (-_ + c) * 6 * o.y + (3 * _ - 2 * c) * s.y
    }
    ,
    a.Lerp = function(e, i, o) {
        var s = e.x + (i.x - e.x) * o
          , c = e.y + (i.y - e.y) * o;
        return new a(s,c)
    }
    ,
    a.Dot = function(e, i) {
        return e.x * i.x + e.y * i.y
    }
    ,
    a.Normalize = function(e) {
        var i = a.Zero();
        return this.NormalizeToRef(e, i),
        i
    }
    ,
    a.NormalizeToRef = function(e, i) {
        var o = e.length();
        o !== 0 && (i.x = e.x / o,
        i.y = e.y / o)
    }
    ,
    a.Minimize = function(e, i) {
        var o = e.x < i.x ? e.x : i.x
          , s = e.y < i.y ? e.y : i.y;
        return new a(o,s)
    }
    ,
    a.Maximize = function(e, i) {
        var o = e.x > i.x ? e.x : i.x
          , s = e.y > i.y ? e.y : i.y;
        return new a(o,s)
    }
    ,
    a.Transform = function(e, i) {
        var o = a.Zero();
        return a.TransformToRef(e, i, o),
        o
    }
    ,
    a.TransformToRef = function(e, i, o) {
        var s = i.m
          , c = e.x * s[0] + e.y * s[4] + s[12]
          , d = e.x * s[1] + e.y * s[5] + s[13];
        o.x = c,
        o.y = d
    }
    ,
    a.PointInTriangle = function(e, i, o, s) {
        var c = .5 * (-o.y * s.x + i.y * (-o.x + s.x) + i.x * (o.y - s.y) + o.x * s.y)
          , d = c < 0 ? -1 : 1
          , _ = (i.y * s.x - i.x * s.y + (s.y - i.y) * e.x + (i.x - s.x) * e.y) * d
          , b = (i.x * o.y - i.y * o.x + (i.y - o.y) * e.x + (o.x - i.x) * e.y) * d;
        return _ > 0 && b > 0 && _ + b < 2 * c * d
    }
    ,
    a.Distance = function(e, i) {
        return Math.sqrt(a.DistanceSquared(e, i))
    }
    ,
    a.DistanceSquared = function(e, i) {
        var o = e.x - i.x
          , s = e.y - i.y;
        return o * o + s * s
    }
    ,
    a.Center = function(e, i) {
        return a.CenterToRef(e, i, a.Zero())
    }
    ,
    a.CenterToRef = function(e, i, o) {
        return o.copyFromFloats((e.x + i.x) / 2, (e.y + i.y) / 2)
    }
    ,
    a.DistanceOfPointFromSegment = function(e, i, o) {
        var s = a.DistanceSquared(i, o);
        if (s === 0)
            return a.Distance(e, i);
        var c = o.subtract(i)
          , d = Math.max(0, Math.min(1, a.Dot(e.subtract(i), c) / s))
          , _ = i.add(c.multiplyByFloats(d, d));
        return a.Distance(e, _)
    }
    ,
    a
}()
  , Vector3 = function() {
    function a(e, i, o) {
        e === void 0 && (e = 0),
        i === void 0 && (i = 0),
        o === void 0 && (o = 0),
        this._isDirty = !0,
        this._x = e,
        this._y = i,
        this._z = o
    }
    return Object.defineProperty(a.prototype, "x", {
        get: function() {
            return this._x
        },
        set: function(e) {
            this._x = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "y", {
        get: function() {
            return this._y
        },
        set: function(e) {
            this._y = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "z", {
        get: function() {
            return this._z
        },
        set: function(e) {
            this._z = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.toString = function() {
        return "{X: " + this._x + " Y: " + this._y + " Z: " + this._z + "}"
    }
    ,
    a.prototype.getClassName = function() {
        return "Vector3"
    }
    ,
    a.prototype.getHashCode = function() {
        var e = this._x | 0;
        return e = e * 397 ^ (this._y | 0),
        e = e * 397 ^ (this._z | 0),
        e
    }
    ,
    a.prototype.asArray = function() {
        var e = [];
        return this.toArray(e, 0),
        e
    }
    ,
    a.prototype.toArray = function(e, i) {
        return i === void 0 && (i = 0),
        e[i] = this._x,
        e[i + 1] = this._y,
        e[i + 2] = this._z,
        this
    }
    ,
    a.prototype.fromArray = function(e, i) {
        return i === void 0 && (i = 0),
        a.FromArrayToRef(e, i, this),
        this
    }
    ,
    a.prototype.toQuaternion = function() {
        return Quaternion.RotationYawPitchRoll(this._y, this._x, this._z)
    }
    ,
    a.prototype.addInPlace = function(e) {
        return this.addInPlaceFromFloats(e._x, e._y, e._z)
    }
    ,
    a.prototype.addInPlaceFromFloats = function(e, i, o) {
        return this.x += e,
        this.y += i,
        this.z += o,
        this
    }
    ,
    a.prototype.add = function(e) {
        return new a(this._x + e._x,this._y + e._y,this._z + e._z)
    }
    ,
    a.prototype.addToRef = function(e, i) {
        return i.copyFromFloats(this._x + e._x, this._y + e._y, this._z + e._z)
    }
    ,
    a.prototype.subtractInPlace = function(e) {
        return this.x -= e._x,
        this.y -= e._y,
        this.z -= e._z,
        this
    }
    ,
    a.prototype.subtract = function(e) {
        return new a(this._x - e._x,this._y - e._y,this._z - e._z)
    }
    ,
    a.prototype.subtractToRef = function(e, i) {
        return this.subtractFromFloatsToRef(e._x, e._y, e._z, i)
    }
    ,
    a.prototype.subtractFromFloats = function(e, i, o) {
        return new a(this._x - e,this._y - i,this._z - o)
    }
    ,
    a.prototype.subtractFromFloatsToRef = function(e, i, o, s) {
        return s.copyFromFloats(this._x - e, this._y - i, this._z - o)
    }
    ,
    a.prototype.negate = function() {
        return new a(-this._x,-this._y,-this._z)
    }
    ,
    a.prototype.negateInPlace = function() {
        return this.x *= -1,
        this.y *= -1,
        this.z *= -1,
        this
    }
    ,
    a.prototype.negateToRef = function(e) {
        return e.copyFromFloats(this._x * -1, this._y * -1, this._z * -1)
    }
    ,
    a.prototype.scaleInPlace = function(e) {
        return this.x *= e,
        this.y *= e,
        this.z *= e,
        this
    }
    ,
    a.prototype.scale = function(e) {
        return new a(this._x * e,this._y * e,this._z * e)
    }
    ,
    a.prototype.scaleToRef = function(e, i) {
        return i.copyFromFloats(this._x * e, this._y * e, this._z * e)
    }
    ,
    a.prototype.scaleAndAddToRef = function(e, i) {
        return i.addInPlaceFromFloats(this._x * e, this._y * e, this._z * e)
    }
    ,
    a.prototype.projectOnPlane = function(e, i) {
        var o = a.Zero();
        return this.projectOnPlaneToRef(e, i, o),
        o
    }
    ,
    a.prototype.projectOnPlaneToRef = function(e, i, o) {
        var s = e.normal
          , c = e.d
          , d = MathTmp.Vector3[0];
        this.subtractToRef(i, d),
        d.normalize();
        var _ = a.Dot(d, s)
          , b = -(a.Dot(i, s) + c) / _
          , k = d.scaleInPlace(b);
        i.addToRef(k, o)
    }
    ,
    a.prototype.equals = function(e) {
        return e && this._x === e._x && this._y === e._y && this._z === e._z
    }
    ,
    a.prototype.equalsWithEpsilon = function(e, i) {
        return i === void 0 && (i = Epsilon),
        e && Scalar.WithinEpsilon(this._x, e._x, i) && Scalar.WithinEpsilon(this._y, e._y, i) && Scalar.WithinEpsilon(this._z, e._z, i)
    }
    ,
    a.prototype.equalsToFloats = function(e, i, o) {
        return this._x === e && this._y === i && this._z === o
    }
    ,
    a.prototype.multiplyInPlace = function(e) {
        return this.x *= e._x,
        this.y *= e._y,
        this.z *= e._z,
        this
    }
    ,
    a.prototype.multiply = function(e) {
        return this.multiplyByFloats(e._x, e._y, e._z)
    }
    ,
    a.prototype.multiplyToRef = function(e, i) {
        return i.copyFromFloats(this._x * e._x, this._y * e._y, this._z * e._z)
    }
    ,
    a.prototype.multiplyByFloats = function(e, i, o) {
        return new a(this._x * e,this._y * i,this._z * o)
    }
    ,
    a.prototype.divide = function(e) {
        return new a(this._x / e._x,this._y / e._y,this._z / e._z)
    }
    ,
    a.prototype.divideToRef = function(e, i) {
        return i.copyFromFloats(this._x / e._x, this._y / e._y, this._z / e._z)
    }
    ,
    a.prototype.divideInPlace = function(e) {
        return this.divideToRef(e, this)
    }
    ,
    a.prototype.minimizeInPlace = function(e) {
        return this.minimizeInPlaceFromFloats(e._x, e._y, e._z)
    }
    ,
    a.prototype.maximizeInPlace = function(e) {
        return this.maximizeInPlaceFromFloats(e._x, e._y, e._z)
    }
    ,
    a.prototype.minimizeInPlaceFromFloats = function(e, i, o) {
        return e < this._x && (this.x = e),
        i < this._y && (this.y = i),
        o < this._z && (this.z = o),
        this
    }
    ,
    a.prototype.maximizeInPlaceFromFloats = function(e, i, o) {
        return e > this._x && (this.x = e),
        i > this._y && (this.y = i),
        o > this._z && (this.z = o),
        this
    }
    ,
    a.prototype.isNonUniformWithinEpsilon = function(e) {
        var i = Math.abs(this._x)
          , o = Math.abs(this._y);
        if (!Scalar.WithinEpsilon(i, o, e))
            return !0;
        var s = Math.abs(this._z);
        return !Scalar.WithinEpsilon(i, s, e) || !Scalar.WithinEpsilon(o, s, e)
    }
    ,
    Object.defineProperty(a.prototype, "isNonUniform", {
        get: function() {
            var e = Math.abs(this._x)
              , i = Math.abs(this._y);
            if (e !== i)
                return !0;
            var o = Math.abs(this._z);
            return e !== o
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.floor = function() {
        return new a(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))
    }
    ,
    a.prototype.fract = function() {
        return new a(this._x - Math.floor(this._x),this._y - Math.floor(this._y),this._z - Math.floor(this._z))
    }
    ,
    a.prototype.length = function() {
        return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z)
    }
    ,
    a.prototype.lengthSquared = function() {
        return this._x * this._x + this._y * this._y + this._z * this._z
    }
    ,
    a.prototype.normalize = function() {
        return this.normalizeFromLength(this.length())
    }
    ,
    a.prototype.reorderInPlace = function(e) {
        var i = this;
        return e = e.toLowerCase(),
        e === "xyz" ? this : (MathTmp.Vector3[0].copyFrom(this),
        ["x", "y", "z"].forEach(function(o, s) {
            i[o] = MathTmp.Vector3[0][e[s]]
        }),
        this)
    }
    ,
    a.prototype.rotateByQuaternionToRef = function(e, i) {
        return e.toRotationMatrix(MathTmp.Matrix[0]),
        a.TransformCoordinatesToRef(this, MathTmp.Matrix[0], i),
        i
    }
    ,
    a.prototype.rotateByQuaternionAroundPointToRef = function(e, i, o) {
        return this.subtractToRef(i, MathTmp.Vector3[0]),
        MathTmp.Vector3[0].rotateByQuaternionToRef(e, MathTmp.Vector3[0]),
        i.addToRef(MathTmp.Vector3[0], o),
        o
    }
    ,
    a.prototype.cross = function(e) {
        return a.Cross(this, e)
    }
    ,
    a.prototype.normalizeFromLength = function(e) {
        return e === 0 || e === 1 ? this : this.scaleInPlace(1 / e)
    }
    ,
    a.prototype.normalizeToNew = function() {
        var e = new a(0,0,0);
        return this.normalizeToRef(e),
        e
    }
    ,
    a.prototype.normalizeToRef = function(e) {
        var i = this.length();
        return i === 0 || i === 1 ? e.copyFromFloats(this._x, this._y, this._z) : this.scaleToRef(1 / i, e)
    }
    ,
    a.prototype.clone = function() {
        return new a(this._x,this._y,this._z)
    }
    ,
    a.prototype.copyFrom = function(e) {
        return this.copyFromFloats(e._x, e._y, e._z)
    }
    ,
    a.prototype.copyFromFloats = function(e, i, o) {
        return this.x = e,
        this.y = i,
        this.z = o,
        this
    }
    ,
    a.prototype.set = function(e, i, o) {
        return this.copyFromFloats(e, i, o)
    }
    ,
    a.prototype.setAll = function(e) {
        return this.x = this.y = this.z = e,
        this
    }
    ,
    a.GetClipFactor = function(e, i, o, s) {
        var c = a.Dot(e, o) - s
          , d = a.Dot(i, o) - s
          , _ = c / (c - d);
        return _
    }
    ,
    a.GetAngleBetweenVectors = function(e, i, o) {
        var s = e.normalizeToRef(MathTmp.Vector3[1])
          , c = i.normalizeToRef(MathTmp.Vector3[2])
          , d = a.Dot(s, c)
          , _ = Math.acos(d)
          , b = MathTmp.Vector3[3];
        return a.CrossToRef(s, c, b),
        a.Dot(b, o) > 0 ? isNaN(_) ? 0 : _ : isNaN(_) ? -Math.PI : -Math.acos(d)
    }
    ,
    a.GetAngleBetweenVectorsOnPlane = function(e, i, o) {
        MathTmp.Vector3[0].copyFrom(e);
        var s = MathTmp.Vector3[0];
        MathTmp.Vector3[1].copyFrom(i);
        var c = MathTmp.Vector3[1];
        MathTmp.Vector3[2].copyFrom(o);
        var d = MathTmp.Vector3[2]
          , _ = MathTmp.Vector3[3]
          , b = MathTmp.Vector3[4];
        s.normalize(),
        c.normalize(),
        d.normalize(),
        a.CrossToRef(d, s, _),
        a.CrossToRef(_, d, b);
        var k = Math.atan2(a.Dot(c, _), a.Dot(c, b));
        return Scalar.NormalizeRadians(k)
    }
    ,
    a.SlerpToRef = function(e, i, o, s) {
        o = Scalar.Clamp(o, 0, 1);
        var c = MathTmp.Vector3[0], d = MathTmp.Vector3[1], _, b;
        c.copyFrom(e),
        _ = c.length(),
        c.normalizeFromLength(_),
        d.copyFrom(i),
        b = d.length(),
        d.normalizeFromLength(b);
        var k = a.Dot(c, d), j, $;
        if (k < 1 - Epsilon) {
            var _e = Math.acos(k)
              , et = 1 / Math.sin(_e);
            j = Math.sin((1 - o) * _e) * et,
            $ = Math.sin(o * _e) * et
        } else
            j = 1 - o,
            $ = o;
        c.scaleInPlace(j),
        d.scaleInPlace($),
        s.copyFrom(c).addInPlace(d),
        s.scaleInPlace(Scalar.Lerp(_, b, o))
    }
    ,
    a.SmoothToRef = function(e, i, o, s, c) {
        a.SlerpToRef(e, i, s === 0 ? 1 : o / s, c)
    }
    ,
    a.FromArray = function(e, i) {
        return i === void 0 && (i = 0),
        new a(e[i],e[i + 1],e[i + 2])
    }
    ,
    a.FromFloatArray = function(e, i) {
        return a.FromArray(e, i)
    }
    ,
    a.FromArrayToRef = function(e, i, o) {
        o.x = e[i],
        o.y = e[i + 1],
        o.z = e[i + 2]
    }
    ,
    a.FromFloatArrayToRef = function(e, i, o) {
        return a.FromArrayToRef(e, i, o)
    }
    ,
    a.FromFloatsToRef = function(e, i, o, s) {
        s.copyFromFloats(e, i, o)
    }
    ,
    a.Zero = function() {
        return new a(0,0,0)
    }
    ,
    a.One = function() {
        return new a(1,1,1)
    }
    ,
    a.Up = function() {
        return new a(0,1,0)
    }
    ,
    Object.defineProperty(a, "UpReadOnly", {
        get: function() {
            return a._UpReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "RightReadOnly", {
        get: function() {
            return a._RightReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "LeftHandedForwardReadOnly", {
        get: function() {
            return a._LeftHandedForwardReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "RightHandedForwardReadOnly", {
        get: function() {
            return a._RightHandedForwardReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ZeroReadOnly", {
        get: function() {
            return a._ZeroReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    a.Down = function() {
        return new a(0,-1,0)
    }
    ,
    a.Forward = function(e) {
        return e === void 0 && (e = !1),
        new a(0,0,e ? -1 : 1)
    }
    ,
    a.Backward = function(e) {
        return e === void 0 && (e = !1),
        new a(0,0,e ? 1 : -1)
    }
    ,
    a.Right = function() {
        return new a(1,0,0)
    }
    ,
    a.Left = function() {
        return new a(-1,0,0)
    }
    ,
    a.TransformCoordinates = function(e, i) {
        var o = a.Zero();
        return a.TransformCoordinatesToRef(e, i, o),
        o
    }
    ,
    a.TransformCoordinatesToRef = function(e, i, o) {
        a.TransformCoordinatesFromFloatsToRef(e._x, e._y, e._z, i, o)
    }
    ,
    a.TransformCoordinatesFromFloatsToRef = function(e, i, o, s, c) {
        var d = s.m
          , _ = e * d[0] + i * d[4] + o * d[8] + d[12]
          , b = e * d[1] + i * d[5] + o * d[9] + d[13]
          , k = e * d[2] + i * d[6] + o * d[10] + d[14]
          , j = 1 / (e * d[3] + i * d[7] + o * d[11] + d[15]);
        c.x = _ * j,
        c.y = b * j,
        c.z = k * j
    }
    ,
    a.TransformNormal = function(e, i) {
        var o = a.Zero();
        return a.TransformNormalToRef(e, i, o),
        o
    }
    ,
    a.TransformNormalToRef = function(e, i, o) {
        this.TransformNormalFromFloatsToRef(e._x, e._y, e._z, i, o)
    }
    ,
    a.TransformNormalFromFloatsToRef = function(e, i, o, s, c) {
        var d = s.m;
        c.x = e * d[0] + i * d[4] + o * d[8],
        c.y = e * d[1] + i * d[5] + o * d[9],
        c.z = e * d[2] + i * d[6] + o * d[10]
    }
    ,
    a.CatmullRom = function(e, i, o, s, c) {
        var d = c * c
          , _ = c * d
          , b = .5 * (2 * i._x + (-e._x + o._x) * c + (2 * e._x - 5 * i._x + 4 * o._x - s._x) * d + (-e._x + 3 * i._x - 3 * o._x + s._x) * _)
          , k = .5 * (2 * i._y + (-e._y + o._y) * c + (2 * e._y - 5 * i._y + 4 * o._y - s._y) * d + (-e._y + 3 * i._y - 3 * o._y + s._y) * _)
          , j = .5 * (2 * i._z + (-e._z + o._z) * c + (2 * e._z - 5 * i._z + 4 * o._z - s._z) * d + (-e._z + 3 * i._z - 3 * o._z + s._z) * _);
        return new a(b,k,j)
    }
    ,
    a.Clamp = function(e, i, o) {
        var s = new a;
        return a.ClampToRef(e, i, o, s),
        s
    }
    ,
    a.ClampToRef = function(e, i, o, s) {
        var c = e._x;
        c = c > o._x ? o._x : c,
        c = c < i._x ? i._x : c;
        var d = e._y;
        d = d > o._y ? o._y : d,
        d = d < i._y ? i._y : d;
        var _ = e._z;
        _ = _ > o._z ? o._z : _,
        _ = _ < i._z ? i._z : _,
        s.copyFromFloats(c, d, _)
    }
    ,
    a.CheckExtends = function(e, i, o) {
        i.minimizeInPlace(e),
        o.maximizeInPlace(e)
    }
    ,
    a.Hermite = function(e, i, o, s, c) {
        var d = c * c
          , _ = c * d
          , b = 2 * _ - 3 * d + 1
          , k = -2 * _ + 3 * d
          , j = _ - 2 * d + c
          , $ = _ - d
          , _e = e._x * b + o._x * k + i._x * j + s._x * $
          , et = e._y * b + o._y * k + i._y * j + s._y * $
          , tt = e._z * b + o._z * k + i._z * j + s._z * $;
        return new a(_e,et,tt)
    }
    ,
    a.Hermite1stDerivative = function(e, i, o, s, c) {
        var d = a.Zero();
        return this.Hermite1stDerivativeToRef(e, i, o, s, c, d),
        d
    }
    ,
    a.Hermite1stDerivativeToRef = function(e, i, o, s, c, d) {
        var _ = c * c;
        d.x = (_ - c) * 6 * e.x + (3 * _ - 4 * c + 1) * i.x + (-_ + c) * 6 * o.x + (3 * _ - 2 * c) * s.x,
        d.y = (_ - c) * 6 * e.y + (3 * _ - 4 * c + 1) * i.y + (-_ + c) * 6 * o.y + (3 * _ - 2 * c) * s.y,
        d.z = (_ - c) * 6 * e.z + (3 * _ - 4 * c + 1) * i.z + (-_ + c) * 6 * o.z + (3 * _ - 2 * c) * s.z
    }
    ,
    a.Lerp = function(e, i, o) {
        var s = new a(0,0,0);
        return a.LerpToRef(e, i, o, s),
        s
    }
    ,
    a.LerpToRef = function(e, i, o, s) {
        s.x = e._x + (i._x - e._x) * o,
        s.y = e._y + (i._y - e._y) * o,
        s.z = e._z + (i._z - e._z) * o
    }
    ,
    a.Dot = function(e, i) {
        return e._x * i._x + e._y * i._y + e._z * i._z
    }
    ,
    a.Cross = function(e, i) {
        var o = a.Zero();
        return a.CrossToRef(e, i, o),
        o
    }
    ,
    a.CrossToRef = function(e, i, o) {
        var s = e._y * i._z - e._z * i._y
          , c = e._z * i._x - e._x * i._z
          , d = e._x * i._y - e._y * i._x;
        o.copyFromFloats(s, c, d)
    }
    ,
    a.Normalize = function(e) {
        var i = a.Zero();
        return a.NormalizeToRef(e, i),
        i
    }
    ,
    a.NormalizeToRef = function(e, i) {
        e.normalizeToRef(i)
    }
    ,
    a.Project = function(e, i, o, s) {
        var c = new a;
        return a.ProjectToRef(e, i, o, s, c),
        c
    }
    ,
    a.ProjectToRef = function(e, i, o, s, c) {
        var d = s.width
          , _ = s.height
          , b = s.x
          , k = s.y
          , j = MathTmp.Matrix[1];
        Matrix.FromValuesToRef(d / 2, 0, 0, 0, 0, -_ / 2, 0, 0, 0, 0, .5, 0, b + d / 2, _ / 2 + k, .5, 1, j);
        var $ = MathTmp.Matrix[0];
        return i.multiplyToRef(o, $),
        $.multiplyToRef(j, $),
        a.TransformCoordinatesToRef(e, $, c),
        c
    }
    ,
    a._UnprojectFromInvertedMatrixToRef = function(e, i, o) {
        a.TransformCoordinatesToRef(e, i, o);
        var s = i.m
          , c = e._x * s[3] + e._y * s[7] + e._z * s[11] + s[15];
        Scalar.WithinEpsilon(c, 1) && o.scaleInPlace(1 / c)
    }
    ,
    a.UnprojectFromTransform = function(e, i, o, s, c) {
        var d = MathTmp.Matrix[0];
        s.multiplyToRef(c, d),
        d.invert(),
        e.x = e._x / i * 2 - 1,
        e.y = -(e._y / o * 2 - 1);
        var _ = new a;
        return a._UnprojectFromInvertedMatrixToRef(e, d, _),
        _
    }
    ,
    a.Unproject = function(e, i, o, s, c, d) {
        var _ = a.Zero();
        return a.UnprojectToRef(e, i, o, s, c, d, _),
        _
    }
    ,
    a.UnprojectToRef = function(e, i, o, s, c, d, _) {
        a.UnprojectFloatsToRef(e._x, e._y, e._z, i, o, s, c, d, _)
    }
    ,
    a.UnprojectFloatsToRef = function(e, i, o, s, c, d, _, b, k) {
        var j = MathTmp.Matrix[0];
        d.multiplyToRef(_, j),
        j.multiplyToRef(b, j),
        j.invert();
        var $ = MathTmp.Vector3[0];
        $.x = e / s * 2 - 1,
        $.y = -(i / c * 2 - 1),
        $.z = 2 * o - 1,
        a._UnprojectFromInvertedMatrixToRef($, j, k)
    }
    ,
    a.Minimize = function(e, i) {
        var o = e.clone();
        return o.minimizeInPlace(i),
        o
    }
    ,
    a.Maximize = function(e, i) {
        var o = e.clone();
        return o.maximizeInPlace(i),
        o
    }
    ,
    a.Distance = function(e, i) {
        return Math.sqrt(a.DistanceSquared(e, i))
    }
    ,
    a.DistanceSquared = function(e, i) {
        var o = e._x - i._x
          , s = e._y - i._y
          , c = e._z - i._z;
        return o * o + s * s + c * c
    }
    ,
    a.ProjectOnTriangleToRef = function(e, i, o, s, c) {
        var d = MathTmp.Vector3[0]
          , _ = MathTmp.Vector3[1]
          , b = MathTmp.Vector3[2]
          , k = MathTmp.Vector3[3]
          , j = MathTmp.Vector3[4];
        o.subtractToRef(i, d),
        s.subtractToRef(i, _),
        s.subtractToRef(o, b);
        var $ = d.length()
          , _e = _.length()
          , et = b.length();
        if ($ < Epsilon || _e < Epsilon || et < Epsilon)
            return c.copyFrom(i),
            a.Distance(e, i);
        e.subtractToRef(i, j),
        a.CrossToRef(d, _, k);
        var tt = k.length();
        if (tt < Epsilon)
            return c.copyFrom(i),
            a.Distance(e, i);
        k.normalizeFromLength(tt);
        var rt = j.length();
        if (rt < Epsilon)
            return c.copyFrom(i),
            0;
        j.normalizeFromLength(rt);
        var it = a.Dot(k, j)
          , nt = MathTmp.Vector3[5]
          , ot = MathTmp.Vector3[6];
        nt.copyFrom(k).scaleInPlace(-rt * it),
        ot.copyFrom(e).addInPlace(nt);
        var at = MathTmp.Vector3[4]
          , st = MathTmp.Vector3[5]
          , ut = MathTmp.Vector3[7]
          , ct = MathTmp.Vector3[8];
        at.copyFrom(d).scaleInPlace(1 / $),
        ct.copyFrom(_).scaleInPlace(1 / _e),
        at.addInPlace(ct).scaleInPlace(-1),
        st.copyFrom(d).scaleInPlace(-1 / $),
        ct.copyFrom(b).scaleInPlace(1 / et),
        st.addInPlace(ct).scaleInPlace(-1),
        ut.copyFrom(b).scaleInPlace(-1 / et),
        ct.copyFrom(_).scaleInPlace(-1 / _e),
        ut.addInPlace(ct).scaleInPlace(-1);
        var lt = MathTmp.Vector3[9], ft, ht, pt, dt;
        lt.copyFrom(ot).subtractInPlace(i),
        a.CrossToRef(at, lt, ct),
        ft = a.Dot(ct, k),
        ht = ft,
        lt.copyFrom(ot).subtractInPlace(o),
        a.CrossToRef(st, lt, ct),
        ft = a.Dot(ct, k),
        pt = ft,
        lt.copyFrom(ot).subtractInPlace(s),
        a.CrossToRef(ut, lt, ct),
        ft = a.Dot(ct, k),
        dt = ft;
        var _t = MathTmp.Vector3[10], mt, vt;
        ht > 0 && pt < 0 ? (_t.copyFrom(d),
        mt = i,
        vt = o) : pt > 0 && dt < 0 ? (_t.copyFrom(b),
        mt = o,
        vt = s) : (_t.copyFrom(_).scaleInPlace(-1),
        mt = s,
        vt = i);
        var yt = MathTmp.Vector3[9]
          , Et = MathTmp.Vector3[4];
        mt.subtractToRef(ot, ct),
        vt.subtractToRef(ot, yt),
        a.CrossToRef(ct, yt, Et);
        var At = a.Dot(Et, k) < 0;
        if (!At)
            return c.copyFrom(ot),
            Math.abs(rt * it);
        var gt = MathTmp.Vector3[5];
        a.CrossToRef(_t, Et, gt),
        gt.normalize();
        var St = MathTmp.Vector3[9];
        St.copyFrom(mt).subtractInPlace(ot);
        var xt = St.length();
        if (xt < Epsilon)
            return c.copyFrom(mt),
            a.Distance(e, mt);
        St.normalizeFromLength(xt);
        var bt = a.Dot(gt, St)
          , Rt = MathTmp.Vector3[7];
        Rt.copyFrom(ot).addInPlace(gt.scaleInPlace(xt * bt)),
        ct.copyFrom(Rt).subtractInPlace(mt),
        rt = _t.length(),
        _t.normalizeFromLength(rt);
        var Mt = a.Dot(ct, _t) / Math.max(rt, Epsilon);
        return Mt = Scalar.Clamp(Mt, 0, 1),
        Rt.copyFrom(mt).addInPlace(_t.scaleInPlace(Mt * rt)),
        c.copyFrom(Rt),
        a.Distance(e, Rt)
    }
    ,
    a.Center = function(e, i) {
        return a.CenterToRef(e, i, a.Zero())
    }
    ,
    a.CenterToRef = function(e, i, o) {
        return o.copyFromFloats((e._x + i._x) / 2, (e._y + i._y) / 2, (e._z + i._z) / 2)
    }
    ,
    a.RotationFromAxis = function(e, i, o) {
        var s = a.Zero();
        return a.RotationFromAxisToRef(e, i, o, s),
        s
    }
    ,
    a.RotationFromAxisToRef = function(e, i, o, s) {
        var c = MathTmp.Quaternion[0];
        Quaternion.RotationQuaternionFromAxisToRef(e, i, o, c),
        c.toEulerAnglesToRef(s)
    }
    ,
    a._UpReadOnly = a.Up(),
    a._LeftHandedForwardReadOnly = a.Forward(!1),
    a._RightHandedForwardReadOnly = a.Forward(!0),
    a._RightReadOnly = a.Right(),
    a._ZeroReadOnly = a.Zero(),
    a
}()
  , Vector4 = function() {
    function a(e, i, o, s) {
        this.x = e,
        this.y = i,
        this.z = o,
        this.w = s
    }
    return a.prototype.toString = function() {
        return "{X: " + this.x + " Y: " + this.y + " Z: " + this.z + " W: " + this.w + "}"
    }
    ,
    a.prototype.getClassName = function() {
        return "Vector4"
    }
    ,
    a.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
    }
    ,
    a.prototype.asArray = function() {
        var e = new Array;
        return this.toArray(e, 0),
        e
    }
    ,
    a.prototype.toArray = function(e, i) {
        return i === void 0 && (i = 0),
        e[i] = this.x,
        e[i + 1] = this.y,
        e[i + 2] = this.z,
        e[i + 3] = this.w,
        this
    }
    ,
    a.prototype.fromArray = function(e, i) {
        return i === void 0 && (i = 0),
        a.FromArrayToRef(e, i, this),
        this
    }
    ,
    a.prototype.addInPlace = function(e) {
        return this.x += e.x,
        this.y += e.y,
        this.z += e.z,
        this.w += e.w,
        this
    }
    ,
    a.prototype.add = function(e) {
        return new a(this.x + e.x,this.y + e.y,this.z + e.z,this.w + e.w)
    }
    ,
    a.prototype.addToRef = function(e, i) {
        return i.x = this.x + e.x,
        i.y = this.y + e.y,
        i.z = this.z + e.z,
        i.w = this.w + e.w,
        this
    }
    ,
    a.prototype.subtractInPlace = function(e) {
        return this.x -= e.x,
        this.y -= e.y,
        this.z -= e.z,
        this.w -= e.w,
        this
    }
    ,
    a.prototype.subtract = function(e) {
        return new a(this.x - e.x,this.y - e.y,this.z - e.z,this.w - e.w)
    }
    ,
    a.prototype.subtractToRef = function(e, i) {
        return i.x = this.x - e.x,
        i.y = this.y - e.y,
        i.z = this.z - e.z,
        i.w = this.w - e.w,
        this
    }
    ,
    a.prototype.subtractFromFloats = function(e, i, o, s) {
        return new a(this.x - e,this.y - i,this.z - o,this.w - s)
    }
    ,
    a.prototype.subtractFromFloatsToRef = function(e, i, o, s, c) {
        return c.x = this.x - e,
        c.y = this.y - i,
        c.z = this.z - o,
        c.w = this.w - s,
        this
    }
    ,
    a.prototype.negate = function() {
        return new a(-this.x,-this.y,-this.z,-this.w)
    }
    ,
    a.prototype.negateInPlace = function() {
        return this.x *= -1,
        this.y *= -1,
        this.z *= -1,
        this.w *= -1,
        this
    }
    ,
    a.prototype.negateToRef = function(e) {
        return e.copyFromFloats(this.x * -1, this.y * -1, this.z * -1, this.w * -1)
    }
    ,
    a.prototype.scaleInPlace = function(e) {
        return this.x *= e,
        this.y *= e,
        this.z *= e,
        this.w *= e,
        this
    }
    ,
    a.prototype.scale = function(e) {
        return new a(this.x * e,this.y * e,this.z * e,this.w * e)
    }
    ,
    a.prototype.scaleToRef = function(e, i) {
        return i.x = this.x * e,
        i.y = this.y * e,
        i.z = this.z * e,
        i.w = this.w * e,
        this
    }
    ,
    a.prototype.scaleAndAddToRef = function(e, i) {
        return i.x += this.x * e,
        i.y += this.y * e,
        i.z += this.z * e,
        i.w += this.w * e,
        this
    }
    ,
    a.prototype.equals = function(e) {
        return e && this.x === e.x && this.y === e.y && this.z === e.z && this.w === e.w
    }
    ,
    a.prototype.equalsWithEpsilon = function(e, i) {
        return i === void 0 && (i = Epsilon),
        e && Scalar.WithinEpsilon(this.x, e.x, i) && Scalar.WithinEpsilon(this.y, e.y, i) && Scalar.WithinEpsilon(this.z, e.z, i) && Scalar.WithinEpsilon(this.w, e.w, i)
    }
    ,
    a.prototype.equalsToFloats = function(e, i, o, s) {
        return this.x === e && this.y === i && this.z === o && this.w === s
    }
    ,
    a.prototype.multiplyInPlace = function(e) {
        return this.x *= e.x,
        this.y *= e.y,
        this.z *= e.z,
        this.w *= e.w,
        this
    }
    ,
    a.prototype.multiply = function(e) {
        return new a(this.x * e.x,this.y * e.y,this.z * e.z,this.w * e.w)
    }
    ,
    a.prototype.multiplyToRef = function(e, i) {
        return i.x = this.x * e.x,
        i.y = this.y * e.y,
        i.z = this.z * e.z,
        i.w = this.w * e.w,
        this
    }
    ,
    a.prototype.multiplyByFloats = function(e, i, o, s) {
        return new a(this.x * e,this.y * i,this.z * o,this.w * s)
    }
    ,
    a.prototype.divide = function(e) {
        return new a(this.x / e.x,this.y / e.y,this.z / e.z,this.w / e.w)
    }
    ,
    a.prototype.divideToRef = function(e, i) {
        return i.x = this.x / e.x,
        i.y = this.y / e.y,
        i.z = this.z / e.z,
        i.w = this.w / e.w,
        this
    }
    ,
    a.prototype.divideInPlace = function(e) {
        return this.divideToRef(e, this)
    }
    ,
    a.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
    }
    ,
    a.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
    }
    ,
    a.prototype.floor = function() {
        return new a(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))
    }
    ,
    a.prototype.fract = function() {
        return new a(this.x - Math.floor(this.x),this.y - Math.floor(this.y),this.z - Math.floor(this.z),this.w - Math.floor(this.w))
    }
    ,
    a.prototype.length = function() {
        return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w)
    }
    ,
    a.prototype.lengthSquared = function() {
        return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w
    }
    ,
    a.prototype.normalize = function() {
        var e = this.length();
        return e === 0 ? this : this.scaleInPlace(1 / e)
    }
    ,
    a.prototype.toVector3 = function() {
        return new Vector3(this.x,this.y,this.z)
    }
    ,
    a.prototype.clone = function() {
        return new a(this.x,this.y,this.z,this.w)
    }
    ,
    a.prototype.copyFrom = function(e) {
        return this.x = e.x,
        this.y = e.y,
        this.z = e.z,
        this.w = e.w,
        this
    }
    ,
    a.prototype.copyFromFloats = function(e, i, o, s) {
        return this.x = e,
        this.y = i,
        this.z = o,
        this.w = s,
        this
    }
    ,
    a.prototype.set = function(e, i, o, s) {
        return this.copyFromFloats(e, i, o, s)
    }
    ,
    a.prototype.setAll = function(e) {
        return this.x = this.y = this.z = this.w = e,
        this
    }
    ,
    a.FromArray = function(e, i) {
        return i || (i = 0),
        new a(e[i],e[i + 1],e[i + 2],e[i + 3])
    }
    ,
    a.FromArrayToRef = function(e, i, o) {
        o.x = e[i],
        o.y = e[i + 1],
        o.z = e[i + 2],
        o.w = e[i + 3]
    }
    ,
    a.FromFloatArrayToRef = function(e, i, o) {
        a.FromArrayToRef(e, i, o)
    }
    ,
    a.FromFloatsToRef = function(e, i, o, s, c) {
        c.x = e,
        c.y = i,
        c.z = o,
        c.w = s
    }
    ,
    a.Zero = function() {
        return new a(0,0,0,0)
    }
    ,
    a.One = function() {
        return new a(1,1,1,1)
    }
    ,
    a.Normalize = function(e) {
        var i = a.Zero();
        return a.NormalizeToRef(e, i),
        i
    }
    ,
    a.NormalizeToRef = function(e, i) {
        i.copyFrom(e),
        i.normalize()
    }
    ,
    a.Minimize = function(e, i) {
        var o = e.clone();
        return o.minimizeInPlace(i),
        o
    }
    ,
    a.Maximize = function(e, i) {
        var o = e.clone();
        return o.maximizeInPlace(i),
        o
    }
    ,
    a.Distance = function(e, i) {
        return Math.sqrt(a.DistanceSquared(e, i))
    }
    ,
    a.DistanceSquared = function(e, i) {
        var o = e.x - i.x
          , s = e.y - i.y
          , c = e.z - i.z
          , d = e.w - i.w;
        return o * o + s * s + c * c + d * d
    }
    ,
    a.Center = function(e, i) {
        return a.CenterToRef(e, i, a.Zero())
    }
    ,
    a.CenterToRef = function(e, i, o) {
        return o.copyFromFloats((e.x + i.x) / 2, (e.y + i.y) / 2, (e.z + i.z) / 2, (e.w + i.w) / 2)
    }
    ,
    a.TransformCoordinates = function(e, i) {
        var o = a.Zero();
        return a.TransformCoordinatesToRef(e, i, o),
        o
    }
    ,
    a.TransformCoordinatesToRef = function(e, i, o) {
        a.TransformCoordinatesFromFloatsToRef(e._x, e._y, e._z, i, o)
    }
    ,
    a.TransformCoordinatesFromFloatsToRef = function(e, i, o, s, c) {
        var d = s.m
          , _ = e * d[0] + i * d[4] + o * d[8] + d[12]
          , b = e * d[1] + i * d[5] + o * d[9] + d[13]
          , k = e * d[2] + i * d[6] + o * d[10] + d[14]
          , j = e * d[3] + i * d[7] + o * d[11] + d[15];
        c.x = _,
        c.y = b,
        c.z = k,
        c.w = j
    }
    ,
    a.TransformNormal = function(e, i) {
        var o = a.Zero();
        return a.TransformNormalToRef(e, i, o),
        o
    }
    ,
    a.TransformNormalToRef = function(e, i, o) {
        var s = i.m
          , c = e.x * s[0] + e.y * s[4] + e.z * s[8]
          , d = e.x * s[1] + e.y * s[5] + e.z * s[9]
          , _ = e.x * s[2] + e.y * s[6] + e.z * s[10];
        o.x = c,
        o.y = d,
        o.z = _,
        o.w = e.w
    }
    ,
    a.TransformNormalFromFloatsToRef = function(e, i, o, s, c, d) {
        var _ = c.m;
        d.x = e * _[0] + i * _[4] + o * _[8],
        d.y = e * _[1] + i * _[5] + o * _[9],
        d.z = e * _[2] + i * _[6] + o * _[10],
        d.w = s
    }
    ,
    a.FromVector3 = function(e, i) {
        return i === void 0 && (i = 0),
        new a(e._x,e._y,e._z,i)
    }
    ,
    a
}()
  , Quaternion = function() {
    function a(e, i, o, s) {
        e === void 0 && (e = 0),
        i === void 0 && (i = 0),
        o === void 0 && (o = 0),
        s === void 0 && (s = 1),
        this._isDirty = !0,
        this._x = e,
        this._y = i,
        this._z = o,
        this._w = s
    }
    return Object.defineProperty(a.prototype, "x", {
        get: function() {
            return this._x
        },
        set: function(e) {
            this._x = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "y", {
        get: function() {
            return this._y
        },
        set: function(e) {
            this._y = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "z", {
        get: function() {
            return this._z
        },
        set: function(e) {
            this._z = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "w", {
        get: function() {
            return this._w
        },
        set: function(e) {
            this._w = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.toString = function() {
        return "{X: " + this._x + " Y: " + this._y + " Z: " + this._z + " W: " + this._w + "}"
    }
    ,
    a.prototype.getClassName = function() {
        return "Quaternion"
    }
    ,
    a.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
    }
    ,
    a.prototype.asArray = function() {
        return [this._x, this._y, this._z, this._w]
    }
    ,
    a.prototype.equals = function(e) {
        return e && this._x === e._x && this._y === e._y && this._z === e._z && this._w === e._w
    }
    ,
    a.prototype.equalsWithEpsilon = function(e, i) {
        return i === void 0 && (i = Epsilon),
        e && Scalar.WithinEpsilon(this._x, e._x, i) && Scalar.WithinEpsilon(this._y, e._y, i) && Scalar.WithinEpsilon(this._z, e._z, i) && Scalar.WithinEpsilon(this._w, e._w, i)
    }
    ,
    a.prototype.clone = function() {
        return new a(this._x,this._y,this._z,this._w)
    }
    ,
    a.prototype.copyFrom = function(e) {
        return this.x = e._x,
        this.y = e._y,
        this.z = e._z,
        this.w = e._w,
        this
    }
    ,
    a.prototype.copyFromFloats = function(e, i, o, s) {
        return this.x = e,
        this.y = i,
        this.z = o,
        this.w = s,
        this
    }
    ,
    a.prototype.set = function(e, i, o, s) {
        return this.copyFromFloats(e, i, o, s)
    }
    ,
    a.prototype.add = function(e) {
        return new a(this._x + e._x,this._y + e._y,this._z + e._z,this._w + e._w)
    }
    ,
    a.prototype.addInPlace = function(e) {
        return this._x += e._x,
        this._y += e._y,
        this._z += e._z,
        this._w += e._w,
        this
    }
    ,
    a.prototype.subtract = function(e) {
        return new a(this._x - e._x,this._y - e._y,this._z - e._z,this._w - e._w)
    }
    ,
    a.prototype.scale = function(e) {
        return new a(this._x * e,this._y * e,this._z * e,this._w * e)
    }
    ,
    a.prototype.scaleToRef = function(e, i) {
        return i.x = this._x * e,
        i.y = this._y * e,
        i.z = this._z * e,
        i.w = this._w * e,
        this
    }
    ,
    a.prototype.scaleInPlace = function(e) {
        return this.x *= e,
        this.y *= e,
        this.z *= e,
        this.w *= e,
        this
    }
    ,
    a.prototype.scaleAndAddToRef = function(e, i) {
        return i.x += this._x * e,
        i.y += this._y * e,
        i.z += this._z * e,
        i.w += this._w * e,
        this
    }
    ,
    a.prototype.multiply = function(e) {
        var i = new a(0,0,0,1);
        return this.multiplyToRef(e, i),
        i
    }
    ,
    a.prototype.multiplyToRef = function(e, i) {
        var o = this._x * e._w + this._y * e._z - this._z * e._y + this._w * e._x
          , s = -this._x * e._z + this._y * e._w + this._z * e._x + this._w * e._y
          , c = this._x * e._y - this._y * e._x + this._z * e._w + this._w * e._z
          , d = -this._x * e._x - this._y * e._y - this._z * e._z + this._w * e._w;
        return i.copyFromFloats(o, s, c, d),
        this
    }
    ,
    a.prototype.multiplyInPlace = function(e) {
        return this.multiplyToRef(e, this),
        this
    }
    ,
    a.prototype.conjugateToRef = function(e) {
        return e.copyFromFloats(-this._x, -this._y, -this._z, this._w),
        this
    }
    ,
    a.prototype.conjugateInPlace = function() {
        return this.x *= -1,
        this.y *= -1,
        this.z *= -1,
        this
    }
    ,
    a.prototype.conjugate = function() {
        var e = new a(-this._x,-this._y,-this._z,this._w);
        return e
    }
    ,
    a.prototype.length = function() {
        return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w)
    }
    ,
    a.prototype.normalize = function() {
        var e = this.length();
        if (e === 0)
            return this;
        var i = 1 / e;
        return this.x *= i,
        this.y *= i,
        this.z *= i,
        this.w *= i,
        this
    }
    ,
    a.prototype.toEulerAngles = function() {
        var e = Vector3.Zero();
        return this.toEulerAnglesToRef(e),
        e
    }
    ,
    a.prototype.toEulerAnglesToRef = function(e) {
        var i = this._z
          , o = this._x
          , s = this._y
          , c = this._w
          , d = c * c
          , _ = i * i
          , b = o * o
          , k = s * s
          , j = s * i - o * c
          , $ = .4999999;
        return j < -$ ? (e.y = 2 * Math.atan2(s, c),
        e.x = Math.PI / 2,
        e.z = 0) : j > $ ? (e.y = 2 * Math.atan2(s, c),
        e.x = -Math.PI / 2,
        e.z = 0) : (e.z = Math.atan2(2 * (o * s + i * c), -_ - b + k + d),
        e.x = Math.asin(-2 * (i * s - o * c)),
        e.y = Math.atan2(2 * (i * o + s * c), _ - b - k + d)),
        this
    }
    ,
    a.prototype.toRotationMatrix = function(e) {
        return Matrix.FromQuaternionToRef(this, e),
        this
    }
    ,
    a.prototype.fromRotationMatrix = function(e) {
        return a.FromRotationMatrixToRef(e, this),
        this
    }
    ,
    a.FromRotationMatrix = function(e) {
        var i = new a;
        return a.FromRotationMatrixToRef(e, i),
        i
    }
    ,
    a.FromRotationMatrixToRef = function(e, i) {
        var o = e.m, s = o[0], c = o[4], d = o[8], _ = o[1], b = o[5], k = o[9], j = o[2], $ = o[6], _e = o[10], et = s + b + _e, tt;
        et > 0 ? (tt = .5 / Math.sqrt(et + 1),
        i.w = .25 / tt,
        i.x = ($ - k) * tt,
        i.y = (d - j) * tt,
        i.z = (_ - c) * tt) : s > b && s > _e ? (tt = 2 * Math.sqrt(1 + s - b - _e),
        i.w = ($ - k) / tt,
        i.x = .25 * tt,
        i.y = (c + _) / tt,
        i.z = (d + j) / tt) : b > _e ? (tt = 2 * Math.sqrt(1 + b - s - _e),
        i.w = (d - j) / tt,
        i.x = (c + _) / tt,
        i.y = .25 * tt,
        i.z = (k + $) / tt) : (tt = 2 * Math.sqrt(1 + _e - s - b),
        i.w = (_ - c) / tt,
        i.x = (d + j) / tt,
        i.y = (k + $) / tt,
        i.z = .25 * tt)
    }
    ,
    a.Dot = function(e, i) {
        return e._x * i._x + e._y * i._y + e._z * i._z + e._w * i._w
    }
    ,
    a.AreClose = function(e, i) {
        var o = a.Dot(e, i);
        return o >= 0
    }
    ,
    a.SmoothToRef = function(e, i, o, s, c) {
        var d = s === 0 ? 1 : o / s;
        d = Scalar.Clamp(d, 0, 1),
        a.SlerpToRef(e, i, d, c)
    }
    ,
    a.Zero = function() {
        return new a(0,0,0,0)
    }
    ,
    a.Inverse = function(e) {
        return new a(-e._x,-e._y,-e._z,e._w)
    }
    ,
    a.InverseToRef = function(e, i) {
        return i.set(-e._x, -e._y, -e._z, e._w),
        i
    }
    ,
    a.Identity = function() {
        return new a(0,0,0,1)
    }
    ,
    a.IsIdentity = function(e) {
        return e && e._x === 0 && e._y === 0 && e._z === 0 && e._w === 1
    }
    ,
    a.RotationAxis = function(e, i) {
        return a.RotationAxisToRef(e, i, new a)
    }
    ,
    a.RotationAxisToRef = function(e, i, o) {
        var s = Math.sin(i / 2);
        return e.normalize(),
        o.w = Math.cos(i / 2),
        o.x = e._x * s,
        o.y = e._y * s,
        o.z = e._z * s,
        o
    }
    ,
    a.FromArray = function(e, i) {
        return i || (i = 0),
        new a(e[i],e[i + 1],e[i + 2],e[i + 3])
    }
    ,
    a.FromArrayToRef = function(e, i, o) {
        o.x = e[i],
        o.y = e[i + 1],
        o.z = e[i + 2],
        o.w = e[i + 3]
    }
    ,
    a.FromEulerAngles = function(e, i, o) {
        var s = new a;
        return a.RotationYawPitchRollToRef(i, e, o, s),
        s
    }
    ,
    a.FromEulerAnglesToRef = function(e, i, o, s) {
        return a.RotationYawPitchRollToRef(i, e, o, s),
        s
    }
    ,
    a.FromEulerVector = function(e) {
        var i = new a;
        return a.RotationYawPitchRollToRef(e._y, e._x, e._z, i),
        i
    }
    ,
    a.FromEulerVectorToRef = function(e, i) {
        return a.RotationYawPitchRollToRef(e._y, e._x, e._z, i),
        i
    }
    ,
    a.FromUnitVectorsToRef = function(e, i, o) {
        var s = Vector3.Dot(e, i) + 1;
        return s < Epsilon ? Math.abs(e.x) > Math.abs(e.z) ? o.set(-e.y, e.x, 0, 0) : o.set(0, -e.z, e.y, 0) : (Vector3.CrossToRef(e, i, TmpVectors.Vector3[0]),
        o.set(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z, s)),
        o.normalize()
    }
    ,
    a.RotationYawPitchRoll = function(e, i, o) {
        var s = new a;
        return a.RotationYawPitchRollToRef(e, i, o, s),
        s
    }
    ,
    a.RotationYawPitchRollToRef = function(e, i, o, s) {
        var c = o * .5
          , d = i * .5
          , _ = e * .5
          , b = Math.sin(c)
          , k = Math.cos(c)
          , j = Math.sin(d)
          , $ = Math.cos(d)
          , _e = Math.sin(_)
          , et = Math.cos(_);
        s.x = et * j * k + _e * $ * b,
        s.y = _e * $ * k - et * j * b,
        s.z = et * $ * b - _e * j * k,
        s.w = et * $ * k + _e * j * b
    }
    ,
    a.RotationAlphaBetaGamma = function(e, i, o) {
        var s = new a;
        return a.RotationAlphaBetaGammaToRef(e, i, o, s),
        s
    }
    ,
    a.RotationAlphaBetaGammaToRef = function(e, i, o, s) {
        var c = (o + e) * .5
          , d = (o - e) * .5
          , _ = i * .5;
        s.x = Math.cos(d) * Math.sin(_),
        s.y = Math.sin(d) * Math.sin(_),
        s.z = Math.sin(c) * Math.cos(_),
        s.w = Math.cos(c) * Math.cos(_)
    }
    ,
    a.RotationQuaternionFromAxis = function(e, i, o) {
        var s = new a(0,0,0,0);
        return a.RotationQuaternionFromAxisToRef(e, i, o, s),
        s
    }
    ,
    a.RotationQuaternionFromAxisToRef = function(e, i, o, s) {
        var c = MathTmp.Matrix[0];
        Matrix.FromXYZAxesToRef(e.normalize(), i.normalize(), o.normalize(), c),
        a.FromRotationMatrixToRef(c, s)
    }
    ,
    a.FromLookDirectionLH = function(e, i) {
        var o = new a;
        return a.FromLookDirectionLHToRef(e, i, o),
        o
    }
    ,
    a.FromLookDirectionLHToRef = function(e, i, o) {
        var s = MathTmp.Matrix[0];
        Matrix.LookDirectionLHToRef(e, i, s),
        a.FromRotationMatrixToRef(s, o)
    }
    ,
    a.FromLookDirectionRH = function(e, i) {
        var o = new a;
        return a.FromLookDirectionRHToRef(e, i, o),
        o
    }
    ,
    a.FromLookDirectionRHToRef = function(e, i, o) {
        var s = MathTmp.Matrix[0];
        return Matrix.LookDirectionRHToRef(e, i, s),
        a.FromRotationMatrixToRef(s, o)
    }
    ,
    a.Slerp = function(e, i, o) {
        var s = a.Identity();
        return a.SlerpToRef(e, i, o, s),
        s
    }
    ,
    a.SlerpToRef = function(e, i, o, s) {
        var c, d, _ = e._x * i._x + e._y * i._y + e._z * i._z + e._w * i._w, b = !1;
        if (_ < 0 && (b = !0,
        _ = -_),
        _ > .999999)
            d = 1 - o,
            c = b ? -o : o;
        else {
            var k = Math.acos(_)
              , j = 1 / Math.sin(k);
            d = Math.sin((1 - o) * k) * j,
            c = b ? -Math.sin(o * k) * j : Math.sin(o * k) * j
        }
        s.x = d * e._x + c * i._x,
        s.y = d * e._y + c * i._y,
        s.z = d * e._z + c * i._z,
        s.w = d * e._w + c * i._w
    }
    ,
    a.Hermite = function(e, i, o, s, c) {
        var d = c * c
          , _ = c * d
          , b = 2 * _ - 3 * d + 1
          , k = -2 * _ + 3 * d
          , j = _ - 2 * d + c
          , $ = _ - d
          , _e = e._x * b + o._x * k + i._x * j + s._x * $
          , et = e._y * b + o._y * k + i._y * j + s._y * $
          , tt = e._z * b + o._z * k + i._z * j + s._z * $
          , rt = e._w * b + o._w * k + i._w * j + s._w * $;
        return new a(_e,et,tt,rt)
    }
    ,
    a.Hermite1stDerivative = function(e, i, o, s, c) {
        var d = a.Zero();
        return this.Hermite1stDerivativeToRef(e, i, o, s, c, d),
        d
    }
    ,
    a.Hermite1stDerivativeToRef = function(e, i, o, s, c, d) {
        var _ = c * c;
        d.x = (_ - c) * 6 * e.x + (3 * _ - 4 * c + 1) * i.x + (-_ + c) * 6 * o.x + (3 * _ - 2 * c) * s.x,
        d.y = (_ - c) * 6 * e.y + (3 * _ - 4 * c + 1) * i.y + (-_ + c) * 6 * o.y + (3 * _ - 2 * c) * s.y,
        d.z = (_ - c) * 6 * e.z + (3 * _ - 4 * c + 1) * i.z + (-_ + c) * 6 * o.z + (3 * _ - 2 * c) * s.z,
        d.w = (_ - c) * 6 * e.w + (3 * _ - 4 * c + 1) * i.w + (-_ + c) * 6 * o.w + (3 * _ - 2 * c) * s.w
    }
    ,
    a
}()
  , Matrix = function() {
    function a() {
        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(a, "Use64Bits", {
        get: function() {
            return PerformanceConfigurator.MatrixUse64Bits
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "m", {
        get: function() {
            return this._m
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._markAsUpdated = function() {
        this.updateFlag = a._updateFlagSeed++,
        this._isIdentity = !1,
        this._isIdentity3x2 = !1,
        this._isIdentityDirty = !0,
        this._isIdentity3x2Dirty = !0
    }
    ,
    a.prototype._updateIdentityStatus = function(e, i, o, s) {
        i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        s === void 0 && (s = !0),
        this._isIdentity = e,
        this._isIdentity3x2 = e || o,
        this._isIdentityDirty = this._isIdentity ? !1 : i,
        this._isIdentity3x2Dirty = this._isIdentity3x2 ? !1 : s
    }
    ,
    a.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
    }
    ,
    a.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
    }
    ,
    a.prototype.determinant = function() {
        if (this._isIdentity === !0)
            return 1;
        var e = this._m
          , i = e[0]
          , o = e[1]
          , s = e[2]
          , c = e[3]
          , d = e[4]
          , _ = e[5]
          , b = e[6]
          , k = e[7]
          , j = e[8]
          , $ = e[9]
          , _e = e[10]
          , et = e[11]
          , tt = e[12]
          , rt = e[13]
          , it = e[14]
          , nt = e[15]
          , ot = _e * nt - it * et
          , at = $ * nt - rt * et
          , st = $ * it - rt * _e
          , ut = j * nt - tt * et
          , ct = j * it - _e * tt
          , lt = j * rt - tt * $
          , ft = +(_ * ot - b * at + k * st)
          , ht = -(d * ot - b * ut + k * ct)
          , pt = +(d * at - _ * ut + k * lt)
          , dt = -(d * st - _ * ct + b * lt);
        return i * ft + o * ht + s * pt + c * dt
    }
    ,
    a.prototype.toArray = function() {
        return this._m
    }
    ,
    a.prototype.asArray = function() {
        return this._m
    }
    ,
    a.prototype.invert = function() {
        return this.invertToRef(this),
        this
    }
    ,
    a.prototype.reset = function() {
        return a.FromValuesToRef(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, this),
        this._updateIdentityStatus(!1),
        this
    }
    ,
    a.prototype.add = function(e) {
        var i = new a;
        return this.addToRef(e, i),
        i
    }
    ,
    a.prototype.addToRef = function(e, i) {
        for (var o = this._m, s = i._m, c = e.m, d = 0; d < 16; d++)
            s[d] = o[d] + c[d];
        return i._markAsUpdated(),
        this
    }
    ,
    a.prototype.addToSelf = function(e) {
        for (var i = this._m, o = e.m, s = 0; s < 16; s++)
            i[s] += o[s];
        return this._markAsUpdated(),
        this
    }
    ,
    a.prototype.invertToRef = function(e) {
        if (this._isIdentity === !0)
            return a.IdentityToRef(e),
            this;
        var i = this._m
          , o = i[0]
          , s = i[1]
          , c = i[2]
          , d = i[3]
          , _ = i[4]
          , b = i[5]
          , k = i[6]
          , j = i[7]
          , $ = i[8]
          , _e = i[9]
          , et = i[10]
          , tt = i[11]
          , rt = i[12]
          , it = i[13]
          , nt = i[14]
          , ot = i[15]
          , at = et * ot - nt * tt
          , st = _e * ot - it * tt
          , ut = _e * nt - it * et
          , ct = $ * ot - rt * tt
          , lt = $ * nt - et * rt
          , ft = $ * it - rt * _e
          , ht = +(b * at - k * st + j * ut)
          , pt = -(_ * at - k * ct + j * lt)
          , dt = +(_ * st - b * ct + j * ft)
          , _t = -(_ * ut - b * lt + k * ft)
          , mt = o * ht + s * pt + c * dt + d * _t;
        if (mt === 0)
            return e.copyFrom(this),
            this;
        var vt = 1 / mt
          , yt = k * ot - nt * j
          , Et = b * ot - it * j
          , At = b * nt - it * k
          , gt = _ * ot - rt * j
          , St = _ * nt - rt * k
          , xt = _ * it - rt * b
          , bt = k * tt - et * j
          , Rt = b * tt - _e * j
          , Mt = b * et - _e * k
          , Pt = _ * tt - $ * j
          , It = _ * et - $ * k
          , Dt = _ * _e - $ * b
          , Ct = -(s * at - c * st + d * ut)
          , Ot = +(o * at - c * ct + d * lt)
          , wt = -(o * st - s * ct + d * ft)
          , Nt = +(o * ut - s * lt + c * ft)
          , Ft = +(s * yt - c * Et + d * At)
          , Vt = -(o * yt - c * gt + d * St)
          , Lt = +(o * Et - s * gt + d * xt)
          , kt = -(o * At - s * St + c * xt)
          , Bt = -(s * bt - c * Rt + d * Mt)
          , Ut = +(o * bt - c * Pt + d * It)
          , Gt = -(o * Rt - s * Pt + d * Dt)
          , Ht = +(o * Mt - s * It + c * Dt);
        return a.FromValuesToRef(ht * vt, Ct * vt, Ft * vt, Bt * vt, pt * vt, Ot * vt, Vt * vt, Ut * vt, dt * vt, wt * vt, Lt * vt, Gt * vt, _t * vt, Nt * vt, kt * vt, Ht * vt, e),
        this
    }
    ,
    a.prototype.addAtIndex = function(e, i) {
        return this._m[e] += i,
        this._markAsUpdated(),
        this
    }
    ,
    a.prototype.multiplyAtIndex = function(e, i) {
        return this._m[e] *= i,
        this._markAsUpdated(),
        this
    }
    ,
    a.prototype.setTranslationFromFloats = function(e, i, o) {
        return this._m[12] = e,
        this._m[13] = i,
        this._m[14] = o,
        this._markAsUpdated(),
        this
    }
    ,
    a.prototype.addTranslationFromFloats = function(e, i, o) {
        return this._m[12] += e,
        this._m[13] += i,
        this._m[14] += o,
        this._markAsUpdated(),
        this
    }
    ,
    a.prototype.setTranslation = function(e) {
        return this.setTranslationFromFloats(e._x, e._y, e._z)
    }
    ,
    a.prototype.getTranslation = function() {
        return new Vector3(this._m[12],this._m[13],this._m[14])
    }
    ,
    a.prototype.getTranslationToRef = function(e) {
        return e.x = this._m[12],
        e.y = this._m[13],
        e.z = this._m[14],
        this
    }
    ,
    a.prototype.removeRotationAndScaling = function() {
        var e = this.m;
        return a.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
    }
    ,
    a.prototype.multiply = function(e) {
        var i = new a;
        return this.multiplyToRef(e, i),
        i
    }
    ,
    a.prototype.copyFrom = function(e) {
        e.copyToArray(this._m);
        var i = e;
        return this.updateFlag = i.updateFlag,
        this._updateIdentityStatus(i._isIdentity, i._isIdentityDirty, i._isIdentity3x2, i._isIdentity3x2Dirty),
        this
    }
    ,
    a.prototype.copyToArray = function(e, i) {
        i === void 0 && (i = 0);
        var o = this._m;
        return e[i] = o[0],
        e[i + 1] = o[1],
        e[i + 2] = o[2],
        e[i + 3] = o[3],
        e[i + 4] = o[4],
        e[i + 5] = o[5],
        e[i + 6] = o[6],
        e[i + 7] = o[7],
        e[i + 8] = o[8],
        e[i + 9] = o[9],
        e[i + 10] = o[10],
        e[i + 11] = o[11],
        e[i + 12] = o[12],
        e[i + 13] = o[13],
        e[i + 14] = o[14],
        e[i + 15] = o[15],
        this
    }
    ,
    a.prototype.multiplyToRef = function(e, i) {
        return this._isIdentity ? (i.copyFrom(e),
        this) : e._isIdentity ? (i.copyFrom(this),
        this) : (this.multiplyToArray(e, i._m, 0),
        i._markAsUpdated(),
        this)
    }
    ,
    a.prototype.multiplyToArray = function(e, i, o) {
        var s = this._m
          , c = e.m
          , d = s[0]
          , _ = s[1]
          , b = s[2]
          , k = s[3]
          , j = s[4]
          , $ = s[5]
          , _e = s[6]
          , et = s[7]
          , tt = s[8]
          , rt = s[9]
          , it = s[10]
          , nt = s[11]
          , ot = s[12]
          , at = s[13]
          , st = s[14]
          , ut = s[15]
          , ct = c[0]
          , lt = c[1]
          , ft = c[2]
          , ht = c[3]
          , pt = c[4]
          , dt = c[5]
          , _t = c[6]
          , mt = c[7]
          , vt = c[8]
          , yt = c[9]
          , Et = c[10]
          , At = c[11]
          , gt = c[12]
          , St = c[13]
          , xt = c[14]
          , bt = c[15];
        return i[o] = d * ct + _ * pt + b * vt + k * gt,
        i[o + 1] = d * lt + _ * dt + b * yt + k * St,
        i[o + 2] = d * ft + _ * _t + b * Et + k * xt,
        i[o + 3] = d * ht + _ * mt + b * At + k * bt,
        i[o + 4] = j * ct + $ * pt + _e * vt + et * gt,
        i[o + 5] = j * lt + $ * dt + _e * yt + et * St,
        i[o + 6] = j * ft + $ * _t + _e * Et + et * xt,
        i[o + 7] = j * ht + $ * mt + _e * At + et * bt,
        i[o + 8] = tt * ct + rt * pt + it * vt + nt * gt,
        i[o + 9] = tt * lt + rt * dt + it * yt + nt * St,
        i[o + 10] = tt * ft + rt * _t + it * Et + nt * xt,
        i[o + 11] = tt * ht + rt * mt + it * At + nt * bt,
        i[o + 12] = ot * ct + at * pt + st * vt + ut * gt,
        i[o + 13] = ot * lt + at * dt + st * yt + ut * St,
        i[o + 14] = ot * ft + at * _t + st * Et + ut * xt,
        i[o + 15] = ot * ht + at * mt + st * At + ut * bt,
        this
    }
    ,
    a.prototype.equals = function(e) {
        var i = e;
        if (!i)
            return !1;
        if ((this._isIdentity || i._isIdentity) && !this._isIdentityDirty && !i._isIdentityDirty)
            return this._isIdentity && i._isIdentity;
        var o = this.m
          , s = i.m;
        return o[0] === s[0] && o[1] === s[1] && o[2] === s[2] && o[3] === s[3] && o[4] === s[4] && o[5] === s[5] && o[6] === s[6] && o[7] === s[7] && o[8] === s[8] && o[9] === s[9] && o[10] === s[10] && o[11] === s[11] && o[12] === s[12] && o[13] === s[13] && o[14] === s[14] && o[15] === s[15]
    }
    ,
    a.prototype.clone = function() {
        var e = new a;
        return e.copyFrom(this),
        e
    }
    ,
    a.prototype.getClassName = function() {
        return "Matrix"
    }
    ,
    a.prototype.getHashCode = function() {
        for (var e = this._m[0] | 0, i = 1; i < 16; i++)
            e = e * 397 ^ (this._m[i] | 0);
        return e
    }
    ,
    a.prototype.decomposeToTransformNode = function(e) {
        return e.rotationQuaternion = e.rotationQuaternion || new Quaternion,
        this.decompose(e.scaling, e.rotationQuaternion, e.position)
    }
    ,
    a.prototype.decompose = function(e, i, o, s) {
        if (this._isIdentity)
            return o && o.setAll(0),
            e && e.setAll(1),
            i && i.copyFromFloats(0, 0, 0, 1),
            !0;
        var c = this._m;
        if (o && o.copyFromFloats(c[12], c[13], c[14]),
        e = e || MathTmp.Vector3[0],
        e.x = Math.sqrt(c[0] * c[0] + c[1] * c[1] + c[2] * c[2]),
        e.y = Math.sqrt(c[4] * c[4] + c[5] * c[5] + c[6] * c[6]),
        e.z = Math.sqrt(c[8] * c[8] + c[9] * c[9] + c[10] * c[10]),
        s) {
            var d = s.scaling.x < 0 ? -1 : 1
              , _ = s.scaling.y < 0 ? -1 : 1
              , b = s.scaling.z < 0 ? -1 : 1;
            e.x *= d,
            e.y *= _,
            e.z *= b
        } else
            this.determinant() <= 0 && (e.y *= -1);
        if (e._x === 0 || e._y === 0 || e._z === 0)
            return i && i.copyFromFloats(0, 0, 0, 1),
            !1;
        if (i) {
            var k = 1 / e._x
              , j = 1 / e._y
              , $ = 1 / e._z;
            a.FromValuesToRef(c[0] * k, c[1] * k, c[2] * k, 0, c[4] * j, c[5] * j, c[6] * j, 0, c[8] * $, c[9] * $, c[10] * $, 0, 0, 0, 0, 1, MathTmp.Matrix[0]),
            Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], i)
        }
        return !0
    }
    ,
    a.prototype.getRow = function(e) {
        if (e < 0 || e > 3)
            return null;
        var i = e * 4;
        return new Vector4(this._m[i + 0],this._m[i + 1],this._m[i + 2],this._m[i + 3])
    }
    ,
    a.prototype.setRow = function(e, i) {
        return this.setRowFromFloats(e, i.x, i.y, i.z, i.w)
    }
    ,
    a.prototype.transpose = function() {
        return a.Transpose(this)
    }
    ,
    a.prototype.transposeToRef = function(e) {
        return a.TransposeToRef(this, e),
        this
    }
    ,
    a.prototype.setRowFromFloats = function(e, i, o, s, c) {
        if (e < 0 || e > 3)
            return this;
        var d = e * 4;
        return this._m[d + 0] = i,
        this._m[d + 1] = o,
        this._m[d + 2] = s,
        this._m[d + 3] = c,
        this._markAsUpdated(),
        this
    }
    ,
    a.prototype.scale = function(e) {
        var i = new a;
        return this.scaleToRef(e, i),
        i
    }
    ,
    a.prototype.scaleToRef = function(e, i) {
        for (var o = 0; o < 16; o++)
            i._m[o] = this._m[o] * e;
        return i._markAsUpdated(),
        this
    }
    ,
    a.prototype.scaleAndAddToRef = function(e, i) {
        for (var o = 0; o < 16; o++)
            i._m[o] += this._m[o] * e;
        return i._markAsUpdated(),
        this
    }
    ,
    a.prototype.toNormalMatrix = function(e) {
        var i = MathTmp.Matrix[0];
        this.invertToRef(i),
        i.transposeToRef(e);
        var o = e._m;
        a.FromValuesToRef(o[0], o[1], o[2], 0, o[4], o[5], o[6], 0, o[8], o[9], o[10], 0, 0, 0, 0, 1, e)
    }
    ,
    a.prototype.getRotationMatrix = function() {
        var e = new a;
        return this.getRotationMatrixToRef(e),
        e
    }
    ,
    a.prototype.getRotationMatrixToRef = function(e) {
        var i = MathTmp.Vector3[0];
        if (!this.decompose(i))
            return a.IdentityToRef(e),
            this;
        var o = this._m
          , s = 1 / i._x
          , c = 1 / i._y
          , d = 1 / i._z;
        return a.FromValuesToRef(o[0] * s, o[1] * s, o[2] * s, 0, o[4] * c, o[5] * c, o[6] * c, 0, o[8] * d, o[9] * d, o[10] * d, 0, 0, 0, 0, 1, e),
        this
    }
    ,
    a.prototype.toggleModelMatrixHandInPlace = function() {
        var e = this._m;
        e[2] *= -1,
        e[6] *= -1,
        e[8] *= -1,
        e[9] *= -1,
        e[14] *= -1,
        this._markAsUpdated()
    }
    ,
    a.prototype.toggleProjectionMatrixHandInPlace = function() {
        var e = this._m;
        e[8] *= -1,
        e[9] *= -1,
        e[10] *= -1,
        e[11] *= -1,
        this._markAsUpdated()
    }
    ,
    a.FromArray = function(e, i) {
        i === void 0 && (i = 0);
        var o = new a;
        return a.FromArrayToRef(e, i, o),
        o
    }
    ,
    a.FromArrayToRef = function(e, i, o) {
        for (var s = 0; s < 16; s++)
            o._m[s] = e[s + i];
        o._markAsUpdated()
    }
    ,
    a.FromFloat32ArrayToRefScaled = function(e, i, o, s) {
        for (var c = 0; c < 16; c++)
            s._m[c] = e[c + i] * o;
        s._markAsUpdated()
    }
    ,
    Object.defineProperty(a, "IdentityReadOnly", {
        get: function() {
            return a._identityReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    a.FromValuesToRef = function(e, i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it, nt) {
        var ot = nt._m;
        ot[0] = e,
        ot[1] = i,
        ot[2] = o,
        ot[3] = s,
        ot[4] = c,
        ot[5] = d,
        ot[6] = _,
        ot[7] = b,
        ot[8] = k,
        ot[9] = j,
        ot[10] = $,
        ot[11] = _e,
        ot[12] = et,
        ot[13] = tt,
        ot[14] = rt,
        ot[15] = it,
        nt._markAsUpdated()
    }
    ,
    a.FromValues = function(e, i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it) {
        var nt = new a
          , ot = nt._m;
        return ot[0] = e,
        ot[1] = i,
        ot[2] = o,
        ot[3] = s,
        ot[4] = c,
        ot[5] = d,
        ot[6] = _,
        ot[7] = b,
        ot[8] = k,
        ot[9] = j,
        ot[10] = $,
        ot[11] = _e,
        ot[12] = et,
        ot[13] = tt,
        ot[14] = rt,
        ot[15] = it,
        nt._markAsUpdated(),
        nt
    }
    ,
    a.Compose = function(e, i, o) {
        var s = new a;
        return a.ComposeToRef(e, i, o, s),
        s
    }
    ,
    a.ComposeToRef = function(e, i, o, s) {
        var c = s._m
          , d = i._x
          , _ = i._y
          , b = i._z
          , k = i._w
          , j = d + d
          , $ = _ + _
          , _e = b + b
          , et = d * j
          , tt = d * $
          , rt = d * _e
          , it = _ * $
          , nt = _ * _e
          , ot = b * _e
          , at = k * j
          , st = k * $
          , ut = k * _e
          , ct = e._x
          , lt = e._y
          , ft = e._z;
        c[0] = (1 - (it + ot)) * ct,
        c[1] = (tt + ut) * ct,
        c[2] = (rt - st) * ct,
        c[3] = 0,
        c[4] = (tt - ut) * lt,
        c[5] = (1 - (et + ot)) * lt,
        c[6] = (nt + at) * lt,
        c[7] = 0,
        c[8] = (rt + st) * ft,
        c[9] = (nt - at) * ft,
        c[10] = (1 - (et + it)) * ft,
        c[11] = 0,
        c[12] = o._x,
        c[13] = o._y,
        c[14] = o._z,
        c[15] = 1,
        s._markAsUpdated()
    }
    ,
    a.Identity = function() {
        var e = a.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
        return e._updateIdentityStatus(!0),
        e
    }
    ,
    a.IdentityToRef = function(e) {
        a.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, e),
        e._updateIdentityStatus(!0)
    }
    ,
    a.Zero = function() {
        var e = a.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        return e._updateIdentityStatus(!1),
        e
    }
    ,
    a.RotationX = function(e) {
        var i = new a;
        return a.RotationXToRef(e, i),
        i
    }
    ,
    a.Invert = function(e) {
        var i = new a;
        return e.invertToRef(i),
        i
    }
    ,
    a.RotationXToRef = function(e, i) {
        var o = Math.sin(e)
          , s = Math.cos(e);
        a.FromValuesToRef(1, 0, 0, 0, 0, s, o, 0, 0, -o, s, 0, 0, 0, 0, 1, i),
        i._updateIdentityStatus(s === 1 && o === 0)
    }
    ,
    a.RotationY = function(e) {
        var i = new a;
        return a.RotationYToRef(e, i),
        i
    }
    ,
    a.RotationYToRef = function(e, i) {
        var o = Math.sin(e)
          , s = Math.cos(e);
        a.FromValuesToRef(s, 0, -o, 0, 0, 1, 0, 0, o, 0, s, 0, 0, 0, 0, 1, i),
        i._updateIdentityStatus(s === 1 && o === 0)
    }
    ,
    a.RotationZ = function(e) {
        var i = new a;
        return a.RotationZToRef(e, i),
        i
    }
    ,
    a.RotationZToRef = function(e, i) {
        var o = Math.sin(e)
          , s = Math.cos(e);
        a.FromValuesToRef(s, o, 0, 0, -o, s, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, i),
        i._updateIdentityStatus(s === 1 && o === 0)
    }
    ,
    a.RotationAxis = function(e, i) {
        var o = new a;
        return a.RotationAxisToRef(e, i, o),
        o
    }
    ,
    a.RotationAxisToRef = function(e, i, o) {
        var s = Math.sin(-i)
          , c = Math.cos(-i)
          , d = 1 - c;
        e.normalize();
        var _ = o._m;
        _[0] = e._x * e._x * d + c,
        _[1] = e._x * e._y * d - e._z * s,
        _[2] = e._x * e._z * d + e._y * s,
        _[3] = 0,
        _[4] = e._y * e._x * d + e._z * s,
        _[5] = e._y * e._y * d + c,
        _[6] = e._y * e._z * d - e._x * s,
        _[7] = 0,
        _[8] = e._z * e._x * d - e._y * s,
        _[9] = e._z * e._y * d + e._x * s,
        _[10] = e._z * e._z * d + c,
        _[11] = 0,
        _[12] = 0,
        _[13] = 0,
        _[14] = 0,
        _[15] = 1,
        o._markAsUpdated()
    }
    ,
    a.RotationAlignToRef = function(e, i, o) {
        var s = Vector3.Dot(i, e)
          , c = o._m;
        if (s < -1 + Epsilon)
            c[0] = -1,
            c[1] = 0,
            c[2] = 0,
            c[3] = 0,
            c[4] = 0,
            c[5] = -1,
            c[6] = 0,
            c[7] = 0,
            c[8] = 0,
            c[9] = 0,
            c[10] = 1,
            c[11] = 0;
        else {
            var d = Vector3.Cross(i, e)
              , _ = 1 / (1 + s);
            c[0] = d._x * d._x * _ + s,
            c[1] = d._y * d._x * _ - d._z,
            c[2] = d._z * d._x * _ + d._y,
            c[3] = 0,
            c[4] = d._x * d._y * _ + d._z,
            c[5] = d._y * d._y * _ + s,
            c[6] = d._z * d._y * _ - d._x,
            c[7] = 0,
            c[8] = d._x * d._z * _ - d._y,
            c[9] = d._y * d._z * _ + d._x,
            c[10] = d._z * d._z * _ + s,
            c[11] = 0
        }
        c[12] = 0,
        c[13] = 0,
        c[14] = 0,
        c[15] = 1,
        o._markAsUpdated()
    }
    ,
    a.RotationYawPitchRoll = function(e, i, o) {
        var s = new a;
        return a.RotationYawPitchRollToRef(e, i, o, s),
        s
    }
    ,
    a.RotationYawPitchRollToRef = function(e, i, o, s) {
        Quaternion.RotationYawPitchRollToRef(e, i, o, MathTmp.Quaternion[0]),
        MathTmp.Quaternion[0].toRotationMatrix(s)
    }
    ,
    a.Scaling = function(e, i, o) {
        var s = new a;
        return a.ScalingToRef(e, i, o, s),
        s
    }
    ,
    a.ScalingToRef = function(e, i, o, s) {
        a.FromValuesToRef(e, 0, 0, 0, 0, i, 0, 0, 0, 0, o, 0, 0, 0, 0, 1, s),
        s._updateIdentityStatus(e === 1 && i === 1 && o === 1)
    }
    ,
    a.Translation = function(e, i, o) {
        var s = new a;
        return a.TranslationToRef(e, i, o, s),
        s
    }
    ,
    a.TranslationToRef = function(e, i, o, s) {
        a.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, e, i, o, 1, s),
        s._updateIdentityStatus(e === 0 && i === 0 && o === 0)
    }
    ,
    a.Lerp = function(e, i, o) {
        var s = new a;
        return a.LerpToRef(e, i, o, s),
        s
    }
    ,
    a.LerpToRef = function(e, i, o, s) {
        for (var c = s._m, d = e.m, _ = i.m, b = 0; b < 16; b++)
            c[b] = d[b] * (1 - o) + _[b] * o;
        s._markAsUpdated()
    }
    ,
    a.DecomposeLerp = function(e, i, o) {
        var s = new a;
        return a.DecomposeLerpToRef(e, i, o, s),
        s
    }
    ,
    a.DecomposeLerpToRef = function(e, i, o, s) {
        var c = MathTmp.Vector3[0]
          , d = MathTmp.Quaternion[0]
          , _ = MathTmp.Vector3[1];
        e.decompose(c, d, _);
        var b = MathTmp.Vector3[2]
          , k = MathTmp.Quaternion[1]
          , j = MathTmp.Vector3[3];
        i.decompose(b, k, j);
        var $ = MathTmp.Vector3[4];
        Vector3.LerpToRef(c, b, o, $);
        var _e = MathTmp.Quaternion[2];
        Quaternion.SlerpToRef(d, k, o, _e);
        var et = MathTmp.Vector3[5];
        Vector3.LerpToRef(_, j, o, et),
        a.ComposeToRef($, _e, et, s)
    }
    ,
    a.LookAtLH = function(e, i, o) {
        var s = new a;
        return a.LookAtLHToRef(e, i, o, s),
        s
    }
    ,
    a.LookAtLHToRef = function(e, i, o, s) {
        var c = MathTmp.Vector3[0]
          , d = MathTmp.Vector3[1]
          , _ = MathTmp.Vector3[2];
        i.subtractToRef(e, _),
        _.normalize(),
        Vector3.CrossToRef(o, _, c);
        var b = c.lengthSquared();
        b === 0 ? c.x = 1 : c.normalizeFromLength(Math.sqrt(b)),
        Vector3.CrossToRef(_, c, d),
        d.normalize();
        var k = -Vector3.Dot(c, e)
          , j = -Vector3.Dot(d, e)
          , $ = -Vector3.Dot(_, e);
        a.FromValuesToRef(c._x, d._x, _._x, 0, c._y, d._y, _._y, 0, c._z, d._z, _._z, 0, k, j, $, 1, s)
    }
    ,
    a.LookAtRH = function(e, i, o) {
        var s = new a;
        return a.LookAtRHToRef(e, i, o, s),
        s
    }
    ,
    a.LookAtRHToRef = function(e, i, o, s) {
        var c = MathTmp.Vector3[0]
          , d = MathTmp.Vector3[1]
          , _ = MathTmp.Vector3[2];
        e.subtractToRef(i, _),
        _.normalize(),
        Vector3.CrossToRef(o, _, c);
        var b = c.lengthSquared();
        b === 0 ? c.x = 1 : c.normalizeFromLength(Math.sqrt(b)),
        Vector3.CrossToRef(_, c, d),
        d.normalize();
        var k = -Vector3.Dot(c, e)
          , j = -Vector3.Dot(d, e)
          , $ = -Vector3.Dot(_, e);
        a.FromValuesToRef(c._x, d._x, _._x, 0, c._y, d._y, _._y, 0, c._z, d._z, _._z, 0, k, j, $, 1, s)
    }
    ,
    a.LookDirectionLH = function(e, i) {
        var o = new a;
        return a.LookDirectionLHToRef(e, i, o),
        o
    }
    ,
    a.LookDirectionLHToRef = function(e, i, o) {
        var s = MathTmp.Vector3[0];
        s.copyFrom(e),
        s.scaleInPlace(-1);
        var c = MathTmp.Vector3[1];
        Vector3.CrossToRef(i, s, c),
        a.FromValuesToRef(c._x, c._y, c._z, 0, i._x, i._y, i._z, 0, s._x, s._y, s._z, 0, 0, 0, 0, 1, o)
    }
    ,
    a.LookDirectionRH = function(e, i) {
        var o = new a;
        return a.LookDirectionRHToRef(e, i, o),
        o
    }
    ,
    a.LookDirectionRHToRef = function(e, i, o) {
        var s = MathTmp.Vector3[2];
        Vector3.CrossToRef(i, e, s),
        a.FromValuesToRef(s._x, s._y, s._z, 0, i._x, i._y, i._z, 0, e._x, e._y, e._z, 0, 0, 0, 0, 1, o)
    }
    ,
    a.OrthoLH = function(e, i, o, s, c) {
        var d = new a;
        return a.OrthoLHToRef(e, i, o, s, d, c),
        d
    }
    ,
    a.OrthoLHToRef = function(e, i, o, s, c, d) {
        var _ = o
          , b = s
          , k = 2 / e
          , j = 2 / i
          , $ = 2 / (b - _)
          , _e = -(b + _) / (b - _);
        a.FromValuesToRef(k, 0, 0, 0, 0, j, 0, 0, 0, 0, $, 0, 0, 0, _e, 1, c),
        d && c.multiplyToRef(mtxConvertNDCToHalfZRange, c),
        c._updateIdentityStatus(k === 1 && j === 1 && $ === 1 && _e === 0)
    }
    ,
    a.OrthoOffCenterLH = function(e, i, o, s, c, d, _) {
        var b = new a;
        return a.OrthoOffCenterLHToRef(e, i, o, s, c, d, b, _),
        b
    }
    ,
    a.OrthoOffCenterLHToRef = function(e, i, o, s, c, d, _, b) {
        var k = c
          , j = d
          , $ = 2 / (i - e)
          , _e = 2 / (s - o)
          , et = 2 / (j - k)
          , tt = -(j + k) / (j - k)
          , rt = (e + i) / (e - i)
          , it = (s + o) / (o - s);
        a.FromValuesToRef($, 0, 0, 0, 0, _e, 0, 0, 0, 0, et, 0, rt, it, tt, 1, _),
        b && _.multiplyToRef(mtxConvertNDCToHalfZRange, _),
        _._markAsUpdated()
    }
    ,
    a.OrthoOffCenterRH = function(e, i, o, s, c, d, _) {
        var b = new a;
        return a.OrthoOffCenterRHToRef(e, i, o, s, c, d, b, _),
        b
    }
    ,
    a.OrthoOffCenterRHToRef = function(e, i, o, s, c, d, _, b) {
        a.OrthoOffCenterLHToRef(e, i, o, s, c, d, _, b),
        _._m[10] *= -1
    }
    ,
    a.PerspectiveLH = function(e, i, o, s, c, d) {
        d === void 0 && (d = 0);
        var _ = new a
          , b = o
          , k = s
          , j = 2 * b / e
          , $ = 2 * b / i
          , _e = (k + b) / (k - b)
          , et = -2 * k * b / (k - b)
          , tt = Math.tan(d);
        return a.FromValuesToRef(j, 0, 0, 0, 0, $, 0, tt, 0, 0, _e, 1, 0, 0, et, 0, _),
        c && _.multiplyToRef(mtxConvertNDCToHalfZRange, _),
        _._updateIdentityStatus(!1),
        _
    }
    ,
    a.PerspectiveFovLH = function(e, i, o, s, c, d, _) {
        d === void 0 && (d = 0),
        _ === void 0 && (_ = !1);
        var b = new a;
        return a.PerspectiveFovLHToRef(e, i, o, s, b, !0, c, d, _),
        b
    }
    ,
    a.PerspectiveFovLHToRef = function(e, i, o, s, c, d, _, b, k) {
        d === void 0 && (d = !0),
        b === void 0 && (b = 0),
        k === void 0 && (k = !1);
        var j = o
          , $ = s
          , _e = 1 / Math.tan(e * .5)
          , et = d ? _e / i : _e
          , tt = d ? _e : _e * i
          , rt = k && j === 0 ? -1 : $ !== 0 ? ($ + j) / ($ - j) : 1
          , it = k && j === 0 ? 2 * $ : $ !== 0 ? -2 * $ * j / ($ - j) : -2 * j
          , nt = Math.tan(b);
        a.FromValuesToRef(et, 0, 0, 0, 0, tt, 0, nt, 0, 0, rt, 1, 0, 0, it, 0, c),
        _ && c.multiplyToRef(mtxConvertNDCToHalfZRange, c),
        c._updateIdentityStatus(!1)
    }
    ,
    a.PerspectiveFovReverseLHToRef = function(e, i, o, s, c, d, _, b) {
        d === void 0 && (d = !0),
        b === void 0 && (b = 0);
        var k = 1 / Math.tan(e * .5)
          , j = d ? k / i : k
          , $ = d ? k : k * i
          , _e = Math.tan(b);
        a.FromValuesToRef(j, 0, 0, 0, 0, $, 0, _e, 0, 0, -o, 1, 0, 0, 1, 0, c),
        _ && c.multiplyToRef(mtxConvertNDCToHalfZRange, c),
        c._updateIdentityStatus(!1)
    }
    ,
    a.PerspectiveFovRH = function(e, i, o, s, c, d, _) {
        d === void 0 && (d = 0),
        _ === void 0 && (_ = !1);
        var b = new a;
        return a.PerspectiveFovRHToRef(e, i, o, s, b, !0, c, d, _),
        b
    }
    ,
    a.PerspectiveFovRHToRef = function(e, i, o, s, c, d, _, b, k) {
        d === void 0 && (d = !0),
        b === void 0 && (b = 0),
        k === void 0 && (k = !1);
        var j = o
          , $ = s
          , _e = 1 / Math.tan(e * .5)
          , et = d ? _e / i : _e
          , tt = d ? _e : _e * i
          , rt = k && j === 0 ? 1 : $ !== 0 ? -($ + j) / ($ - j) : -1
          , it = k && j === 0 ? 2 * $ : $ !== 0 ? -2 * $ * j / ($ - j) : -2 * j
          , nt = Math.tan(b);
        a.FromValuesToRef(et, 0, 0, 0, 0, tt, 0, nt, 0, 0, rt, -1, 0, 0, it, 0, c),
        _ && c.multiplyToRef(mtxConvertNDCToHalfZRange, c),
        c._updateIdentityStatus(!1)
    }
    ,
    a.PerspectiveFovReverseRHToRef = function(e, i, o, s, c, d, _, b) {
        d === void 0 && (d = !0),
        b === void 0 && (b = 0);
        var k = 1 / Math.tan(e * .5)
          , j = d ? k / i : k
          , $ = d ? k : k * i
          , _e = Math.tan(b);
        a.FromValuesToRef(j, 0, 0, 0, 0, $, 0, _e, 0, 0, -o, -1, 0, 0, -1, 0, c),
        _ && c.multiplyToRef(mtxConvertNDCToHalfZRange, c),
        c._updateIdentityStatus(!1)
    }
    ,
    a.PerspectiveFovWebVRToRef = function(e, i, o, s, c, d, _) {
        c === void 0 && (c = !1),
        _ === void 0 && (_ = 0);
        var b = c ? -1 : 1
          , k = Math.tan(e.upDegrees * Math.PI / 180)
          , j = Math.tan(e.downDegrees * Math.PI / 180)
          , $ = Math.tan(e.leftDegrees * Math.PI / 180)
          , _e = Math.tan(e.rightDegrees * Math.PI / 180)
          , et = 2 / ($ + _e)
          , tt = 2 / (k + j)
          , rt = Math.tan(_)
          , it = s._m;
        it[0] = et,
        it[1] = it[2] = it[3] = it[4] = 0,
        it[5] = tt,
        it[6] = 0,
        it[7] = rt,
        it[8] = ($ - _e) * et * .5,
        it[9] = -((k - j) * tt * .5),
        it[10] = -o / (i - o),
        it[11] = 1 * b,
        it[12] = it[13] = it[15] = 0,
        it[14] = -(2 * o * i) / (o - i),
        d && s.multiplyToRef(mtxConvertNDCToHalfZRange, s),
        s._markAsUpdated()
    }
    ,
    a.GetFinalMatrix = function(e, i, o, s, c, d) {
        var _ = e.width
          , b = e.height
          , k = e.x
          , j = e.y
          , $ = a.FromValues(_ / 2, 0, 0, 0, 0, -b / 2, 0, 0, 0, 0, d - c, 0, k + _ / 2, b / 2 + j, c, 1)
          , _e = MathTmp.Matrix[0];
        return i.multiplyToRef(o, _e),
        _e.multiplyToRef(s, _e),
        _e.multiply($)
    }
    ,
    a.GetAsMatrix2x2 = function(e) {
        var i = e.m
          , o = [i[0], i[1], i[4], i[5]];
        return PerformanceConfigurator.MatrixUse64Bits ? o : new Float32Array(o)
    }
    ,
    a.GetAsMatrix3x3 = function(e) {
        var i = e.m
          , o = [i[0], i[1], i[2], i[4], i[5], i[6], i[8], i[9], i[10]];
        return PerformanceConfigurator.MatrixUse64Bits ? o : new Float32Array(o)
    }
    ,
    a.Transpose = function(e) {
        var i = new a;
        return a.TransposeToRef(e, i),
        i
    }
    ,
    a.TransposeToRef = function(e, i) {
        var o = i._m
          , s = e.m;
        o[0] = s[0],
        o[1] = s[4],
        o[2] = s[8],
        o[3] = s[12],
        o[4] = s[1],
        o[5] = s[5],
        o[6] = s[9],
        o[7] = s[13],
        o[8] = s[2],
        o[9] = s[6],
        o[10] = s[10],
        o[11] = s[14],
        o[12] = s[3],
        o[13] = s[7],
        o[14] = s[11],
        o[15] = s[15],
        i._markAsUpdated(),
        i._updateIdentityStatus(e._isIdentity, e._isIdentityDirty)
    }
    ,
    a.Reflection = function(e) {
        var i = new a;
        return a.ReflectionToRef(e, i),
        i
    }
    ,
    a.ReflectionToRef = function(e, i) {
        e.normalize();
        var o = e.normal.x
          , s = e.normal.y
          , c = e.normal.z
          , d = -2 * o
          , _ = -2 * s
          , b = -2 * c;
        a.FromValuesToRef(d * o + 1, _ * o, b * o, 0, d * s, _ * s + 1, b * s, 0, d * c, _ * c, b * c + 1, 0, d * e.d, _ * e.d, b * e.d, 1, i)
    }
    ,
    a.FromXYZAxesToRef = function(e, i, o, s) {
        a.FromValuesToRef(e._x, e._y, e._z, 0, i._x, i._y, i._z, 0, o._x, o._y, o._z, 0, 0, 0, 0, 1, s)
    }
    ,
    a.FromQuaternionToRef = function(e, i) {
        var o = e._x * e._x
          , s = e._y * e._y
          , c = e._z * e._z
          , d = e._x * e._y
          , _ = e._z * e._w
          , b = e._z * e._x
          , k = e._y * e._w
          , j = e._y * e._z
          , $ = e._x * e._w;
        i._m[0] = 1 - 2 * (s + c),
        i._m[1] = 2 * (d + _),
        i._m[2] = 2 * (b - k),
        i._m[3] = 0,
        i._m[4] = 2 * (d - _),
        i._m[5] = 1 - 2 * (c + o),
        i._m[6] = 2 * (j + $),
        i._m[7] = 0,
        i._m[8] = 2 * (b + k),
        i._m[9] = 2 * (j - $),
        i._m[10] = 1 - 2 * (s + o),
        i._m[11] = 0,
        i._m[12] = 0,
        i._m[13] = 0,
        i._m[14] = 0,
        i._m[15] = 1,
        i._markAsUpdated()
    }
    ,
    a._updateFlagSeed = 0,
    a._identityReadOnly = a.Identity(),
    a
}()
  , MathTmp = function() {
    function a() {}
    return a.Vector3 = ArrayTools.BuildTuple(11, Vector3.Zero),
    a.Matrix = ArrayTools.BuildTuple(2, Matrix.Identity),
    a.Quaternion = ArrayTools.BuildTuple(3, Quaternion.Zero),
    a
}()
  , TmpVectors = function() {
    function a() {}
    return a.Vector2 = ArrayTools.BuildTuple(3, Vector2.Zero),
    a.Vector3 = ArrayTools.BuildTuple(13, Vector3.Zero),
    a.Vector4 = ArrayTools.BuildTuple(3, Vector4.Zero),
    a.Quaternion = ArrayTools.BuildTuple(2, Quaternion.Zero),
    a.Matrix = ArrayTools.BuildTuple(8, Matrix.Identity),
    a
}();
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)
  , Buffer = function() {
    function a(e, i, o, s, c, d, _, b) {
        s === void 0 && (s = 0),
        c === void 0 && (c = !1),
        d === void 0 && (d = !1),
        _ === void 0 && (_ = !1),
        this._isAlreadyOwned = !1,
        e.getScene ? this._engine = e.getScene().getEngine() : this._engine = e,
        this._updatable = o,
        this._instanced = d,
        this._divisor = b || 1,
        i instanceof DataBuffer ? (this._data = null,
        this._buffer = i) : (this._data = i,
        this._buffer = null),
        this.byteStride = _ ? s : s * Float32Array.BYTES_PER_ELEMENT,
        c || this.create()
    }
    return a.prototype.createVertexBuffer = function(e, i, o, s, c, d, _) {
        d === void 0 && (d = !1);
        var b = d ? i : i * Float32Array.BYTES_PER_ELEMENT
          , k = s ? d ? s : s * Float32Array.BYTES_PER_ELEMENT : this.byteStride;
        return new VertexBuffer(this._engine,this,e,this._updatable,!0,k,c === void 0 ? this._instanced : c,b,o,void 0,void 0,!0,this._divisor || _)
    }
    ,
    a.prototype.isUpdatable = function() {
        return this._updatable
    }
    ,
    a.prototype.getData = function() {
        return this._data
    }
    ,
    a.prototype.getBuffer = function() {
        return this._buffer
    }
    ,
    a.prototype.getStrideSize = function() {
        return this.byteStride / Float32Array.BYTES_PER_ELEMENT
    }
    ,
    a.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)))
    }
    ,
    a.prototype._rebuild = function() {
        this._buffer = null,
        this.create(this._data)
    }
    ,
    a.prototype.update = function(e) {
        this.create(e)
    }
    ,
    a.prototype.updateDirectly = function(e, i, o, s) {
        s === void 0 && (s = !1),
        !!this._buffer && this._updatable && (this._engine.updateDynamicVertexBuffer(this._buffer, e, s ? i : i * Float32Array.BYTES_PER_ELEMENT, o ? o * this.byteStride : void 0),
        this._data = null)
    }
    ,
    a.prototype._increaseReferences = function() {
        if (!!this._buffer) {
            if (!this._isAlreadyOwned) {
                this._isAlreadyOwned = !0;
                return
            }
            this._buffer.references++
        }
    }
    ,
    a.prototype.dispose = function() {
        !this._buffer || this._engine._releaseBuffer(this._buffer) && (this._buffer = null,
        this._data = null)
    }
    ,
    a
}()
  , VertexBuffer = function() {
    function a(e, i, o, s, c, d, _, b, k, j, $, _e, et, tt) {
        if ($ === void 0 && ($ = !1),
        _e === void 0 && (_e = !1),
        et === void 0 && (et = 1),
        tt === void 0 && (tt = !1),
        i instanceof Buffer ? (this._buffer = i,
        this._ownsBuffer = tt) : (this._buffer = new Buffer(e,i,s,d,c,_,_e),
        this._ownsBuffer = !0),
        this.uniqueId = a._Counter++,
        this._kind = o,
        j == null) {
            var rt = this.getData();
            this.type = a.FLOAT,
            rt instanceof Int8Array ? this.type = a.BYTE : rt instanceof Uint8Array ? this.type = a.UNSIGNED_BYTE : rt instanceof Int16Array ? this.type = a.SHORT : rt instanceof Uint16Array ? this.type = a.UNSIGNED_SHORT : rt instanceof Int32Array ? this.type = a.INT : rt instanceof Uint32Array && (this.type = a.UNSIGNED_INT)
        } else
            this.type = j;
        var it = a.GetTypeByteLength(this.type);
        _e ? (this._size = k || (d ? d / it : a.DeduceStride(o)),
        this.byteStride = d || this._buffer.byteStride || this._size * it,
        this.byteOffset = b || 0) : (this._size = k || d || a.DeduceStride(o),
        this.byteStride = d ? d * it : this._buffer.byteStride || this._size * it,
        this.byteOffset = (b || 0) * it),
        this.normalized = $,
        this._instanced = _ !== void 0 ? _ : !1,
        this._instanceDivisor = _ ? et : 0,
        this._computeHashCode()
    }
    return Object.defineProperty(a.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
    }),
    a.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)
    }
    ,
    a.prototype._rebuild = function() {
        !this._buffer || this._buffer._rebuild()
    }
    ,
    a.prototype.getKind = function() {
        return this._kind
    }
    ,
    a.prototype.isUpdatable = function() {
        return this._buffer.isUpdatable()
    }
    ,
    a.prototype.getData = function() {
        return this._buffer.getData()
    }
    ,
    a.prototype.getFloatData = function(e, i) {
        var o = this.getData();
        if (!o)
            return null;
        var s = this.getSize() * a.GetTypeByteLength(this.type)
          , c = e * this.getSize();
        if (this.type !== a.FLOAT || this.byteStride !== s) {
            var d = new Float32Array(c);
            return this.forEach(c, function($, _e) {
                return d[_e] = $
            }),
            d
        }
        if (!(o instanceof Array || o instanceof Float32Array) || this.byteOffset !== 0 || o.length !== c)
            if (o instanceof Array) {
                var _ = this.byteOffset / 4;
                return SliceTools.Slice(o, _, _ + c)
            } else {
                if (o instanceof ArrayBuffer)
                    return new Float32Array(o,this.byteOffset,c);
                var _ = o.byteOffset + this.byteOffset;
                if (i) {
                    var b = new Float32Array(c)
                      , k = new Float32Array(o.buffer,_,c);
                    return b.set(k),
                    b
                }
                var j = _ % 4;
                return j && (_ = Math.max(0, _ - j)),
                new Float32Array(o.buffer,_,c)
            }
        return i ? SliceTools.Slice(o) : o
    }
    ,
    a.prototype.getBuffer = function() {
        return this._buffer.getBuffer()
    }
    ,
    a.prototype.getStrideSize = function() {
        return this.byteStride / a.GetTypeByteLength(this.type)
    }
    ,
    a.prototype.getOffset = function() {
        return this.byteOffset / a.GetTypeByteLength(this.type)
    }
    ,
    a.prototype.getSize = function(e) {
        return e === void 0 && (e = !1),
        e ? this._size * a.GetTypeByteLength(this.type) : this._size
    }
    ,
    a.prototype.getIsInstanced = function() {
        return this._instanced
    }
    ,
    a.prototype.getInstanceDivisor = function() {
        return this._instanceDivisor
    }
    ,
    a.prototype.create = function(e) {
        this._buffer.create(e)
    }
    ,
    a.prototype.update = function(e) {
        this._buffer.update(e)
    }
    ,
    a.prototype.updateDirectly = function(e, i, o) {
        o === void 0 && (o = !1),
        this._buffer.updateDirectly(e, i, void 0, o)
    }
    ,
    a.prototype.dispose = function() {
        this._ownsBuffer && this._buffer.dispose()
    }
    ,
    a.prototype.forEach = function(e, i) {
        a.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, e, this.normalized, i)
    }
    ,
    a.DeduceStride = function(e) {
        switch (e) {
        case a.UVKind:
        case a.UV2Kind:
        case a.UV3Kind:
        case a.UV4Kind:
        case a.UV5Kind:
        case a.UV6Kind:
            return 2;
        case a.NormalKind:
        case a.PositionKind:
            return 3;
        case a.ColorKind:
        case a.MatricesIndicesKind:
        case a.MatricesIndicesExtraKind:
        case a.MatricesWeightsKind:
        case a.MatricesWeightsExtraKind:
        case a.TangentKind:
            return 4;
        default:
            throw new Error("Invalid kind '" + e + "'")
        }
    }
    ,
    a.GetTypeByteLength = function(e) {
        switch (e) {
        case a.BYTE:
        case a.UNSIGNED_BYTE:
            return 1;
        case a.SHORT:
        case a.UNSIGNED_SHORT:
            return 2;
        case a.INT:
        case a.UNSIGNED_INT:
        case a.FLOAT:
            return 4;
        default:
            throw new Error("Invalid type '" + e + "'")
        }
    }
    ,
    a.ForEach = function(e, i, o, s, c, d, _, b) {
        if (e instanceof Array)
            for (var k = i / 4, j = o / 4, $ = 0; $ < d; $ += s) {
                for (var _e = 0; _e < s; _e++)
                    b(e[k + _e], $ + _e);
                k += j
            }
        else
            for (var et = e instanceof ArrayBuffer ? new DataView(e) : new DataView(e.buffer,e.byteOffset,e.byteLength), tt = a.GetTypeByteLength(c), $ = 0; $ < d; $ += s) {
                for (var rt = i, _e = 0; _e < s; _e++) {
                    var it = a._GetFloatValue(et, c, rt, _);
                    b(it, $ + _e),
                    rt += tt
                }
                i += o
            }
    }
    ,
    a._GetFloatValue = function(e, i, o, s) {
        switch (i) {
        case a.BYTE:
            {
                var c = e.getInt8(o);
                return s && (c = Math.max(c / 127, -1)),
                c
            }
        case a.UNSIGNED_BYTE:
            {
                var c = e.getUint8(o);
                return s && (c = c / 255),
                c
            }
        case a.SHORT:
            {
                var c = e.getInt16(o, !0);
                return s && (c = Math.max(c / 32767, -1)),
                c
            }
        case a.UNSIGNED_SHORT:
            {
                var c = e.getUint16(o, !0);
                return s && (c = c / 65535),
                c
            }
        case a.INT:
            return e.getInt32(o, !0);
        case a.UNSIGNED_INT:
            return e.getUint32(o, !0);
        case a.FLOAT:
            return e.getFloat32(o, !0);
        default:
            throw new Error("Invalid component type " + i)
        }
    }
    ,
    a._Counter = 0,
    a.BYTE = 5120,
    a.UNSIGNED_BYTE = 5121,
    a.SHORT = 5122,
    a.UNSIGNED_SHORT = 5123,
    a.INT = 5124,
    a.UNSIGNED_INT = 5125,
    a.FLOAT = 5126,
    a.PositionKind = "position",
    a.NormalKind = "normal",
    a.TangentKind = "tangent",
    a.UVKind = "uv",
    a.UV2Kind = "uv2",
    a.UV3Kind = "uv3",
    a.UV4Kind = "uv4",
    a.UV5Kind = "uv5",
    a.UV6Kind = "uv6",
    a.ColorKind = "color",
    a.MatricesIndicesKind = "matricesIndices",
    a.MatricesWeightsKind = "matricesWeights",
    a.MatricesIndicesExtraKind = "matricesIndicesExtra",
    a.MatricesWeightsExtraKind = "matricesWeightsExtra",
    a
}()
  , Color3 = function() {
    function a(e, i, o) {
        e === void 0 && (e = 0),
        i === void 0 && (i = 0),
        o === void 0 && (o = 0),
        this.r = e,
        this.g = i,
        this.b = o
    }
    return a.prototype.toString = function() {
        return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}"
    }
    ,
    a.prototype.getClassName = function() {
        return "Color3"
    }
    ,
    a.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
    }
    ,
    a.prototype.toArray = function(e, i) {
        return i === void 0 && (i = 0),
        e[i] = this.r,
        e[i + 1] = this.g,
        e[i + 2] = this.b,
        this
    }
    ,
    a.prototype.fromArray = function(e, i) {
        return i === void 0 && (i = 0),
        a.FromArrayToRef(e, i, this),
        this
    }
    ,
    a.prototype.toColor4 = function(e) {
        return e === void 0 && (e = 1),
        new Color4(this.r,this.g,this.b,e)
    }
    ,
    a.prototype.asArray = function() {
        var e = new Array;
        return this.toArray(e, 0),
        e
    }
    ,
    a.prototype.toLuminance = function() {
        return this.r * .3 + this.g * .59 + this.b * .11
    }
    ,
    a.prototype.multiply = function(e) {
        return new a(this.r * e.r,this.g * e.g,this.b * e.b)
    }
    ,
    a.prototype.multiplyToRef = function(e, i) {
        return i.r = this.r * e.r,
        i.g = this.g * e.g,
        i.b = this.b * e.b,
        this
    }
    ,
    a.prototype.equals = function(e) {
        return e && this.r === e.r && this.g === e.g && this.b === e.b
    }
    ,
    a.prototype.equalsFloats = function(e, i, o) {
        return this.r === e && this.g === i && this.b === o
    }
    ,
    a.prototype.scale = function(e) {
        return new a(this.r * e,this.g * e,this.b * e)
    }
    ,
    a.prototype.scaleToRef = function(e, i) {
        return i.r = this.r * e,
        i.g = this.g * e,
        i.b = this.b * e,
        this
    }
    ,
    a.prototype.scaleAndAddToRef = function(e, i) {
        return i.r += this.r * e,
        i.g += this.g * e,
        i.b += this.b * e,
        this
    }
    ,
    a.prototype.clampToRef = function(e, i, o) {
        return e === void 0 && (e = 0),
        i === void 0 && (i = 1),
        o.r = Scalar.Clamp(this.r, e, i),
        o.g = Scalar.Clamp(this.g, e, i),
        o.b = Scalar.Clamp(this.b, e, i),
        this
    }
    ,
    a.prototype.add = function(e) {
        return new a(this.r + e.r,this.g + e.g,this.b + e.b)
    }
    ,
    a.prototype.addToRef = function(e, i) {
        return i.r = this.r + e.r,
        i.g = this.g + e.g,
        i.b = this.b + e.b,
        this
    }
    ,
    a.prototype.subtract = function(e) {
        return new a(this.r - e.r,this.g - e.g,this.b - e.b)
    }
    ,
    a.prototype.subtractToRef = function(e, i) {
        return i.r = this.r - e.r,
        i.g = this.g - e.g,
        i.b = this.b - e.b,
        this
    }
    ,
    a.prototype.clone = function() {
        return new a(this.r,this.g,this.b)
    }
    ,
    a.prototype.copyFrom = function(e) {
        return this.r = e.r,
        this.g = e.g,
        this.b = e.b,
        this
    }
    ,
    a.prototype.copyFromFloats = function(e, i, o) {
        return this.r = e,
        this.g = i,
        this.b = o,
        this
    }
    ,
    a.prototype.set = function(e, i, o) {
        return this.copyFromFloats(e, i, o)
    }
    ,
    a.prototype.toHexString = function() {
        var e = Math.round(this.r * 255)
          , i = Math.round(this.g * 255)
          , o = Math.round(this.b * 255);
        return "#" + Scalar.ToHex(e) + Scalar.ToHex(i) + Scalar.ToHex(o)
    }
    ,
    a.prototype.toLinearSpace = function() {
        var e = new a;
        return this.toLinearSpaceToRef(e),
        e
    }
    ,
    a.prototype.toHSV = function() {
        var e = new a;
        return this.toHSVToRef(e),
        e
    }
    ,
    a.prototype.toHSVToRef = function(e) {
        var i = this.r
          , o = this.g
          , s = this.b
          , c = Math.max(i, o, s)
          , d = Math.min(i, o, s)
          , _ = 0
          , b = 0
          , k = c
          , j = c - d;
        c !== 0 && (b = j / c),
        c != d && (c == i ? (_ = (o - s) / j,
        o < s && (_ += 6)) : c == o ? _ = (s - i) / j + 2 : c == s && (_ = (i - o) / j + 4),
        _ *= 60),
        e.r = _,
        e.g = b,
        e.b = k
    }
    ,
    a.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
    }
    ,
    a.prototype.toGammaSpace = function() {
        var e = new a;
        return this.toGammaSpaceToRef(e),
        e
    }
    ,
    a.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
    }
    ,
    a.HSVtoRGBToRef = function(e, i, o, s) {
        var c = o * i
          , d = e / 60
          , _ = c * (1 - Math.abs(d % 2 - 1))
          , b = 0
          , k = 0
          , j = 0;
        d >= 0 && d <= 1 ? (b = c,
        k = _) : d >= 1 && d <= 2 ? (b = _,
        k = c) : d >= 2 && d <= 3 ? (k = c,
        j = _) : d >= 3 && d <= 4 ? (k = _,
        j = c) : d >= 4 && d <= 5 ? (b = _,
        j = c) : d >= 5 && d <= 6 && (b = c,
        j = _);
        var $ = o - c;
        s.set(b + $, k + $, j + $)
    }
    ,
    a.FromHexString = function(e) {
        if (e.substring(0, 1) !== "#" || e.length !== 7)
            return new a(0,0,0);
        var i = parseInt(e.substring(1, 3), 16)
          , o = parseInt(e.substring(3, 5), 16)
          , s = parseInt(e.substring(5, 7), 16);
        return a.FromInts(i, o, s)
    }
    ,
    a.FromArray = function(e, i) {
        return i === void 0 && (i = 0),
        new a(e[i],e[i + 1],e[i + 2])
    }
    ,
    a.FromArrayToRef = function(e, i, o) {
        i === void 0 && (i = 0),
        o.r = e[i],
        o.g = e[i + 1],
        o.b = e[i + 2]
    }
    ,
    a.FromInts = function(e, i, o) {
        return new a(e / 255,i / 255,o / 255)
    }
    ,
    a.Lerp = function(e, i, o) {
        var s = new a(0,0,0);
        return a.LerpToRef(e, i, o, s),
        s
    }
    ,
    a.LerpToRef = function(e, i, o, s) {
        s.r = e.r + (i.r - e.r) * o,
        s.g = e.g + (i.g - e.g) * o,
        s.b = e.b + (i.b - e.b) * o
    }
    ,
    a.Hermite = function(e, i, o, s, c) {
        var d = c * c
          , _ = c * d
          , b = 2 * _ - 3 * d + 1
          , k = -2 * _ + 3 * d
          , j = _ - 2 * d + c
          , $ = _ - d
          , _e = e.r * b + o.r * k + i.r * j + s.r * $
          , et = e.g * b + o.g * k + i.g * j + s.g * $
          , tt = e.b * b + o.b * k + i.b * j + s.b * $;
        return new a(_e,et,tt)
    }
    ,
    a.Hermite1stDerivative = function(e, i, o, s, c) {
        var d = a.Black();
        return this.Hermite1stDerivativeToRef(e, i, o, s, c, d),
        d
    }
    ,
    a.Hermite1stDerivativeToRef = function(e, i, o, s, c, d) {
        var _ = c * c;
        d.r = (_ - c) * 6 * e.r + (3 * _ - 4 * c + 1) * i.r + (-_ + c) * 6 * o.r + (3 * _ - 2 * c) * s.r,
        d.g = (_ - c) * 6 * e.g + (3 * _ - 4 * c + 1) * i.g + (-_ + c) * 6 * o.g + (3 * _ - 2 * c) * s.g,
        d.b = (_ - c) * 6 * e.b + (3 * _ - 4 * c + 1) * i.b + (-_ + c) * 6 * o.b + (3 * _ - 2 * c) * s.b
    }
    ,
    a.Red = function() {
        return new a(1,0,0)
    }
    ,
    a.Green = function() {
        return new a(0,1,0)
    }
    ,
    a.Blue = function() {
        return new a(0,0,1)
    }
    ,
    a.Black = function() {
        return new a(0,0,0)
    }
    ,
    Object.defineProperty(a, "BlackReadOnly", {
        get: function() {
            return a._BlackReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    a.White = function() {
        return new a(1,1,1)
    }
    ,
    a.Purple = function() {
        return new a(.5,0,.5)
    }
    ,
    a.Magenta = function() {
        return new a(1,0,1)
    }
    ,
    a.Yellow = function() {
        return new a(1,1,0)
    }
    ,
    a.Gray = function() {
        return new a(.5,.5,.5)
    }
    ,
    a.Teal = function() {
        return new a(0,1,1)
    }
    ,
    a.Random = function() {
        return new a(Math.random(),Math.random(),Math.random())
    }
    ,
    a._BlackReadOnly = a.Black(),
    a
}()
  , Color4 = function() {
    function a(e, i, o, s) {
        e === void 0 && (e = 0),
        i === void 0 && (i = 0),
        o === void 0 && (o = 0),
        s === void 0 && (s = 1),
        this.r = e,
        this.g = i,
        this.b = o,
        this.a = s
    }
    return a.prototype.addInPlace = function(e) {
        return this.r += e.r,
        this.g += e.g,
        this.b += e.b,
        this.a += e.a,
        this
    }
    ,
    a.prototype.asArray = function() {
        var e = new Array;
        return this.toArray(e, 0),
        e
    }
    ,
    a.prototype.toArray = function(e, i) {
        return i === void 0 && (i = 0),
        e[i] = this.r,
        e[i + 1] = this.g,
        e[i + 2] = this.b,
        e[i + 3] = this.a,
        this
    }
    ,
    a.prototype.fromArray = function(e, i) {
        return i === void 0 && (i = 0),
        a.FromArrayToRef(e, i, this),
        this
    }
    ,
    a.prototype.equals = function(e) {
        return e && this.r === e.r && this.g === e.g && this.b === e.b && this.a === e.a
    }
    ,
    a.prototype.add = function(e) {
        return new a(this.r + e.r,this.g + e.g,this.b + e.b,this.a + e.a)
    }
    ,
    a.prototype.subtract = function(e) {
        return new a(this.r - e.r,this.g - e.g,this.b - e.b,this.a - e.a)
    }
    ,
    a.prototype.subtractToRef = function(e, i) {
        return i.r = this.r - e.r,
        i.g = this.g - e.g,
        i.b = this.b - e.b,
        i.a = this.a - e.a,
        this
    }
    ,
    a.prototype.scale = function(e) {
        return new a(this.r * e,this.g * e,this.b * e,this.a * e)
    }
    ,
    a.prototype.scaleToRef = function(e, i) {
        return i.r = this.r * e,
        i.g = this.g * e,
        i.b = this.b * e,
        i.a = this.a * e,
        this
    }
    ,
    a.prototype.scaleAndAddToRef = function(e, i) {
        return i.r += this.r * e,
        i.g += this.g * e,
        i.b += this.b * e,
        i.a += this.a * e,
        this
    }
    ,
    a.prototype.clampToRef = function(e, i, o) {
        return e === void 0 && (e = 0),
        i === void 0 && (i = 1),
        o.r = Scalar.Clamp(this.r, e, i),
        o.g = Scalar.Clamp(this.g, e, i),
        o.b = Scalar.Clamp(this.b, e, i),
        o.a = Scalar.Clamp(this.a, e, i),
        this
    }
    ,
    a.prototype.multiply = function(e) {
        return new a(this.r * e.r,this.g * e.g,this.b * e.b,this.a * e.a)
    }
    ,
    a.prototype.multiplyToRef = function(e, i) {
        return i.r = this.r * e.r,
        i.g = this.g * e.g,
        i.b = this.b * e.b,
        i.a = this.a * e.a,
        i
    }
    ,
    a.prototype.toString = function() {
        return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}"
    }
    ,
    a.prototype.getClassName = function() {
        return "Color4"
    }
    ,
    a.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
    }
    ,
    a.prototype.clone = function() {
        return new a(this.r,this.g,this.b,this.a)
    }
    ,
    a.prototype.copyFrom = function(e) {
        return this.r = e.r,
        this.g = e.g,
        this.b = e.b,
        this.a = e.a,
        this
    }
    ,
    a.prototype.copyFromFloats = function(e, i, o, s) {
        return this.r = e,
        this.g = i,
        this.b = o,
        this.a = s,
        this
    }
    ,
    a.prototype.set = function(e, i, o, s) {
        return this.copyFromFloats(e, i, o, s)
    }
    ,
    a.prototype.toHexString = function(e) {
        e === void 0 && (e = !1);
        var i = Math.round(this.r * 255)
          , o = Math.round(this.g * 255)
          , s = Math.round(this.b * 255);
        if (e)
            return "#" + Scalar.ToHex(i) + Scalar.ToHex(o) + Scalar.ToHex(s);
        var c = Math.round(this.a * 255);
        return "#" + Scalar.ToHex(i) + Scalar.ToHex(o) + Scalar.ToHex(s) + Scalar.ToHex(c)
    }
    ,
    a.prototype.toLinearSpace = function() {
        var e = new a;
        return this.toLinearSpaceToRef(e),
        e
    }
    ,
    a.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
    }
    ,
    a.prototype.toGammaSpace = function() {
        var e = new a;
        return this.toGammaSpaceToRef(e),
        e
    }
    ,
    a.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
    }
    ,
    a.FromHexString = function(e) {
        if (e.substring(0, 1) !== "#" || e.length !== 9 && e.length !== 7)
            return new a(0,0,0,0);
        var i = parseInt(e.substring(1, 3), 16)
          , o = parseInt(e.substring(3, 5), 16)
          , s = parseInt(e.substring(5, 7), 16)
          , c = e.length === 9 ? parseInt(e.substring(7, 9), 16) : 255;
        return a.FromInts(i, o, s, c)
    }
    ,
    a.Lerp = function(e, i, o) {
        var s = new a(0,0,0,0);
        return a.LerpToRef(e, i, o, s),
        s
    }
    ,
    a.LerpToRef = function(e, i, o, s) {
        s.r = e.r + (i.r - e.r) * o,
        s.g = e.g + (i.g - e.g) * o,
        s.b = e.b + (i.b - e.b) * o,
        s.a = e.a + (i.a - e.a) * o
    }
    ,
    a.Hermite = function(e, i, o, s, c) {
        var d = c * c
          , _ = c * d
          , b = 2 * _ - 3 * d + 1
          , k = -2 * _ + 3 * d
          , j = _ - 2 * d + c
          , $ = _ - d
          , _e = e.r * b + o.r * k + i.r * j + s.r * $
          , et = e.g * b + o.g * k + i.g * j + s.g * $
          , tt = e.b * b + o.b * k + i.b * j + s.b * $
          , rt = e.a * b + o.a * k + i.a * j + s.a * $;
        return new a(_e,et,tt,rt)
    }
    ,
    a.Hermite1stDerivative = function(e, i, o, s, c) {
        var d = new a;
        return this.Hermite1stDerivativeToRef(e, i, o, s, c, d),
        d
    }
    ,
    a.Hermite1stDerivativeToRef = function(e, i, o, s, c, d) {
        var _ = c * c;
        d.r = (_ - c) * 6 * e.r + (3 * _ - 4 * c + 1) * i.r + (-_ + c) * 6 * o.r + (3 * _ - 2 * c) * s.r,
        d.g = (_ - c) * 6 * e.g + (3 * _ - 4 * c + 1) * i.g + (-_ + c) * 6 * o.g + (3 * _ - 2 * c) * s.g,
        d.b = (_ - c) * 6 * e.b + (3 * _ - 4 * c + 1) * i.b + (-_ + c) * 6 * o.b + (3 * _ - 2 * c) * s.b,
        d.a = (_ - c) * 6 * e.a + (3 * _ - 4 * c + 1) * i.a + (-_ + c) * 6 * o.a + (3 * _ - 2 * c) * s.a
    }
    ,
    a.FromColor3 = function(e, i) {
        return i === void 0 && (i = 1),
        new a(e.r,e.g,e.b,i)
    }
    ,
    a.FromArray = function(e, i) {
        return i === void 0 && (i = 0),
        new a(e[i],e[i + 1],e[i + 2],e[i + 3])
    }
    ,
    a.FromArrayToRef = function(e, i, o) {
        i === void 0 && (i = 0),
        o.r = e[i],
        o.g = e[i + 1],
        o.b = e[i + 2],
        o.a = e[i + 3]
    }
    ,
    a.FromInts = function(e, i, o, s) {
        return new a(e / 255,i / 255,o / 255,s / 255)
    }
    ,
    a.CheckColors4 = function(e, i) {
        if (e.length === i * 3) {
            for (var o = [], s = 0; s < e.length; s += 3) {
                var c = s / 3 * 4;
                o[c] = e[s],
                o[c + 1] = e[s + 1],
                o[c + 2] = e[s + 2],
                o[c + 3] = 1
            }
            return o
        }
        return e
    }
    ,
    a
}()
  , TmpColors = function() {
    function a() {}
    return a.Color3 = ArrayTools.BuildArray(3, Color3.Black),
    a.Color4 = ArrayTools.BuildArray(3, function() {
        return new Color4(0,0,0,0)
    }),
    a
}();
RegisterClass("BABYLON.Color3", Color3);
RegisterClass("BABYLON.Color4", Color4);
var AndOrNotEvaluator = function() {
    function a() {}
    return a.Eval = function(e, i) {
        return e.match(/\([^\(\)]*\)/g) ? e = e.replace(/\([^\(\)]*\)/g, function(o) {
            return o = o.slice(1, o.length - 1),
            a._HandleParenthesisContent(o, i)
        }) : e = a._HandleParenthesisContent(e, i),
        e === "true" ? !0 : e === "false" ? !1 : a.Eval(e, i)
    }
    ,
    a._HandleParenthesisContent = function(e, i) {
        i = i || function(j) {
            return j === "true"
        }
        ;
        var o, s = e.split("||");
        for (var c in s)
            if (s.hasOwnProperty(c)) {
                var d = a._SimplifyNegation(s[c].trim())
                  , _ = d.split("&&");
                if (_.length > 1)
                    for (var b = 0; b < _.length; ++b) {
                        var k = a._SimplifyNegation(_[b].trim());
                        if (k !== "true" && k !== "false" ? k[0] === "!" ? o = !i(k.substring(1)) : o = i(k) : o = k === "true",
                        !o) {
                            d = "false";
                            break
                        }
                    }
                if (o || d === "true") {
                    o = !0;
                    break
                }
                d !== "true" && d !== "false" ? d[0] === "!" ? o = !i(d.substring(1)) : o = i(d) : o = d === "true"
            }
        return o ? "true" : "false"
    }
    ,
    a._SimplifyNegation = function(e) {
        return e = e.replace(/^[\s!]+/, function(i) {
            return i = i.replace(/[\s]/g, function() {
                return ""
            }),
            i.length % 2 ? "!" : ""
        }),
        e = e.trim(),
        e === "!true" ? e = "false" : e === "!false" && (e = "true"),
        e
    }
    ,
    a
}()
  , Tags = function() {
    function a() {}
    return a.EnableFor = function(e) {
        e._tags = e._tags || {},
        e.hasTags = function() {
            return a.HasTags(e)
        }
        ,
        e.addTags = function(i) {
            return a.AddTagsTo(e, i)
        }
        ,
        e.removeTags = function(i) {
            return a.RemoveTagsFrom(e, i)
        }
        ,
        e.matchesTagsQuery = function(i) {
            return a.MatchesQuery(e, i)
        }
    }
    ,
    a.DisableFor = function(e) {
        delete e._tags,
        delete e.hasTags,
        delete e.addTags,
        delete e.removeTags,
        delete e.matchesTagsQuery
    }
    ,
    a.HasTags = function(e) {
        if (!e._tags)
            return !1;
        var i = e._tags;
        for (var o in i)
            if (i.hasOwnProperty(o))
                return !0;
        return !1
    }
    ,
    a.GetTags = function(e, i) {
        if (i === void 0 && (i = !0),
        !e._tags)
            return null;
        if (i) {
            var o = [];
            for (var s in e._tags)
                e._tags.hasOwnProperty(s) && e._tags[s] === !0 && o.push(s);
            return o.join(" ")
        } else
            return e._tags
    }
    ,
    a.AddTagsTo = function(e, i) {
        if (!!i && typeof i == "string") {
            var o = i.split(" ");
            o.forEach(function(s, c, d) {
                a._AddTagTo(e, s)
            })
        }
    }
    ,
    a._AddTagTo = function(e, i) {
        i = i.trim(),
        !(i === "" || i === "true" || i === "false") && (i.match(/[\s]/) || i.match(/^([!]|([|]|[&]){2})/) || (a.EnableFor(e),
        e._tags[i] = !0))
    }
    ,
    a.RemoveTagsFrom = function(e, i) {
        if (!!a.HasTags(e)) {
            var o = i.split(" ");
            for (var s in o)
                a._RemoveTagFrom(e, o[s])
        }
    }
    ,
    a._RemoveTagFrom = function(e, i) {
        delete e._tags[i]
    }
    ,
    a.MatchesQuery = function(e, i) {
        return i === void 0 ? !0 : i === "" ? a.HasTags(e) : AndOrNotEvaluator.Eval(i, function(o) {
            return a.HasTags(e) && e._tags[o]
        })
    }
    ,
    a
}()
  , __decoratorInitialStore$1 = {}
  , __mergedStore$1 = {}
  , _copySource$1 = function(a, e, i) {
    var o = a();
    Tags && Tags.AddTagsTo(o, e.tags);
    var s = getMergedStore(o);
    for (var c in s) {
        var d = s[c]
          , _ = e[c]
          , b = d.type;
        if (_ != null && (c !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId))
            switch (b) {
            case 0:
            case 6:
            case 11:
                o[c] = _;
                break;
            case 1:
                o[c] = i || _.isRenderTarget ? _ : _.clone();
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 7:
            case 10:
            case 12:
                o[c] = i ? _ : _.clone();
                break
            }
    }
    return o
};
function getDirectStore$1(a) {
    var e = a.getClassName();
    return __decoratorInitialStore$1[e] || (__decoratorInitialStore$1[e] = {}),
    __decoratorInitialStore$1[e]
}
function getMergedStore(a) {
    var e = a.getClassName();
    if (__mergedStore$1[e])
        return __mergedStore$1[e];
    __mergedStore$1[e] = {};
    for (var i = __mergedStore$1[e], o = a, s = e; s; ) {
        var c = __decoratorInitialStore$1[s];
        for (var d in c)
            i[d] = c[d];
        var _ = void 0
          , b = !1;
        do {
            if (_ = Object.getPrototypeOf(o),
            !_.getClassName) {
                b = !0;
                break
            }
            if (_.getClassName() !== s)
                break;
            o = _
        } while (_);
        if (b)
            break;
        s = _.getClassName(),
        o = _
    }
    return i
}
function generateSerializableMember$1(a, e) {
    return function(i, o) {
        var s = getDirectStore$1(i);
        s[o] || (s[o] = {
            type: a,
            sourceName: e
        })
    }
}
function generateExpandMember(a, e) {
    return e === void 0 && (e = null),
    function(i, o) {
        var s = e || "_" + o;
        Object.defineProperty(i, o, {
            get: function() {
                return this[s]
            },
            set: function(c) {
                this[s] !== c && (this[s] = c,
                i[a].apply(this))
            },
            enumerable: !0,
            configurable: !0
        })
    }
}
function expandToProperty(a, e) {
    return e === void 0 && (e = null),
    generateExpandMember(a, e)
}
function serialize(a) {
    return generateSerializableMember$1(0, a)
}
function serializeAsTexture(a) {
    return generateSerializableMember$1(1, a)
}
function serializeAsColor3(a) {
    return generateSerializableMember$1(2, a)
}
function serializeAsFresnelParameters(a) {
    return generateSerializableMember$1(3, a)
}
function serializeAsVector2(a) {
    return generateSerializableMember$1(4, a)
}
function serializeAsVector3(a) {
    return generateSerializableMember$1(5, a)
}
function serializeAsMeshReference(a) {
    return generateSerializableMember$1(6, a)
}
function serializeAsColorCurves(a) {
    return generateSerializableMember$1(7, a)
}
function serializeAsColor4(a) {
    return generateSerializableMember$1(8, a)
}
function serializeAsImageProcessingConfiguration(a) {
    return generateSerializableMember$1(9, a)
}
function serializeAsQuaternion(a) {
    return generateSerializableMember$1(10, a)
}
function serializeAsMatrix(a) {
    return generateSerializableMember$1(12, a)
}
function serializeAsCameraReference(a) {
    return generateSerializableMember$1(11, a)
}
var SerializationHelper = function() {
    function a() {}
    return a.AppendSerializedAnimations = function(e, i) {
        if (e.animations) {
            i.animations = [];
            for (var o = 0; o < e.animations.length; o++) {
                var s = e.animations[o];
                i.animations.push(s.serialize())
            }
        }
    }
    ,
    a.Serialize = function(e, i) {
        i || (i = {}),
        Tags && (i.tags = Tags.GetTags(e));
        var o = getMergedStore(e);
        for (var s in o) {
            var c = o[s]
              , d = c.sourceName || s
              , _ = c.type
              , b = e[s];
            if (b != null && (s !== "uniqueId" || a.AllowLoadingUniqueId))
                switch (_) {
                case 0:
                    i[d] = b;
                    break;
                case 1:
                    i[d] = b.serialize();
                    break;
                case 2:
                    i[d] = b.asArray();
                    break;
                case 3:
                    i[d] = b.serialize();
                    break;
                case 4:
                    i[d] = b.asArray();
                    break;
                case 5:
                    i[d] = b.asArray();
                    break;
                case 6:
                    i[d] = b.id;
                    break;
                case 7:
                    i[d] = b.serialize();
                    break;
                case 8:
                    i[d] = b.asArray();
                    break;
                case 9:
                    i[d] = b.serialize();
                    break;
                case 10:
                    i[d] = b.asArray();
                    break;
                case 11:
                    i[d] = b.id;
                    break;
                case 12:
                    i[d] = b.asArray();
                    break
                }
        }
        return i
    }
    ,
    a.Parse = function(e, i, o, s) {
        s === void 0 && (s = null);
        var c = e();
        s || (s = ""),
        Tags && Tags.AddTagsTo(c, i.tags);
        var d = getMergedStore(c);
        for (var _ in d) {
            var b = d[_]
              , k = i[b.sourceName || _]
              , j = b.type;
            if (k != null && (_ !== "uniqueId" || a.AllowLoadingUniqueId)) {
                var $ = c;
                switch (j) {
                case 0:
                    $[_] = k;
                    break;
                case 1:
                    o && ($[_] = a._TextureParser(k, o, s));
                    break;
                case 2:
                    $[_] = Color3.FromArray(k);
                    break;
                case 3:
                    $[_] = a._FresnelParametersParser(k);
                    break;
                case 4:
                    $[_] = Vector2.FromArray(k);
                    break;
                case 5:
                    $[_] = Vector3.FromArray(k);
                    break;
                case 6:
                    o && ($[_] = o.getLastMeshById(k));
                    break;
                case 7:
                    $[_] = a._ColorCurvesParser(k);
                    break;
                case 8:
                    $[_] = Color4.FromArray(k);
                    break;
                case 9:
                    $[_] = a._ImageProcessingConfigurationParser(k);
                    break;
                case 10:
                    $[_] = Quaternion.FromArray(k);
                    break;
                case 11:
                    o && ($[_] = o.getCameraById(k));
                case 12:
                    $[_] = Matrix.FromArray(k);
                    break
                }
            }
        }
        return c
    }
    ,
    a.Clone = function(e, i) {
        return _copySource$1(e, i, !1)
    }
    ,
    a.Instanciate = function(e, i) {
        return _copySource$1(e, i, !0)
    }
    ,
    a.AllowLoadingUniqueId = !1,
    a._ImageProcessingConfigurationParser = function(e) {
        throw _WarnImport("ImageProcessingConfiguration")
    }
    ,
    a._FresnelParametersParser = function(e) {
        throw _WarnImport("FresnelParameters")
    }
    ,
    a._ColorCurvesParser = function(e) {
        throw _WarnImport("ColorCurves")
    }
    ,
    a._TextureParser = function(e, i, o) {
        throw _WarnImport("Texture")
    }
    ,
    a
}();
function nativeOverride(a, e, i, o) {
    var s = i.value;
    i.value = function() {
        for (var c = [], d = 0; d < arguments.length; d++)
            c[d] = arguments[d];
        var _ = s;
        if (typeof _native != "undefined" && _native[e]) {
            var b = _native[e];
            o ? _ = function() {
                for (var k = [], j = 0; j < arguments.length; j++)
                    k[j] = arguments[j];
                return o.apply(void 0, k) ? b.apply(void 0, k) : s.apply(void 0, k)
            }
            : _ = b
        }
        return a[e] = _,
        _.apply(void 0, c)
    }
}
nativeOverride.filter = function(a) {
    return function(e, i, o) {
        return nativeOverride(e, i, o, a)
    }
}
;
function inlineScheduler(a, e, i) {
    try {
        var o = a.next();
        o.done ? e(o) : o.value ? o.value.then(function() {
            o.value = void 0,
            e(o)
        }, i) : e(o)
    } catch (s) {
        i(s)
    }
}
function createYieldingScheduler(a) {
    a === void 0 && (a = 25);
    var e;
    return function(i, o, s) {
        var c = performance.now();
        e === void 0 || c - e > a ? (e = c,
        setTimeout(function() {
            inlineScheduler(i, o, s)
        }, 0)) : inlineScheduler(i, o, s)
    }
}
function runCoroutine(a, e, i, o, s) {
    var c = function() {
        var d, _ = function(b) {
            b.done ? i(b.value) : d === void 0 ? d = !0 : c()
        };
        do
            d = void 0,
            !s || !s.aborted ? e(a, _, o) : o(new Error("Aborted")),
            d === void 0 && (d = !1);
        while (d)
    };
    c()
}
function runCoroutineSync(a, e) {
    var i;
    return runCoroutine(a, inlineScheduler, function(o) {
        return i = o
    }, function(o) {
        throw o
    }, e),
    i
}
function runCoroutineAsync(a, e, i) {
    return new Promise(function(o, s) {
        runCoroutine(a, e, o, s, i)
    }
    )
}
function makeSyncFunction(a, e) {
    return function() {
        for (var i = [], o = 0; o < arguments.length; o++)
            i[o] = arguments[o];
        return runCoroutineSync(a.apply(void 0, i), e)
    }
}
var VertexData = function() {
    function a() {
        this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this))
    }
    return a.prototype.set = function(e, i) {
        switch (e.length || Logger$2.Warn("Setting vertex data kind '" + i + "' with an empty array"),
        i) {
        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
        }
    }
    ,
    a.prototype.applyToMesh = function(e, i) {
        return this._applyTo(e, i, !1),
        this
    }
    ,
    a.prototype.applyToGeometry = function(e, i) {
        return this._applyTo(e, i, !1),
        this
    }
    ,
    a.prototype.updateMesh = function(e) {
        return this._update(e),
        this
    }
    ,
    a.prototype.updateGeometry = function(e) {
        return this._update(e),
        this
    }
    ,
    a.prototype._applyToCoroutine = function(e, i, o) {
        return i === void 0 && (i = !1),
        __generator(this, function(s) {
            switch (s.label) {
            case 0:
                return this.positions ? (e.setVerticesData(VertexBuffer.PositionKind, this.positions, i),
                o ? [4] : [3, 2]) : [3, 2];
            case 1:
                s.sent(),
                s.label = 2;
            case 2:
                return this.normals ? (e.setVerticesData(VertexBuffer.NormalKind, this.normals, i),
                o ? [4] : [3, 4]) : [3, 4];
            case 3:
                s.sent(),
                s.label = 4;
            case 4:
                return this.tangents ? (e.setVerticesData(VertexBuffer.TangentKind, this.tangents, i),
                o ? [4] : [3, 6]) : [3, 6];
            case 5:
                s.sent(),
                s.label = 6;
            case 6:
                return this.uvs ? (e.setVerticesData(VertexBuffer.UVKind, this.uvs, i),
                o ? [4] : [3, 8]) : [3, 8];
            case 7:
                s.sent(),
                s.label = 8;
            case 8:
                return this.uvs2 ? (e.setVerticesData(VertexBuffer.UV2Kind, this.uvs2, i),
                o ? [4] : [3, 10]) : [3, 10];
            case 9:
                s.sent(),
                s.label = 10;
            case 10:
                return this.uvs3 ? (e.setVerticesData(VertexBuffer.UV3Kind, this.uvs3, i),
                o ? [4] : [3, 12]) : [3, 12];
            case 11:
                s.sent(),
                s.label = 12;
            case 12:
                return this.uvs4 ? (e.setVerticesData(VertexBuffer.UV4Kind, this.uvs4, i),
                o ? [4] : [3, 14]) : [3, 14];
            case 13:
                s.sent(),
                s.label = 14;
            case 14:
                return this.uvs5 ? (e.setVerticesData(VertexBuffer.UV5Kind, this.uvs5, i),
                o ? [4] : [3, 16]) : [3, 16];
            case 15:
                s.sent(),
                s.label = 16;
            case 16:
                return this.uvs6 ? (e.setVerticesData(VertexBuffer.UV6Kind, this.uvs6, i),
                o ? [4] : [3, 18]) : [3, 18];
            case 17:
                s.sent(),
                s.label = 18;
            case 18:
                return this.colors ? (e.setVerticesData(VertexBuffer.ColorKind, this.colors, i),
                o ? [4] : [3, 20]) : [3, 20];
            case 19:
                s.sent(),
                s.label = 20;
            case 20:
                return this.matricesIndices ? (e.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, i),
                o ? [4] : [3, 22]) : [3, 22];
            case 21:
                s.sent(),
                s.label = 22;
            case 22:
                return this.matricesWeights ? (e.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, i),
                o ? [4] : [3, 24]) : [3, 24];
            case 23:
                s.sent(),
                s.label = 24;
            case 24:
                return this.matricesIndicesExtra ? (e.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, i),
                o ? [4] : [3, 26]) : [3, 26];
            case 25:
                s.sent(),
                s.label = 26;
            case 26:
                return this.matricesWeightsExtra ? (e.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, i),
                o ? [4] : [3, 28]) : [3, 28];
            case 27:
                s.sent(),
                s.label = 28;
            case 28:
                return this.indices ? (e.setIndices(this.indices, null, i),
                o ? [4] : [3, 30]) : [3, 31];
            case 29:
                s.sent(),
                s.label = 30;
            case 30:
                return [3, 32];
            case 31:
                e.setIndices([], null),
                s.label = 32;
            case 32:
                return [2, this]
            }
        })
    }
    ,
    a.prototype._update = function(e, i, o) {
        return this.positions && e.updateVerticesData(VertexBuffer.PositionKind, this.positions, i, o),
        this.normals && e.updateVerticesData(VertexBuffer.NormalKind, this.normals, i, o),
        this.tangents && e.updateVerticesData(VertexBuffer.TangentKind, this.tangents, i, o),
        this.uvs && e.updateVerticesData(VertexBuffer.UVKind, this.uvs, i, o),
        this.uvs2 && e.updateVerticesData(VertexBuffer.UV2Kind, this.uvs2, i, o),
        this.uvs3 && e.updateVerticesData(VertexBuffer.UV3Kind, this.uvs3, i, o),
        this.uvs4 && e.updateVerticesData(VertexBuffer.UV4Kind, this.uvs4, i, o),
        this.uvs5 && e.updateVerticesData(VertexBuffer.UV5Kind, this.uvs5, i, o),
        this.uvs6 && e.updateVerticesData(VertexBuffer.UV6Kind, this.uvs6, i, o),
        this.colors && e.updateVerticesData(VertexBuffer.ColorKind, this.colors, i, o),
        this.matricesIndices && e.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, i, o),
        this.matricesWeights && e.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, i, o),
        this.matricesIndicesExtra && e.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, i, o),
        this.matricesWeightsExtra && e.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, i, o),
        this.indices && e.setIndices(this.indices, null),
        this
    }
    ,
    a._TransformVector3Coordinates = function(e, i) {
        for (var o = TmpVectors.Vector3[0], s = TmpVectors.Vector3[1], c = 0; c < e.length; c += 3)
            Vector3.FromArrayToRef(e, c, o),
            Vector3.TransformCoordinatesToRef(o, i, s),
            e[c] = s.x,
            e[c + 1] = s.y,
            e[c + 2] = s.z
    }
    ,
    a._TransformVector3Normals = function(e, i) {
        for (var o = TmpVectors.Vector3[0], s = TmpVectors.Vector3[1], c = 0; c < e.length; c += 3)
            Vector3.FromArrayToRef(e, c, o),
            Vector3.TransformNormalToRef(o, i, s),
            e[c] = s.x,
            e[c + 1] = s.y,
            e[c + 2] = s.z
    }
    ,
    a._TransformVector4Normals = function(e, i) {
        for (var o = TmpVectors.Vector4[0], s = TmpVectors.Vector4[1], c = 0; c < e.length; c += 4)
            Vector4.FromArrayToRef(e, c, o),
            Vector4.TransformNormalToRef(o, i, s),
            e[c] = s.x,
            e[c + 1] = s.y,
            e[c + 2] = s.z,
            e[c + 3] = s.w
    }
    ,
    a._FlipFaces = function(e) {
        for (var i = 0; i < e.length; i += 3) {
            var o = e[i + 1];
            e[i + 1] = e[i + 2],
            e[i + 2] = o
        }
    }
    ,
    a.prototype.transform = function(e) {
        var i = e.determinant() < 0;
        return this.positions && a._TransformVector3Coordinates(this.positions, e),
        this.normals && a._TransformVector3Normals(this.normals, e),
        this.tangents && a._TransformVector4Normals(this.tangents, e),
        i && this.indices && a._FlipFaces(this.indices),
        this
    }
    ,
    a.prototype.merge = function(e, i) {
        return i === void 0 && (i = !1),
        runCoroutineSync(this._mergeCoroutine(e, i, !1))
    }
    ,
    a.prototype._mergeCoroutine = function(e, i, o) {
        var s, c, _e, d, _, b, k, j, $, _e, et, tt, rt, it, nt;
        return i === void 0 && (i = !1),
        __generator(this, function(ot) {
            switch (ot.label) {
            case 0:
                for (this._validate(),
                e = Array.isArray(e) ? e : [e],
                s = 0,
                c = e; s < c.length; s++)
                    if (_e = c[s],
                    _e._validate(),
                    !this.normals != !_e.normals || !this.tangents != !_e.tangents || !this.uvs != !_e.uvs || !this.uvs2 != !_e.uvs2 || !this.uvs3 != !_e.uvs3 || !this.uvs4 != !_e.uvs4 || !this.uvs5 != !_e.uvs5 || !this.uvs6 != !_e.uvs6 || !this.colors != !_e.colors || !this.matricesIndices != !_e.matricesIndices || !this.matricesWeights != !_e.matricesWeights || !this.matricesIndicesExtra != !_e.matricesIndicesExtra || !this.matricesWeightsExtra != !_e.matricesWeightsExtra)
                        throw new Error("Cannot merge vertex data that do not have the same set of attributes");
                if (d = e.reduce(function(at, st) {
                    var ut, ct;
                    return at + ((ct = (ut = st.indices) === null || ut === void 0 ? void 0 : ut.length) !== null && ct !== void 0 ? ct : 0)
                }, (rt = (tt = this.indices) === null || tt === void 0 ? void 0 : tt.length) !== null && rt !== void 0 ? rt : 0),
                !(d > 0))
                    return [3, 4];
                _ = (nt = (it = this.indices) === null || it === void 0 ? void 0 : it.length) !== null && nt !== void 0 ? nt : 0,
                this.indices || (this.indices = new Array(d)),
                this.indices.length !== d && (Array.isArray(this.indices) ? this.indices.length = d : (b = i || this.indices instanceof Uint32Array ? new Uint32Array(d) : new Uint16Array(d),
                b.set(this.indices),
                this.indices = b)),
                k = this.positions ? this.positions.length / 3 : 0,
                j = 0,
                $ = e,
                ot.label = 1;
            case 1:
                if (!(j < $.length))
                    return [3, 4];
                if (_e = $[j],
                !_e.indices)
                    return [3, 3];
                for (et = 0; et < _e.indices.length; et++)
                    this.indices[_ + et] = _e.indices[et] + k;
                return k += _e.positions.length / 3,
                _ += _e.indices.length,
                o ? [4] : [3, 3];
            case 2:
                ot.sent(),
                ot.label = 3;
            case 3:
                return j++,
                [3, 1];
            case 4:
                return this.positions = a._mergeElement(this.positions, e.map(function(at) {
                    return at.positions
                })),
                o ? [4] : [3, 6];
            case 5:
                ot.sent(),
                ot.label = 6;
            case 6:
                return this.normals = a._mergeElement(this.normals, e.map(function(at) {
                    return at.normals
                })),
                o ? [4] : [3, 8];
            case 7:
                ot.sent(),
                ot.label = 8;
            case 8:
                return this.tangents = a._mergeElement(this.tangents, e.map(function(at) {
                    return at.tangents
                })),
                o ? [4] : [3, 10];
            case 9:
                ot.sent(),
                ot.label = 10;
            case 10:
                return this.uvs = a._mergeElement(this.uvs, e.map(function(at) {
                    return at.uvs
                })),
                o ? [4] : [3, 12];
            case 11:
                ot.sent(),
                ot.label = 12;
            case 12:
                return this.uvs2 = a._mergeElement(this.uvs2, e.map(function(at) {
                    return at.uvs2
                })),
                o ? [4] : [3, 14];
            case 13:
                ot.sent(),
                ot.label = 14;
            case 14:
                return this.uvs3 = a._mergeElement(this.uvs3, e.map(function(at) {
                    return at.uvs3
                })),
                o ? [4] : [3, 16];
            case 15:
                ot.sent(),
                ot.label = 16;
            case 16:
                return this.uvs4 = a._mergeElement(this.uvs4, e.map(function(at) {
                    return at.uvs4
                })),
                o ? [4] : [3, 18];
            case 17:
                ot.sent(),
                ot.label = 18;
            case 18:
                return this.uvs5 = a._mergeElement(this.uvs5, e.map(function(at) {
                    return at.uvs5
                })),
                o ? [4] : [3, 20];
            case 19:
                ot.sent(),
                ot.label = 20;
            case 20:
                return this.uvs6 = a._mergeElement(this.uvs6, e.map(function(at) {
                    return at.uvs6
                })),
                o ? [4] : [3, 22];
            case 21:
                ot.sent(),
                ot.label = 22;
            case 22:
                return this.colors = a._mergeElement(this.colors, e.map(function(at) {
                    return at.colors
                })),
                o ? [4] : [3, 24];
            case 23:
                ot.sent(),
                ot.label = 24;
            case 24:
                return this.matricesIndices = a._mergeElement(this.matricesIndices, e.map(function(at) {
                    return at.matricesIndices
                })),
                o ? [4] : [3, 26];
            case 25:
                ot.sent(),
                ot.label = 26;
            case 26:
                return this.matricesWeights = a._mergeElement(this.matricesWeights, e.map(function(at) {
                    return at.matricesWeights
                })),
                o ? [4] : [3, 28];
            case 27:
                ot.sent(),
                ot.label = 28;
            case 28:
                return this.matricesIndicesExtra = a._mergeElement(this.matricesIndicesExtra, e.map(function(at) {
                    return at.matricesIndicesExtra
                })),
                o ? [4] : [3, 30];
            case 29:
                ot.sent(),
                ot.label = 30;
            case 30:
                return this.matricesWeightsExtra = a._mergeElement(this.matricesWeightsExtra, e.map(function(at) {
                    return at.matricesWeightsExtra
                })),
                [2, this]
            }
        })
    }
    ,
    a._mergeElement = function(e, i) {
        var o = i.filter(function(tt) {
            return tt != null
        });
        if (o.length === 0)
            return e;
        if (!e)
            return this._mergeElement(o[0], o.slice(1));
        var s = o.reduce(function(tt, rt) {
            return tt + rt.length
        }, e.length);
        if (e instanceof Float32Array) {
            var c = new Float32Array(s);
            c.set(e);
            for (var d = e.length, _ = 0, b = o; _ < b.length; _++) {
                var k = b[_];
                c.set(k, d),
                d += k.length
            }
            return c
        } else {
            for (var j = new Array(s), $ = 0; $ < e.length; $++)
                j[$] = e[$];
            for (var d = e.length, _e = 0, et = o; _e < et.length; _e++) {
                for (var k = et[_e], $ = 0; $ < k.length; $++)
                    j[d + $] = k[$];
                d += k.length
            }
            return j
        }
    }
    ,
    a.prototype._validate = function() {
        if (!this.positions)
            throw new Error("Positions are required");
        var e = function(s, c) {
            var d = VertexBuffer.DeduceStride(s);
            if (c.length % d !== 0)
                throw new Error("The " + s + "s array count must be a multiple of " + d);
            return c.length / d
        }
          , i = e(VertexBuffer.PositionKind, this.positions)
          , o = function(s, c) {
            var d = e(s, c);
            if (d !== i)
                throw new Error("The " + s + "s element count (" + d + ") does not match the positions count (" + i + ")")
        };
        this.normals && o(VertexBuffer.NormalKind, this.normals),
        this.tangents && o(VertexBuffer.TangentKind, this.tangents),
        this.uvs && o(VertexBuffer.UVKind, this.uvs),
        this.uvs2 && o(VertexBuffer.UV2Kind, this.uvs2),
        this.uvs3 && o(VertexBuffer.UV3Kind, this.uvs3),
        this.uvs4 && o(VertexBuffer.UV4Kind, this.uvs4),
        this.uvs5 && o(VertexBuffer.UV5Kind, this.uvs5),
        this.uvs6 && o(VertexBuffer.UV6Kind, this.uvs6),
        this.colors && o(VertexBuffer.ColorKind, this.colors),
        this.matricesIndices && o(VertexBuffer.MatricesIndicesKind, this.matricesIndices),
        this.matricesWeights && o(VertexBuffer.MatricesWeightsKind, this.matricesWeights),
        this.matricesIndicesExtra && o(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra),
        this.matricesWeightsExtra && o(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra)
    }
    ,
    a.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
    }
    ,
    a.ExtractFromMesh = function(e, i, o) {
        return a._ExtractFrom(e, i, o)
    }
    ,
    a.ExtractFromGeometry = function(e, i, o) {
        return a._ExtractFrom(e, i, o)
    }
    ,
    a._ExtractFrom = function(e, i, o) {
        var s = new a;
        return e.isVerticesDataPresent(VertexBuffer.PositionKind) && (s.positions = e.getVerticesData(VertexBuffer.PositionKind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.NormalKind) && (s.normals = e.getVerticesData(VertexBuffer.NormalKind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.TangentKind) && (s.tangents = e.getVerticesData(VertexBuffer.TangentKind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.UVKind) && (s.uvs = e.getVerticesData(VertexBuffer.UVKind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.UV2Kind) && (s.uvs2 = e.getVerticesData(VertexBuffer.UV2Kind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.UV3Kind) && (s.uvs3 = e.getVerticesData(VertexBuffer.UV3Kind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.UV4Kind) && (s.uvs4 = e.getVerticesData(VertexBuffer.UV4Kind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.UV5Kind) && (s.uvs5 = e.getVerticesData(VertexBuffer.UV5Kind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.UV6Kind) && (s.uvs6 = e.getVerticesData(VertexBuffer.UV6Kind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.ColorKind) && (s.colors = e.getVerticesData(VertexBuffer.ColorKind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && (s.matricesIndices = e.getVerticesData(VertexBuffer.MatricesIndicesKind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind) && (s.matricesWeights = e.getVerticesData(VertexBuffer.MatricesWeightsKind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind) && (s.matricesIndicesExtra = e.getVerticesData(VertexBuffer.MatricesIndicesExtraKind, i, o)),
        e.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind) && (s.matricesWeightsExtra = e.getVerticesData(VertexBuffer.MatricesWeightsExtraKind, i, o)),
        s.indices = e.getIndices(i, o),
        s
    }
    ,
    a.CreateRibbon = function(e) {
        throw _WarnImport("ribbonBuilder")
    }
    ,
    a.CreateBox = function(e) {
        throw _WarnImport("boxBuilder")
    }
    ,
    a.CreateTiledBox = function(e) {
        throw _WarnImport("tiledBoxBuilder")
    }
    ,
    a.CreateTiledPlane = function(e) {
        throw _WarnImport("tiledPlaneBuilder")
    }
    ,
    a.CreateSphere = function(e) {
        throw _WarnImport("sphereBuilder")
    }
    ,
    a.CreateCylinder = function(e) {
        throw _WarnImport("cylinderBuilder")
    }
    ,
    a.CreateTorus = function(e) {
        throw _WarnImport("torusBuilder")
    }
    ,
    a.CreateLineSystem = function(e) {
        throw _WarnImport("linesBuilder")
    }
    ,
    a.CreateDashedLines = function(e) {
        throw _WarnImport("linesBuilder")
    }
    ,
    a.CreateGround = function(e) {
        throw _WarnImport("groundBuilder")
    }
    ,
    a.CreateTiledGround = function(e) {
        throw _WarnImport("groundBuilder")
    }
    ,
    a.CreateGroundFromHeightMap = function(e) {
        throw _WarnImport("groundBuilder")
    }
    ,
    a.CreatePlane = function(e) {
        throw _WarnImport("planeBuilder")
    }
    ,
    a.CreateDisc = function(e) {
        throw _WarnImport("discBuilder")
    }
    ,
    a.CreatePolygon = function(e, i, o, s, c, d, _) {
        throw _WarnImport("polygonBuilder")
    }
    ,
    a.CreateIcoSphere = function(e) {
        throw _WarnImport("icoSphereBuilder")
    }
    ,
    a.CreatePolyhedron = function(e) {
        throw _WarnImport("polyhedronBuilder")
    }
    ,
    a.CreateCapsule = function(e) {
        throw e === void 0 && (e = {
            orientation: Vector3.Up(),
            subdivisions: 2,
            tessellation: 16,
            height: 1,
            radius: .25,
            capSubdivisions: 6
        }),
        _WarnImport("capsuleBuilder")
    }
    ,
    a.CreateTorusKnot = function(e) {
        throw _WarnImport("torusKnotBuilder")
    }
    ,
    a.ComputeNormals = function(e, i, o, s) {
        var c = 0
          , d = 0
          , _ = 0
          , b = 0
          , k = 0
          , j = 0
          , $ = 0
          , _e = 0
          , et = 0
          , tt = 0
          , rt = 0
          , it = 0
          , nt = 0
          , ot = 0
          , at = 0
          , st = 0
          , ut = 0
          , ct = 0
          , lt = 0
          , ft = 0
          , ht = !1
          , pt = !1
          , dt = !1
          , _t = !1
          , mt = 1
          , vt = 0
          , yt = null;
        if (s && (ht = !!s.facetNormals,
        pt = !!s.facetPositions,
        dt = !!s.facetPartitioning,
        mt = s.useRightHandedSystem === !0 ? -1 : 1,
        vt = s.ratio || 0,
        _t = !!s.depthSort,
        yt = s.distanceTo,
        _t)) {
            yt === void 0 && (yt = Vector3.Zero());
            var Et = s.depthSortedFacets
        }
        var At = 0
          , gt = 0
          , St = 0
          , xt = 0;
        if (dt && s && s.bbSize) {
            var bt = 0
              , Rt = 0
              , Mt = 0
              , Pt = 0
              , It = 0
              , Dt = 0
              , Ct = 0
              , Ot = 0
              , wt = 0
              , Nt = 0
              , Ft = 0
              , Vt = 0
              , Lt = 0
              , kt = 0
              , Bt = 0
              , Ut = 0
              , Gt = s.bbSize.x > s.bbSize.y ? s.bbSize.x : s.bbSize.y;
            Gt = Gt > s.bbSize.z ? Gt : s.bbSize.z,
            At = s.subDiv.X * vt / s.bbSize.x,
            gt = s.subDiv.Y * vt / s.bbSize.y,
            St = s.subDiv.Z * vt / s.bbSize.z,
            xt = s.subDiv.max * s.subDiv.max,
            s.facetPartitioning.length = 0
        }
        for (c = 0; c < e.length; c++)
            o[c] = 0;
        var Ht = i.length / 3 | 0;
        for (c = 0; c < Ht; c++) {
            if (it = i[c * 3] * 3,
            nt = it + 1,
            ot = it + 2,
            at = i[c * 3 + 1] * 3,
            st = at + 1,
            ut = at + 2,
            ct = i[c * 3 + 2] * 3,
            lt = ct + 1,
            ft = ct + 2,
            d = e[it] - e[at],
            _ = e[nt] - e[st],
            b = e[ot] - e[ut],
            k = e[ct] - e[at],
            j = e[lt] - e[st],
            $ = e[ft] - e[ut],
            _e = mt * (_ * $ - b * j),
            et = mt * (b * k - d * $),
            tt = mt * (d * j - _ * k),
            rt = Math.sqrt(_e * _e + et * et + tt * tt),
            rt = rt === 0 ? 1 : rt,
            _e /= rt,
            et /= rt,
            tt /= rt,
            ht && s && (s.facetNormals[c].x = _e,
            s.facetNormals[c].y = et,
            s.facetNormals[c].z = tt),
            pt && s && (s.facetPositions[c].x = (e[it] + e[at] + e[ct]) / 3,
            s.facetPositions[c].y = (e[nt] + e[st] + e[lt]) / 3,
            s.facetPositions[c].z = (e[ot] + e[ut] + e[ft]) / 3),
            dt && s && (bt = Math.floor((s.facetPositions[c].x - s.bInfo.minimum.x * vt) * At),
            Rt = Math.floor((s.facetPositions[c].y - s.bInfo.minimum.y * vt) * gt),
            Mt = Math.floor((s.facetPositions[c].z - s.bInfo.minimum.z * vt) * St),
            Pt = Math.floor((e[it] - s.bInfo.minimum.x * vt) * At),
            It = Math.floor((e[nt] - s.bInfo.minimum.y * vt) * gt),
            Dt = Math.floor((e[ot] - s.bInfo.minimum.z * vt) * St),
            Ct = Math.floor((e[at] - s.bInfo.minimum.x * vt) * At),
            Ot = Math.floor((e[st] - s.bInfo.minimum.y * vt) * gt),
            wt = Math.floor((e[ut] - s.bInfo.minimum.z * vt) * St),
            Nt = Math.floor((e[ct] - s.bInfo.minimum.x * vt) * At),
            Ft = Math.floor((e[lt] - s.bInfo.minimum.y * vt) * gt),
            Vt = Math.floor((e[ft] - s.bInfo.minimum.z * vt) * St),
            kt = Pt + s.subDiv.max * It + xt * Dt,
            Bt = Ct + s.subDiv.max * Ot + xt * wt,
            Ut = Nt + s.subDiv.max * Ft + xt * Vt,
            Lt = bt + s.subDiv.max * Rt + xt * Mt,
            s.facetPartitioning[Lt] = s.facetPartitioning[Lt] ? s.facetPartitioning[Lt] : new Array,
            s.facetPartitioning[kt] = s.facetPartitioning[kt] ? s.facetPartitioning[kt] : new Array,
            s.facetPartitioning[Bt] = s.facetPartitioning[Bt] ? s.facetPartitioning[Bt] : new Array,
            s.facetPartitioning[Ut] = s.facetPartitioning[Ut] ? s.facetPartitioning[Ut] : new Array,
            s.facetPartitioning[kt].push(c),
            Bt != kt && s.facetPartitioning[Bt].push(c),
            Ut == Bt || Ut == kt || s.facetPartitioning[Ut].push(c),
            Lt == kt || Lt == Bt || Lt == Ut || s.facetPartitioning[Lt].push(c)),
            _t && s && s.facetPositions) {
                var zt = Et[c];
                zt.ind = c * 3,
                zt.sqDistance = Vector3.DistanceSquared(s.facetPositions[c], yt)
            }
            o[it] += _e,
            o[nt] += et,
            o[ot] += tt,
            o[at] += _e,
            o[st] += et,
            o[ut] += tt,
            o[ct] += _e,
            o[lt] += et,
            o[ft] += tt
        }
        for (c = 0; c < o.length / 3; c++)
            _e = o[c * 3],
            et = o[c * 3 + 1],
            tt = o[c * 3 + 2],
            rt = Math.sqrt(_e * _e + et * et + tt * tt),
            rt = rt === 0 ? 1 : rt,
            _e /= rt,
            et /= rt,
            tt /= rt,
            o[c * 3] = _e,
            o[c * 3 + 1] = et,
            o[c * 3 + 2] = tt
    }
    ,
    a._ComputeSides = function(e, i, o, s, c, d, _) {
        var b = o.length, k = s.length, j, $;
        switch (e = e || a.DEFAULTSIDE,
        e) {
        case a.FRONTSIDE:
            break;
        case a.BACKSIDE:
            var _e;
            for (j = 0; j < b; j += 3)
                _e = o[j],
                o[j] = o[j + 2],
                o[j + 2] = _e;
            for ($ = 0; $ < k; $++)
                s[$] = -s[$];
            break;
        case a.DOUBLESIDE:
            for (var et = i.length, tt = et / 3, rt = 0; rt < et; rt++)
                i[et + rt] = i[rt];
            for (j = 0; j < b; j += 3)
                o[j + b] = o[j + 2] + tt,
                o[j + 1 + b] = o[j + 1] + tt,
                o[j + 2 + b] = o[j] + tt;
            for ($ = 0; $ < k; $++)
                s[k + $] = -s[$];
            var it = c.length
              , nt = 0;
            for (nt = 0; nt < it; nt++)
                c[nt + it] = c[nt];
            for (d = d || new Vector4(0,0,1,1),
            _ = _ || new Vector4(0,0,1,1),
            nt = 0,
            j = 0; j < it / 2; j++)
                c[nt] = d.x + (d.z - d.x) * c[nt],
                c[nt + 1] = d.y + (d.w - d.y) * c[nt + 1],
                c[nt + it] = _.x + (_.z - _.x) * c[nt + it],
                c[nt + it + 1] = _.y + (_.w - _.y) * c[nt + it + 1],
                nt += 2;
            break
        }
    }
    ,
    a.ImportVertexData = function(e, i) {
        var o = new a
          , s = e.positions;
        s && o.set(s, VertexBuffer.PositionKind);
        var c = e.normals;
        c && o.set(c, VertexBuffer.NormalKind);
        var d = e.tangents;
        d && o.set(d, VertexBuffer.TangentKind);
        var _ = e.uvs;
        _ && o.set(_, VertexBuffer.UVKind);
        var b = e.uv2s;
        b && o.set(b, VertexBuffer.UV2Kind);
        var k = e.uv3s;
        k && o.set(k, VertexBuffer.UV3Kind);
        var j = e.uv4s;
        j && o.set(j, VertexBuffer.UV4Kind);
        var $ = e.uv5s;
        $ && o.set($, VertexBuffer.UV5Kind);
        var _e = e.uv6s;
        _e && o.set(_e, VertexBuffer.UV6Kind);
        var et = e.colors;
        et && o.set(Color4.CheckColors4(et, s.length / 3), VertexBuffer.ColorKind);
        var tt = e.matricesIndices;
        tt && o.set(tt, VertexBuffer.MatricesIndicesKind);
        var rt = e.matricesWeights;
        rt && o.set(rt, VertexBuffer.MatricesWeightsKind);
        var it = e.indices;
        it && (o.indices = it),
        i.setAllVerticesData(o, e.updatable)
    }
    ,
    a.FRONTSIDE = 0,
    a.BACKSIDE = 1,
    a.DOUBLESIDE = 2,
    a.DEFAULTSIDE = 0,
    __decorate([nativeOverride.filter(function() {
        for (var e = [], i = 0; i < arguments.length; i++)
            e[i] = arguments[i];
        var o = e[0];
        return !Array.isArray(o)
    })], a, "_TransformVector3Coordinates", null),
    __decorate([nativeOverride.filter(function() {
        for (var e = [], i = 0; i < arguments.length; i++)
            e[i] = arguments[i];
        var o = e[0];
        return !Array.isArray(o)
    })], a, "_TransformVector3Normals", null),
    __decorate([nativeOverride.filter(function() {
        for (var e = [], i = 0; i < arguments.length; i++)
            e[i] = arguments[i];
        var o = e[0];
        return !Array.isArray(o)
    })], a, "_TransformVector4Normals", null),
    __decorate([nativeOverride.filter(function() {
        for (var e = [], i = 0; i < arguments.length; i++)
            e[i] = arguments[i];
        var o = e[0];
        return !Array.isArray(o)
    })], a, "_FlipFaces", null),
    a
}(), _InternalNodeDataInfo = function() {
    function a() {
        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 a
}(), Node$2 = function() {
    function a(e, i) {
        i === void 0 && (i = 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 = i || EngineStore.LastCreatedScene,
        this.uniqueId = this._scene.getUniqueId(),
        this._initCache()
    }
    return a.AddNodeConstructor = function(e, i) {
        this._NodeConstructors[e] = i
    }
    ,
    a.Construct = function(e, i, o, s) {
        var c = this._NodeConstructors[e];
        return c ? c(i, o, s) : null
    }
    ,
    Object.defineProperty(a.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
    }),
    a.prototype.isDisposed = function() {
        return this._nodeDataStorage._isDisposed
    }
    ,
    Object.defineProperty(a.prototype, "parent", {
        get: function() {
            return this._parentNode
        },
        set: function(e) {
            if (this._parentNode !== e) {
                var i = this._parentNode;
                if (this._parentNode && this._parentNode._children !== void 0 && this._parentNode._children !== null) {
                    var o = this._parentNode._children.indexOf(this);
                    o !== -1 && this._parentNode._children.splice(o, 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),
                i || this._removeFromSceneRootNodes()),
                this._syncParentEnabledState()
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._addToSceneRootNodes = function() {
        this._nodeDataStorage._sceneRootNodesIndex === -1 && (this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length,
        this._scene.rootNodes.push(this))
    }
    ,
    a.prototype._removeFromSceneRootNodes = function() {
        if (this._nodeDataStorage._sceneRootNodesIndex !== -1) {
            var e = this._scene.rootNodes
              , i = e.length - 1;
            e[this._nodeDataStorage._sceneRootNodesIndex] = e[i],
            e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex = this._nodeDataStorage._sceneRootNodesIndex,
            this._scene.rootNodes.pop(),
            this._nodeDataStorage._sceneRootNodesIndex = -1
        }
    }
    ,
    Object.defineProperty(a.prototype, "animationPropertiesOverride", {
        get: function() {
            return this._animationPropertiesOverride ? this._animationPropertiesOverride : this._scene.animationPropertiesOverride
        },
        set: function(e) {
            this._animationPropertiesOverride = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getClassName = function() {
        return "Node"
    }
    ,
    Object.defineProperty(a.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onEnabledStateChangedObservable", {
        get: function() {
            return this._nodeDataStorage._onEnabledStateChangedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onClonedObservable", {
        get: function() {
            return this._nodeDataStorage._onClonedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getScene = function() {
        return this._scene
    }
    ,
    a.prototype.getEngine = function() {
        return this._scene.getEngine()
    }
    ,
    a.prototype.addBehavior = function(e, i) {
        var o = this;
        i === void 0 && (i = !1);
        var s = this._behaviors.indexOf(e);
        return s !== -1 ? this : (e.init(),
        this._scene.isLoading && !i ? this._scene.onDataLoadedObservable.addOnce(function() {
            e.attach(o)
        }) : e.attach(this),
        this._behaviors.push(e),
        this)
    }
    ,
    a.prototype.removeBehavior = function(e) {
        var i = this._behaviors.indexOf(e);
        return i === -1 ? this : (this._behaviors[i].detach(),
        this._behaviors.splice(i, 1),
        this)
    }
    ,
    Object.defineProperty(a.prototype, "behaviors", {
        get: function() {
            return this._behaviors
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getBehaviorByName = function(e) {
        for (var i = 0, o = this._behaviors; i < o.length; i++) {
            var s = o[i];
            if (s.name === e)
                return s
        }
        return null
    }
    ,
    a.prototype.getWorldMatrix = function() {
        return this._currentRenderId !== this._scene.getRenderId() && this.computeWorldMatrix(),
        this._worldMatrix
    }
    ,
    a.prototype._getWorldMatrixDeterminant = function() {
        return this._worldMatrixDeterminantIsDirty && (this._worldMatrixDeterminantIsDirty = !1,
        this._worldMatrixDeterminant = this._worldMatrix.determinant()),
        this._worldMatrixDeterminant
    }
    ,
    Object.defineProperty(a.prototype, "worldMatrixFromCache", {
        get: function() {
            return this._worldMatrix
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._initCache = function() {
        this._cache = {},
        this._cache.parent = void 0
    }
    ,
    a.prototype.updateCache = function(e) {
        !e && this.isSynchronized() || (this._cache.parent = this.parent,
        this._updateCache())
    }
    ,
    a.prototype._getActionManagerForTrigger = function(e, i) {
        return this.parent ? this.parent._getActionManagerForTrigger(e, !1) : null
    }
    ,
    a.prototype._updateCache = function(e) {}
    ,
    a.prototype._isSynchronized = function() {
        return !0
    }
    ,
    a.prototype._markSyncedWithParent = function() {
        this._parentNode && (this._parentUpdateId = this._parentNode._childUpdateId)
    }
    ,
    a.prototype.isSynchronizedWithParent = function() {
        return this._parentNode ? this._parentUpdateId !== this._parentNode._childUpdateId ? !1 : this._parentNode.isSynchronized() : !0
    }
    ,
    a.prototype.isSynchronized = function() {
        return this._cache.parent != this._parentNode ? (this._cache.parent = this._parentNode,
        !1) : this._parentNode && !this.isSynchronizedWithParent() ? !1 : this._isSynchronized()
    }
    ,
    a.prototype.isReady = function(e) {
        return this._nodeDataStorage._isReady
    }
    ,
    a.prototype.markAsDirty = function(e) {
        return this._currentRenderId = Number.MAX_VALUE,
        this._isDirty = !0,
        this
    }
    ,
    a.prototype.isEnabled = function(e) {
        return e === void 0 && (e = !0),
        e === !1 ? this._nodeDataStorage._isEnabled : this._nodeDataStorage._isEnabled ? this._nodeDataStorage._isParentEnabled : !1
    }
    ,
    a.prototype._syncParentEnabledState = function() {
        this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : !0,
        this._children && this._children.forEach(function(e) {
            e._syncParentEnabledState()
        })
    }
    ,
    a.prototype.setEnabled = function(e) {
        this._nodeDataStorage._isEnabled !== e && (this._nodeDataStorage._isEnabled = e,
        this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e),
        this._syncParentEnabledState())
    }
    ,
    a.prototype.isDescendantOf = function(e) {
        return this.parent ? this.parent === e ? !0 : this.parent.isDescendantOf(e) : !1
    }
    ,
    a.prototype._getDescendants = function(e, i, o) {
        if (i === void 0 && (i = !1),
        !!this._children)
            for (var s = 0; s < this._children.length; s++) {
                var c = this._children[s];
                (!o || o(c)) && e.push(c),
                i || c._getDescendants(e, !1, o)
            }
    }
    ,
    a.prototype.getDescendants = function(e, i) {
        var o = new Array;
        return this._getDescendants(o, e, i),
        o
    }
    ,
    a.prototype.getChildMeshes = function(e, i) {
        var o = [];
        return this._getDescendants(o, e, function(s) {
            return (!i || i(s)) && s.cullingStrategy !== void 0
        }),
        o
    }
    ,
    a.prototype.getChildren = function(e, i) {
        return i === void 0 && (i = !0),
        this.getDescendants(i, e)
    }
    ,
    a.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
        }
    }
    ,
    a.prototype.getAnimationByName = function(e) {
        for (var i = 0; i < this.animations.length; i++) {
            var o = this.animations[i];
            if (o.name === e)
                return o
        }
        return null
    }
    ,
    a.prototype.createAnimationRange = function(e, i, o) {
        if (!this._ranges[e]) {
            this._ranges[e] = a._AnimationRangeFactory(e, i, o);
            for (var s = 0, c = this.animations.length; s < c; s++)
                this.animations[s] && this.animations[s].createRange(e, i, o)
        }
    }
    ,
    a.prototype.deleteAnimationRange = function(e, i) {
        i === void 0 && (i = !0);
        for (var o = 0, s = this.animations.length; o < s; o++)
            this.animations[o] && this.animations[o].deleteRange(e, i);
        this._ranges[e] = null
    }
    ,
    a.prototype.getAnimationRange = function(e) {
        return this._ranges[e] || null
    }
    ,
    a.prototype.getAnimationRanges = function() {
        var e = [], i;
        for (i in this._ranges)
            e.push(this._ranges[i]);
        return e
    }
    ,
    a.prototype.beginAnimation = function(e, i, o, s) {
        var c = this.getAnimationRange(e);
        return c ? this._scene.beginAnimation(this, c.from, c.to, i, o, s) : null
    }
    ,
    a.prototype.serializeAnimationRanges = function() {
        var e = [];
        for (var i in this._ranges) {
            var o = this._ranges[i];
            if (!!o) {
                var s = {};
                s.name = i,
                s.from = o.from,
                s.to = o.to,
                e.push(s)
            }
        }
        return e
    }
    ,
    a.prototype.computeWorldMatrix = function(e) {
        return this._worldMatrix || (this._worldMatrix = Matrix.Identity()),
        this._worldMatrix
    }
    ,
    a.prototype.dispose = function(e, i) {
        if (i === void 0 && (i = !1),
        this._nodeDataStorage._isDisposed = !0,
        !e)
            for (var o = this.getDescendants(!0), s = 0, c = o; s < c.length; s++) {
                var d = c[s];
                d.dispose(e, i)
            }
        this.parent ? this.parent = null : this._removeFromSceneRootNodes(),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.onEnabledStateChangedObservable.clear(),
        this.onClonedObservable.clear();
        for (var _ = 0, b = this._behaviors; _ < b.length; _++) {
            var k = b[_];
            k.detach()
        }
        this._behaviors = [],
        this.metadata = null
    }
    ,
    a.ParseAnimationRanges = function(e, i, o) {
        if (i.ranges)
            for (var s = 0; s < i.ranges.length; s++) {
                var c = i.ranges[s];
                e.createAnimationRange(c.name, c.from, c.to)
            }
    }
    ,
    a.prototype.getHierarchyBoundingVectors = function(e, i) {
        e === void 0 && (e = !0),
        i === void 0 && (i = null),
        this.getScene().incrementRenderId(),
        this.computeWorldMatrix(!0);
        var o, s, c = this;
        if (c.getBoundingInfo && c.subMeshes) {
            var d = c.getBoundingInfo();
            o = d.boundingBox.minimumWorld.clone(),
            s = d.boundingBox.maximumWorld.clone()
        } else
            o = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
            s = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);
        if (e)
            for (var _ = this.getDescendants(!1), b = 0, k = _; b < k.length; b++) {
                var j = k[b]
                  , $ = j;
                if ($.computeWorldMatrix(!0),
                !(i && !i($)) && !(!$.getBoundingInfo || $.getTotalVertices() === 0)) {
                    var _e = $.getBoundingInfo()
                      , et = _e.boundingBox
                      , tt = et.minimumWorld
                      , rt = et.maximumWorld;
                    Vector3.CheckExtends(tt, o, s),
                    Vector3.CheckExtends(rt, o, s)
                }
            }
        return {
            min: o,
            max: s
        }
    }
    ,
    a._AnimationRangeFactory = function(e, i, o) {
        throw _WarnImport("AnimationRange")
    }
    ,
    a._NodeConstructors = {},
    __decorate([serialize()], a.prototype, "name", void 0),
    __decorate([serialize()], a.prototype, "id", void 0),
    __decorate([serialize()], a.prototype, "uniqueId", void 0),
    __decorate([serialize()], a.prototype, "state", void 0),
    __decorate([serialize()], a.prototype, "metadata", void 0),
    a
}(), Space;
(function(a) {
    a[a.LOCAL = 0] = "LOCAL",
    a[a.WORLD = 1] = "WORLD",
    a[a.BONE = 2] = "BONE"
}
)(Space || (Space = {}));
var Axis = function() {
    function a() {}
    return a.X = new Vector3(1,0,0),
    a.Y = new Vector3(0,1,0),
    a.Z = new Vector3(0,0,1),
    a
}(), Coordinate;
(function(a) {
    a[a.X = 0] = "X",
    a[a.Y = 1] = "Y",
    a[a.Z = 2] = "Z"
}
)(Coordinate || (Coordinate = {}));
var TransformNode = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        o === void 0 && (o = null),
        s === void 0 && (s = !0);
        var c = a.call(this, i, o) || this;
        return c._forward = new Vector3(0,0,1),
        c._forwardInverted = new Vector3(0,0,-1),
        c._up = new Vector3(0,1,0),
        c._right = new Vector3(1,0,0),
        c._rightInverted = new Vector3(-1,0,0),
        c._position = Vector3.Zero(),
        c._rotation = Vector3.Zero(),
        c._rotationQuaternion = null,
        c._scaling = Vector3.One(),
        c._transformToBoneReferal = null,
        c._isAbsoluteSynced = !1,
        c._billboardMode = e.BILLBOARDMODE_NONE,
        c._preserveParentRotationForBillboard = !1,
        c.scalingDeterminant = 1,
        c._infiniteDistance = !1,
        c.ignoreNonUniformScaling = !1,
        c.reIntegrateRotationIntoRotationQuaternion = !1,
        c._poseMatrix = null,
        c._localMatrix = Matrix.Zero(),
        c._usePivotMatrix = !1,
        c._absolutePosition = Vector3.Zero(),
        c._absoluteScaling = Vector3.Zero(),
        c._absoluteRotationQuaternion = Quaternion.Identity(),
        c._pivotMatrix = Matrix.Identity(),
        c._postMultiplyPivotMatrix = !1,
        c._isWorldMatrixFrozen = !1,
        c._indexInSceneTransformNodesArray = -1,
        c.onAfterWorldMatrixUpdateObservable = new Observable,
        c._nonUniformScaling = !1,
        s && c.getScene().addTransformNode(c),
        c
    }
    return Object.defineProperty(e.prototype, "billboardMode", {
        get: function() {
            return this._billboardMode
        },
        set: function(i) {
            this._billboardMode !== i && (this._billboardMode = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "preserveParentRotationForBillboard", {
        get: function() {
            return this._preserveParentRotationForBillboard
        },
        set: function(i) {
            i !== this._preserveParentRotationForBillboard && (this._preserveParentRotationForBillboard = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "infiniteDistance", {
        get: function() {
            return this._infiniteDistance
        },
        set: function(i) {
            this._infiniteDistance !== i && (this._infiniteDistance = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "TransformNode"
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(i) {
            this._position = i,
            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(i) {
            this._rotation = i,
            this._rotationQuaternion = null,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaling", {
        get: function() {
            return this._scaling
        },
        set: function(i) {
            this._scaling = i,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotationQuaternion", {
        get: function() {
            return this._rotationQuaternion
        },
        set: function(i) {
            this._rotationQuaternion = i,
            i && 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(i) {
        return this._poseMatrix ? (this._poseMatrix.copyFrom(i),
        this) : (this._poseMatrix = i.clone(),
        this)
    }
    ,
    e.prototype.getPoseMatrix = function() {
        return this._poseMatrix || (this._poseMatrix = Matrix.Identity()),
        this._poseMatrix
    }
    ,
    e.prototype._isSynchronized = function() {
        var i = this._cache;
        return !(this.billboardMode !== i.billboardMode || this.billboardMode !== e.BILLBOARDMODE_NONE || i.pivotMatrixUpdated || this.infiniteDistance || this.position._isDirty || this.scaling._isDirty || this._rotationQuaternion && this._rotationQuaternion._isDirty || this.rotation._isDirty)
    }
    ,
    e.prototype._initCache = function() {
        a.prototype._initCache.call(this);
        var i = this._cache;
        i.localMatrixUpdated = !1,
        i.billboardMode = -1,
        i.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(i) {
        return this.setPivotMatrix(i, !1)
    }
    ,
    e.prototype.setPivotMatrix = function(i, o) {
        return o === void 0 && (o = !0),
        this._pivotMatrix.copyFrom(i),
        this._usePivotMatrix = !this._pivotMatrix.isIdentity(),
        this._cache.pivotMatrixUpdated = !0,
        this._postMultiplyPivotMatrix = o,
        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(i, o, s) {
        i === void 0 && (i = null);
        var c = this.clone("Clone of " + (this.name || this.id), i || this.parent, !0);
        c && s && s(this, c);
        for (var d = 0, _ = this.getChildTransformNodes(!0); d < _.length; d++) {
            var b = _[d];
            b.instantiateHierarchy(c, o, s)
        }
        return c
    }
    ,
    e.prototype.freezeWorldMatrix = function(i, o) {
        return i === void 0 && (i = null),
        o === void 0 && (o = !1),
        i ? o ? (this._rotation.setAll(0),
        this._rotationQuaternion = this._rotationQuaternion || Quaternion.Identity(),
        i.decompose(this._scaling, this._rotationQuaternion, this._position),
        this.computeWorldMatrix(!0)) : (this._worldMatrix = i,
        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(i) {
        if (!i)
            return this;
        var o, s, c;
        if (i.x === void 0) {
            if (arguments.length < 3)
                return this;
            o = arguments[0],
            s = arguments[1],
            c = arguments[2]
        } else
            o = i.x,
            s = i.y,
            c = i.z;
        if (this.parent) {
            var d = TmpVectors.Matrix[0];
            this.parent.getWorldMatrix().invertToRef(d),
            Vector3.TransformCoordinatesFromFloatsToRef(o, s, c, d, this.position)
        } else
            this.position.x = o,
            this.position.y = s,
            this.position.z = c;
        return this._absolutePosition.copyFrom(i),
        this
    }
    ,
    e.prototype.setPositionWithLocalVector = function(i) {
        return this.computeWorldMatrix(),
        this.position = Vector3.TransformNormal(i, this._localMatrix),
        this
    }
    ,
    e.prototype.getPositionExpressedInLocalSpace = function() {
        this.computeWorldMatrix();
        var i = TmpVectors.Matrix[0];
        return this._localMatrix.invertToRef(i),
        Vector3.TransformNormal(this.position, i)
    }
    ,
    e.prototype.locallyTranslate = function(i) {
        return this.computeWorldMatrix(!0),
        this.position = Vector3.TransformCoordinates(i, this._localMatrix),
        this
    }
    ,
    e.prototype.lookAt = function(i, o, s, c, d) {
        o === void 0 && (o = 0),
        s === void 0 && (s = 0),
        c === void 0 && (c = 0),
        d === void 0 && (d = Space.LOCAL);
        var _ = e._lookAtVectorCache
          , b = d === Space.LOCAL ? this.position : this.getAbsolutePosition();
        if (i.subtractToRef(b, _),
        this.setDirection(_, o, s, c),
        d === Space.WORLD && this.parent)
            if (this.rotationQuaternion) {
                var k = TmpVectors.Matrix[0];
                this.rotationQuaternion.toRotationMatrix(k);
                var j = TmpVectors.Matrix[1];
                this.parent.getWorldMatrix().getRotationMatrixToRef(j),
                j.invert(),
                k.multiplyToRef(j, k),
                this.rotationQuaternion.fromRotationMatrix(k)
            } else {
                var $ = TmpVectors.Quaternion[0];
                Quaternion.FromEulerVectorToRef(this.rotation, $);
                var k = TmpVectors.Matrix[0];
                $.toRotationMatrix(k);
                var j = TmpVectors.Matrix[1];
                this.parent.getWorldMatrix().getRotationMatrixToRef(j),
                j.invert(),
                k.multiplyToRef(j, k),
                $.fromRotationMatrix(k),
                $.toEulerAnglesToRef(this.rotation)
            }
        return this
    }
    ,
    e.prototype.getDirection = function(i) {
        var o = Vector3.Zero();
        return this.getDirectionToRef(i, o),
        o
    }
    ,
    e.prototype.getDirectionToRef = function(i, o) {
        return Vector3.TransformNormalToRef(i, this.getWorldMatrix(), o),
        this
    }
    ,
    e.prototype.setDirection = function(i, o, s, c) {
        o === void 0 && (o = 0),
        s === void 0 && (s = 0),
        c === void 0 && (c = 0);
        var d = -Math.atan2(i.z, i.x) + Math.PI / 2
          , _ = Math.sqrt(i.x * i.x + i.z * i.z)
          , b = -Math.atan2(i.y, _);
        return this.rotationQuaternion ? Quaternion.RotationYawPitchRollToRef(d + o, b + s, c, this.rotationQuaternion) : (this.rotation.x = b + s,
        this.rotation.y = d + o,
        this.rotation.z = c),
        this
    }
    ,
    e.prototype.setPivotPoint = function(i, o) {
        o === void 0 && (o = Space.LOCAL),
        this.getScene().getRenderId() == 0 && this.computeWorldMatrix(!0);
        var s = this.getWorldMatrix();
        if (o == Space.WORLD) {
            var c = TmpVectors.Matrix[0];
            s.invertToRef(c),
            i = Vector3.TransformCoordinates(i, c)
        }
        return this.setPivotMatrix(Matrix.Translation(-i.x, -i.y, -i.z), !0)
    }
    ,
    e.prototype.getPivotPoint = function() {
        var i = Vector3.Zero();
        return this.getPivotPointToRef(i),
        i
    }
    ,
    e.prototype.getPivotPointToRef = function(i) {
        return i.x = -this._pivotMatrix.m[12],
        i.y = -this._pivotMatrix.m[13],
        i.z = -this._pivotMatrix.m[14],
        this
    }
    ,
    e.prototype.getAbsolutePivotPoint = function() {
        var i = Vector3.Zero();
        return this.getAbsolutePivotPointToRef(i),
        i
    }
    ,
    e.prototype.getAbsolutePivotPointToRef = function(i) {
        return this.getPivotPointToRef(i),
        Vector3.TransformCoordinatesToRef(i, this.getWorldMatrix(), i),
        this
    }
    ,
    e.prototype.markAsDirty = function(i) {
        if (this._children)
            for (var o = 0, s = this._children; o < s.length; o++) {
                var c = s[o];
                c.markAsDirty(i)
            }
        return a.prototype.markAsDirty.call(this, i)
    }
    ,
    e.prototype.setParent = function(i, o) {
        if (o === void 0 && (o = !1),
        !i && !this.parent)
            return this;
        var s = TmpVectors.Quaternion[0]
          , c = TmpVectors.Vector3[0]
          , d = TmpVectors.Vector3[1]
          , _ = TmpVectors.Matrix[1];
        Matrix.IdentityToRef(_);
        var b = TmpVectors.Matrix[0];
        this.computeWorldMatrix(!0);
        var k = this.rotationQuaternion;
        return k || (k = e._TmpRotation,
        Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, k)),
        Matrix.ComposeToRef(this.scaling, k, this.position, b),
        this.parent && b.multiplyToRef(this.parent.computeWorldMatrix(!0), b),
        i && (i.computeWorldMatrix(!0).invertToRef(_),
        b.multiplyToRef(_, b)),
        b.decompose(d, s, c, o ? this : void 0),
        this.rotationQuaternion ? this.rotationQuaternion.copyFrom(s) : s.toEulerAnglesToRef(this.rotation),
        this.scaling.copyFrom(d),
        this.position.copyFrom(c),
        this.parent = i,
        this
    }
    ,
    Object.defineProperty(e.prototype, "nonUniformScaling", {
        get: function() {
            return this._nonUniformScaling
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._updateNonUniformScalingState = function(i) {
        return this._nonUniformScaling === i ? !1 : (this._nonUniformScaling = i,
        !0)
    }
    ,
    e.prototype.attachToBone = function(i, o) {
        return this._currentParentWhenAttachingToBone = this.parent,
        this._transformToBoneReferal = o,
        this.parent = i,
        i.getSkeleton().prepare(),
        i.getWorldMatrix().determinant() < 0 && (this.scalingDeterminant *= -1),
        this
    }
    ,
    e.prototype.detachFromBone = function(i) {
        return i === void 0 && (i = !1),
        this.parent ? (this.parent.getWorldMatrix().determinant() < 0 && (this.scalingDeterminant *= -1),
        this._transformToBoneReferal = null,
        i ? this.parent = this._currentParentWhenAttachingToBone : this.parent = null,
        this) : (i && (this.parent = this._currentParentWhenAttachingToBone),
        this)
    }
    ,
    e.prototype.rotate = function(i, o, s) {
        i.normalize(),
        this.rotationQuaternion || (this.rotationQuaternion = this.rotation.toQuaternion(),
        this.rotation.setAll(0));
        var c;
        if (!s || s === Space.LOCAL)
            c = Quaternion.RotationAxisToRef(i, o, e._rotationAxisCache),
            this.rotationQuaternion.multiplyToRef(c, this.rotationQuaternion);
        else {
            if (this.parent) {
                var d = TmpVectors.Matrix[0];
                this.parent.getWorldMatrix().invertToRef(d),
                i = Vector3.TransformNormal(i, d)
            }
            c = Quaternion.RotationAxisToRef(i, o, e._rotationAxisCache),
            c.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion)
        }
        return this
    }
    ,
    e.prototype.rotateAround = function(i, o, s) {
        o.normalize(),
        this.rotationQuaternion || (this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z),
        this.rotation.setAll(0));
        var c = TmpVectors.Vector3[0]
          , d = TmpVectors.Vector3[1]
          , _ = TmpVectors.Vector3[2]
          , b = TmpVectors.Quaternion[0]
          , k = TmpVectors.Matrix[0]
          , j = TmpVectors.Matrix[1]
          , $ = TmpVectors.Matrix[2]
          , _e = TmpVectors.Matrix[3];
        return i.subtractToRef(this.position, c),
        Matrix.TranslationToRef(c.x, c.y, c.z, k),
        Matrix.TranslationToRef(-c.x, -c.y, -c.z, j),
        Matrix.RotationAxisToRef(o, s, $),
        j.multiplyToRef($, _e),
        _e.multiplyToRef(k, _e),
        _e.decompose(d, b, _),
        this.position.addInPlace(_),
        b.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion),
        this
    }
    ,
    e.prototype.translate = function(i, o, s) {
        var c = i.scale(o);
        if (!s || s === Space.LOCAL) {
            var d = this.getPositionExpressedInLocalSpace().add(c);
            this.setPositionWithLocalVector(d)
        } else
            this.setAbsolutePosition(this.getAbsolutePosition().add(c));
        return this
    }
    ,
    e.prototype.addRotation = function(i, o, s) {
        var c;
        this.rotationQuaternion ? c = this.rotationQuaternion : (c = TmpVectors.Quaternion[1],
        Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, c));
        var d = TmpVectors.Quaternion[0];
        return Quaternion.RotationYawPitchRollToRef(o, i, s, d),
        c.multiplyInPlace(d),
        this.rotationQuaternion || c.toEulerAnglesToRef(this.rotation),
        this
    }
    ,
    e.prototype._getEffectiveParent = function() {
        return this.parent
    }
    ,
    e.prototype.computeWorldMatrix = function(i) {
        if (this._isWorldMatrixFrozen && !this._isDirty)
            return this._worldMatrix;
        var o = this.getScene().getRenderId();
        if (!this._isDirty && !i && this.isSynchronized())
            return this._currentRenderId = o,
            this._worldMatrix;
        var s = this.getScene().activeCamera
          , c = (this._billboardMode & e.BILLBOARDMODE_USE_POSITION) !== 0
          , d = this._billboardMode !== e.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;
        d && s && c && (this.lookAt(s.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 _ = this._cache;
        _.pivotMatrixUpdated = !1,
        _.billboardMode = this.billboardMode,
        _.infiniteDistance = this.infiniteDistance,
        this._currentRenderId = o,
        this._childUpdateId += 1,
        this._isDirty = !1,
        this._position._isDirty = !1,
        this._rotation._isDirty = !1,
        this._scaling._isDirty = !1;
        var b = this._getEffectiveParent()
          , k = e._TmpScaling
          , j = this._position;
        if (this._infiniteDistance && !this.parent && s) {
            var $ = s.getWorldMatrix()
              , _e = new Vector3($.m[12],$.m[13],$.m[14]);
            j = e._TmpTranslation,
            j.copyFromFloats(this._position.x + _e.x, this._position.y + _e.y, this._position.z + _e.z)
        }
        k.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant);
        var et;
        if (this._rotationQuaternion) {
            if (this._rotationQuaternion._isDirty = !1,
            et = this._rotationQuaternion,
            this.reIntegrateRotationIntoRotationQuaternion) {
                var tt = this.rotation.lengthSquared();
                tt && (this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z)),
                this._rotation.copyFromFloats(0, 0, 0))
            }
        } else
            et = e._TmpRotation,
            Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, et);
        if (this._usePivotMatrix) {
            var rt = TmpVectors.Matrix[1];
            Matrix.ScalingToRef(k.x, k.y, k.z, rt);
            var it = TmpVectors.Matrix[0];
            et.toRotationMatrix(it),
            this._pivotMatrix.multiplyToRef(rt, TmpVectors.Matrix[4]),
            TmpVectors.Matrix[4].multiplyToRef(it, this._localMatrix),
            this._postMultiplyPivotMatrix && this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix),
            this._localMatrix.addTranslationFromFloats(j.x, j.y, j.z)
        } else
            Matrix.ComposeToRef(k, et, j, this._localMatrix);
        if (b && b.getWorldMatrix) {
            if (i && b.computeWorldMatrix(i),
            d) {
                this._transformToBoneReferal ? b.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]) : TmpVectors.Matrix[7].copyFrom(b.getWorldMatrix());
                var nt = TmpVectors.Vector3[5]
                  , ot = TmpVectors.Vector3[6];
                TmpVectors.Matrix[7].decompose(ot, void 0, nt),
                Matrix.ScalingToRef(ot.x, ot.y, ot.z, TmpVectors.Matrix[7]),
                TmpVectors.Matrix[7].setTranslation(nt),
                this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix)
            } else
                this._transformToBoneReferal ? (this._localMatrix.multiplyToRef(b.getWorldMatrix(), TmpVectors.Matrix[6]),
                TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix)) : this._localMatrix.multiplyToRef(b.getWorldMatrix(), this._worldMatrix);
            this._markSyncedWithParent()
        } else
            this._worldMatrix.copyFrom(this._localMatrix);
        if (d && s && this.billboardMode && !c) {
            var at = TmpVectors.Vector3[0];
            if (this._worldMatrix.getTranslationToRef(at),
            TmpVectors.Matrix[1].copyFrom(s.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 st = TmpVectors.Vector3[1];
                TmpVectors.Quaternion[0].toEulerAnglesToRef(st),
                (this.billboardMode & e.BILLBOARDMODE_X) !== e.BILLBOARDMODE_X && (st.x = 0),
                (this.billboardMode & e.BILLBOARDMODE_Y) !== e.BILLBOARDMODE_Y && (st.y = 0),
                (this.billboardMode & e.BILLBOARDMODE_Z) !== e.BILLBOARDMODE_Z && (st.z = 0),
                Matrix.RotationYawPitchRollToRef(st.y, st.x, st.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) : b && b._nonUniformScaling ? this._updateNonUniformScalingState(b._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(i) {
        if (i === void 0 && (i = !0),
        this.computeWorldMatrix(),
        i)
            for (var o = this.getChildren(), s = 0; s < o.length; ++s) {
                var c = o[s];
                if (c) {
                    c.computeWorldMatrix();
                    var d = TmpVectors.Matrix[0];
                    c._localMatrix.multiplyToRef(this._localMatrix, d);
                    var _ = TmpVectors.Quaternion[0];
                    d.decompose(c.scaling, _, c.position),
                    c.rotationQuaternion ? c.rotationQuaternion.copyFrom(_) : _.toEulerAnglesToRef(c.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(i) {
        return this.onAfterWorldMatrixUpdateObservable.add(i),
        this
    }
    ,
    e.prototype.unregisterAfterWorldMatrixUpdate = function(i) {
        return this.onAfterWorldMatrixUpdateObservable.removeCallback(i),
        this
    }
    ,
    e.prototype.getPositionInCameraSpace = function(i) {
        return i === void 0 && (i = null),
        i || (i = this.getScene().activeCamera),
        Vector3.TransformCoordinates(this.getAbsolutePosition(), i.getViewMatrix())
    }
    ,
    e.prototype.getDistanceToCamera = function(i) {
        return i === void 0 && (i = null),
        i || (i = this.getScene().activeCamera),
        this.getAbsolutePosition().subtract(i.globalPosition).length()
    }
    ,
    e.prototype.clone = function(i, o, s) {
        var c = this
          , d = SerializationHelper.Clone(function() {
            return new e(i,c.getScene())
        }, this);
        if (d.name = i,
        d.id = i,
        o && (d.parent = o),
        !s)
            for (var _ = this.getDescendants(!0), b = 0; b < _.length; b++) {
                var k = _[b];
                k.clone && k.clone(i + "." + k.name, d)
            }
        return d
    }
    ,
    e.prototype.serialize = function(i) {
        var o = SerializationHelper.Serialize(this, i);
        return o.type = this.getClassName(),
        o.uniqueId = this.uniqueId,
        this.parent && (o.parentId = this.parent.uniqueId),
        o.localMatrix = this.getPivotMatrix().asArray(),
        o.isEnabled = this.isEnabled(),
        this.parent && (o.parentId = this.parent.uniqueId),
        o
    }
    ,
    e.Parse = function(i, o, s) {
        var c = SerializationHelper.Parse(function() {
            return new e(i.name,o)
        }, i, o, s);
        return i.localMatrix ? c.setPreTransformMatrix(Matrix.FromArray(i.localMatrix)) : i.pivotMatrix && c.setPivotMatrix(Matrix.FromArray(i.pivotMatrix)),
        c.setEnabled(i.isEnabled),
        i.parentId && (c._waitingParentId = i.parentId),
        c
    }
    ,
    e.prototype.getChildTransformNodes = function(i, o) {
        var s = [];
        return this._getDescendants(s, i, function(c) {
            return (!o || o(c)) && c instanceof e
        }),
        s
    }
    ,
    e.prototype.dispose = function(i, o) {
        if (o === void 0 && (o = !1),
        this.getScene().stopAnimation(this),
        this.getScene().removeTransformNode(this),
        this._parentContainer) {
            var s = this._parentContainer.transformNodes.indexOf(this);
            s > -1 && this._parentContainer.transformNodes.splice(s, 1),
            this._parentContainer = null
        }
        if (this.onAfterWorldMatrixUpdateObservable.clear(),
        i)
            for (var c = this.getChildTransformNodes(!0), d = 0, _ = c; d < _.length; d++) {
                var b = _[d];
                b.parent = null,
                b.computeWorldMatrix(!0)
            }
        a.prototype.dispose.call(this, i, o)
    }
    ,
    e.prototype.normalizeToUnitCube = function(i, o, s) {
        i === void 0 && (i = !0),
        o === void 0 && (o = !1);
        var c = null
          , d = null;
        o && (this.rotationQuaternion ? (d = this.rotationQuaternion.clone(),
        this.rotationQuaternion.copyFromFloats(0, 0, 0, 1)) : this.rotation && (c = this.rotation.clone(),
        this.rotation.copyFromFloats(0, 0, 0)));
        var _ = this.getHierarchyBoundingVectors(i, s)
          , b = _.max.subtract(_.min)
          , k = Math.max(b.x, b.y, b.z);
        if (k === 0)
            return this;
        var j = 1 / k;
        return this.scaling.scaleInPlace(j),
        o && (this.rotationQuaternion && d ? this.rotationQuaternion.copyFrom(d) : this.rotation && c && this.rotation.copyFrom(c)),
        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)
  , PickingInfo = function() {
    function a() {
        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 a.prototype.getNormal = function(e, i) {
        if (e === void 0 && (e = !1),
        i === void 0 && (i = !0),
        !this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(VertexBuffer.NormalKind))
            return null;
        var o = this.pickedMesh.getIndices();
        if (!o)
            return null;
        var s;
        if (i) {
            var c = this.pickedMesh.getVerticesData(VertexBuffer.NormalKind)
              , d = Vector3.FromArray(c, o[this.faceId * 3] * 3)
              , _ = Vector3.FromArray(c, o[this.faceId * 3 + 1] * 3)
              , b = Vector3.FromArray(c, o[this.faceId * 3 + 2] * 3);
            d = d.scale(this.bu),
            _ = _.scale(this.bv),
            b = b.scale(1 - this.bu - this.bv),
            s = new Vector3(d.x + _.x + b.x,d.y + _.y + b.y,d.z + _.z + b.z)
        } else {
            var k = this.pickedMesh.getVerticesData(VertexBuffer.PositionKind)
              , j = Vector3.FromArray(k, o[this.faceId * 3] * 3)
              , $ = Vector3.FromArray(k, o[this.faceId * 3 + 1] * 3)
              , _e = Vector3.FromArray(k, o[this.faceId * 3 + 2] * 3)
              , et = j.subtract($)
              , tt = _e.subtract($);
            s = Vector3.Cross(et, tt)
        }
        if (e) {
            var rt = this.pickedMesh.getWorldMatrix();
            this.pickedMesh.nonUniformScaling && (TmpVectors.Matrix[0].copyFrom(rt),
            rt = TmpVectors.Matrix[0],
            rt.setTranslationFromFloats(0, 0, 0),
            rt.invert(),
            rt.transposeToRef(TmpVectors.Matrix[1]),
            rt = TmpVectors.Matrix[1]),
            s = Vector3.TransformNormal(s, rt)
        }
        return s.normalize(),
        s
    }
    ,
    a.prototype.getTextureCoordinates = function() {
        if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(VertexBuffer.UVKind))
            return null;
        var e = this.pickedMesh.getIndices();
        if (!e)
            return null;
        var i = this.pickedMesh.getVerticesData(VertexBuffer.UVKind);
        if (!i)
            return null;
        var o = Vector2.FromArray(i, e[this.faceId * 3] * 2)
          , s = Vector2.FromArray(i, e[this.faceId * 3 + 1] * 2)
          , c = Vector2.FromArray(i, e[this.faceId * 3 + 2] * 2);
        return o = o.scale(this.bu),
        s = s.scale(this.bv),
        c = c.scale(1 - this.bu - this.bv),
        new Vector2(o.x + s.x + c.x,o.y + s.y + c.y)
    }
    ,
    a
}()
  , BoundingBox = function() {
    function a(e, i, o) {
        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, i, o)
    }
    return a.prototype.reConstruct = function(e, i, o) {
        var s = e.x
          , c = e.y
          , d = e.z
          , _ = i.x
          , b = i.y
          , k = i.z
          , j = this.vectors;
        this.minimum.copyFromFloats(s, c, d),
        this.maximum.copyFromFloats(_, b, k),
        j[0].copyFromFloats(s, c, d),
        j[1].copyFromFloats(_, b, k),
        j[2].copyFromFloats(_, c, d),
        j[3].copyFromFloats(s, b, d),
        j[4].copyFromFloats(s, c, k),
        j[5].copyFromFloats(_, b, d),
        j[6].copyFromFloats(s, b, k),
        j[7].copyFromFloats(_, c, k),
        i.addToRef(e, this.center).scaleInPlace(.5),
        i.subtractToRef(e, this.extendSize).scaleInPlace(.5),
        this._worldMatrix = o || Matrix.IdentityReadOnly,
        this._update(this._worldMatrix)
    }
    ,
    a.prototype.scale = function(e) {
        var i = a.TmpVector3
          , o = this.maximum.subtractToRef(this.minimum, i[0])
          , s = o.length();
        o.normalizeFromLength(s);
        var c = s * e
          , d = o.scaleInPlace(c * .5)
          , _ = this.center.subtractToRef(d, i[1])
          , b = this.center.addToRef(d, i[2]);
        return this.reConstruct(_, b, this._worldMatrix),
        this
    }
    ,
    a.prototype.getWorldMatrix = function() {
        return this._worldMatrix
    }
    ,
    a.prototype._update = function(e) {
        var i = this.minimumWorld
          , o = this.maximumWorld
          , s = this.directions
          , c = this.vectorsWorld
          , d = this.vectors;
        if (e.isIdentity()) {
            i.copyFrom(this.minimum),
            o.copyFrom(this.maximum);
            for (var _ = 0; _ < 8; ++_)
                c[_].copyFrom(d[_]);
            this.extendSizeWorld.copyFrom(this.extendSize),
            this.centerWorld.copyFrom(this.center)
        } else {
            i.setAll(Number.MAX_VALUE),
            o.setAll(-Number.MAX_VALUE);
            for (var _ = 0; _ < 8; ++_) {
                var b = c[_];
                Vector3.TransformCoordinatesToRef(d[_], e, b),
                i.minimizeInPlace(b),
                o.maximizeInPlace(b)
            }
            o.subtractToRef(i, this.extendSizeWorld).scaleInPlace(.5),
            o.addToRef(i, this.centerWorld).scaleInPlace(.5)
        }
        Vector3.FromArrayToRef(e.m, 0, s[0]),
        Vector3.FromArrayToRef(e.m, 4, s[1]),
        Vector3.FromArrayToRef(e.m, 8, s[2]),
        this._worldMatrix = e
    }
    ,
    a.prototype.isInFrustum = function(e) {
        return a.IsInFrustum(this.vectorsWorld, e)
    }
    ,
    a.prototype.isCompletelyInFrustum = function(e) {
        return a.IsCompletelyInFrustum(this.vectorsWorld, e)
    }
    ,
    a.prototype.intersectsPoint = function(e) {
        var i = this.minimumWorld
          , o = this.maximumWorld
          , s = i.x
          , c = i.y
          , d = i.z
          , _ = o.x
          , b = o.y
          , k = o.z
          , j = e.x
          , $ = e.y
          , _e = e.z
          , et = -Epsilon;
        return !(_ - j < et || et > j - s || b - $ < et || et > $ - c || k - _e < et || et > _e - d)
    }
    ,
    a.prototype.intersectsSphere = function(e) {
        return a.IntersectsSphere(this.minimumWorld, this.maximumWorld, e.centerWorld, e.radiusWorld)
    }
    ,
    a.prototype.intersectsMinMax = function(e, i) {
        var o = this.minimumWorld
          , s = this.maximumWorld
          , c = o.x
          , d = o.y
          , _ = o.z
          , b = s.x
          , k = s.y
          , j = s.z
          , $ = e.x
          , _e = e.y
          , et = e.z
          , tt = i.x
          , rt = i.y
          , it = i.z;
        return !(b < $ || c > tt || k < _e || d > rt || j < et || _ > it)
    }
    ,
    a.prototype.dispose = function() {
        var e, i;
        (e = this._drawWrapperFront) === null || e === void 0 || e.dispose(),
        (i = this._drawWrapperBack) === null || i === void 0 || i.dispose()
    }
    ,
    a.Intersects = function(e, i) {
        return e.intersectsMinMax(i.minimumWorld, i.maximumWorld)
    }
    ,
    a.IntersectsSphere = function(e, i, o, s) {
        var c = a.TmpVector3[0];
        Vector3.ClampToRef(o, e, i, c);
        var d = Vector3.DistanceSquared(o, c);
        return d <= s * s
    }
    ,
    a.IsCompletelyInFrustum = function(e, i) {
        for (var o = 0; o < 6; ++o)
            for (var s = i[o], c = 0; c < 8; ++c)
                if (s.dotCoordinate(e[c]) < 0)
                    return !1;
        return !0
    }
    ,
    a.IsInFrustum = function(e, i) {
        for (var o = 0; o < 6; ++o) {
            for (var s = !0, c = i[o], d = 0; d < 8; ++d)
                if (c.dotCoordinate(e[d]) >= 0) {
                    s = !1;
                    break
                }
            if (s)
                return !1
        }
        return !0
    }
    ,
    a.TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero),
    a
}()
  , BoundingSphere = function() {
    function a(e, i, o) {
        this.center = Vector3.Zero(),
        this.centerWorld = Vector3.Zero(),
        this.minimum = Vector3.Zero(),
        this.maximum = Vector3.Zero(),
        this.reConstruct(e, i, o)
    }
    return a.prototype.reConstruct = function(e, i, o) {
        this.minimum.copyFrom(e),
        this.maximum.copyFrom(i);
        var s = Vector3.Distance(e, i);
        i.addToRef(e, this.center).scaleInPlace(.5),
        this.radius = s * .5,
        this._update(o || Matrix.IdentityReadOnly)
    }
    ,
    a.prototype.scale = function(e) {
        var i = this.radius * e
          , o = a.TmpVector3
          , s = o[0].setAll(i)
          , c = this.center.subtractToRef(s, o[1])
          , d = this.center.addToRef(s, o[2]);
        return this.reConstruct(c, d, this._worldMatrix),
        this
    }
    ,
    a.prototype.getWorldMatrix = function() {
        return this._worldMatrix
    }
    ,
    a.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 i = a.TmpVector3[0];
            Vector3.TransformNormalFromFloatsToRef(1, 1, 1, e, i),
            this.radiusWorld = Math.max(Math.abs(i.x), Math.abs(i.y), Math.abs(i.z)) * this.radius
        }
    }
    ,
    a.prototype.isInFrustum = function(e) {
        for (var i = this.centerWorld, o = this.radiusWorld, s = 0; s < 6; s++)
            if (e[s].dotCoordinate(i) <= -o)
                return !1;
        return !0
    }
    ,
    a.prototype.isCenterInFrustum = function(e) {
        for (var i = this.centerWorld, o = 0; o < 6; o++)
            if (e[o].dotCoordinate(i) < 0)
                return !1;
        return !0
    }
    ,
    a.prototype.intersectsPoint = function(e) {
        var i = Vector3.DistanceSquared(this.centerWorld, e);
        return !(this.radiusWorld * this.radiusWorld < i)
    }
    ,
    a.Intersects = function(e, i) {
        var o = Vector3.DistanceSquared(e.centerWorld, i.centerWorld)
          , s = e.radiusWorld + i.radiusWorld;
        return !(s * s < o)
    }
    ,
    a.CreateFromCenterAndRadius = function(e, i, o) {
        this.TmpVector3[0].copyFrom(e),
        this.TmpVector3[1].copyFromFloats(0, 0, i),
        this.TmpVector3[2].copyFrom(e),
        this.TmpVector3[0].addInPlace(this.TmpVector3[1]),
        this.TmpVector3[2].subtractInPlace(this.TmpVector3[1]);
        var s = new a(this.TmpVector3[0],this.TmpVector3[2]);
        return o ? s._worldMatrix = o : s._worldMatrix = Matrix.Identity(),
        s
    }
    ,
    a.TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero),
    a
}()
  , _result0 = {
    min: 0,
    max: 0
}
  , _result1 = {
    min: 0,
    max: 0
}
  , computeBoxExtents = function(a, e, i) {
    var o = Vector3.Dot(e.centerWorld, a)
      , s = Math.abs(Vector3.Dot(e.directions[0], a)) * e.extendSize.x
      , c = Math.abs(Vector3.Dot(e.directions[1], a)) * e.extendSize.y
      , d = Math.abs(Vector3.Dot(e.directions[2], a)) * e.extendSize.z
      , _ = s + c + d;
    i.min = o - _,
    i.max = o + _
}
  , axisOverlap = function(a, e, i) {
    return computeBoxExtents(a, e, _result0),
    computeBoxExtents(a, i, _result1),
    !(_result0.min > _result1.max || _result1.min > _result0.max)
}
  , BoundingInfo = function() {
    function a(e, i, o) {
        this._isLocked = !1,
        this.boundingBox = new BoundingBox(e,i,o),
        this.boundingSphere = new BoundingSphere(e,i,o)
    }
    return a.prototype.reConstruct = function(e, i, o) {
        this.boundingBox.reConstruct(e, i, o),
        this.boundingSphere.reConstruct(e, i, o)
    }
    ,
    Object.defineProperty(a.prototype, "minimum", {
        get: function() {
            return this.boundingBox.minimum
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "maximum", {
        get: function() {
            return this.boundingBox.maximum
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isLocked", {
        get: function() {
            return this._isLocked
        },
        set: function(e) {
            this._isLocked = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.update = function(e) {
        this._isLocked || (this.boundingBox._update(e),
        this.boundingSphere._update(e))
    }
    ,
    a.prototype.centerOn = function(e, i) {
        var o = a.TmpVector3[0].copyFrom(e).subtractInPlace(i)
          , s = a.TmpVector3[1].copyFrom(e).addInPlace(i);
        return this.boundingBox.reConstruct(o, s, this.boundingBox.getWorldMatrix()),
        this.boundingSphere.reConstruct(o, s, this.boundingBox.getWorldMatrix()),
        this
    }
    ,
    a.prototype.encapsulate = function(e) {
        var i = Vector3.Minimize(this.minimum, e)
          , o = Vector3.Maximize(this.maximum, e);
        return this.reConstruct(i, o, this.boundingBox.getWorldMatrix()),
        this
    }
    ,
    a.prototype.encapsulateBoundingInfo = function(e) {
        return this.encapsulate(e.boundingBox.centerWorld.subtract(e.boundingBox.extendSizeWorld)),
        this.encapsulate(e.boundingBox.centerWorld.add(e.boundingBox.extendSizeWorld)),
        this
    }
    ,
    a.prototype.scale = function(e) {
        return this.boundingBox.scale(e),
        this.boundingSphere.scale(e),
        this
    }
    ,
    a.prototype.isInFrustum = function(e, i) {
        i === void 0 && (i = 0);
        var o = i === 2 || i === 3;
        if (o && this.boundingSphere.isCenterInFrustum(e))
            return !0;
        if (!this.boundingSphere.isInFrustum(e))
            return !1;
        var s = i === 1 || i === 3;
        return s ? !0 : this.boundingBox.isInFrustum(e)
    }
    ,
    Object.defineProperty(a.prototype, "diagonalLength", {
        get: function() {
            var e = this.boundingBox
              , i = e.maximumWorld.subtractToRef(e.minimumWorld, a.TmpVector3[0]);
            return i.length()
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.isCompletelyInFrustum = function(e) {
        return this.boundingBox.isCompletelyInFrustum(e)
    }
    ,
    a.prototype._checkCollision = function(e) {
        return e._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld)
    }
    ,
    a.prototype.intersectsPoint = function(e) {
        return !(!this.boundingSphere.centerWorld || !this.boundingSphere.intersectsPoint(e) || !this.boundingBox.intersectsPoint(e))
    }
    ,
    a.prototype.intersects = function(e, i) {
        if (!BoundingSphere.Intersects(this.boundingSphere, e.boundingSphere) || !BoundingBox.Intersects(this.boundingBox, e.boundingBox))
            return !1;
        if (!i)
            return !0;
        var o = this.boundingBox
          , s = e.boundingBox;
        return !(!axisOverlap(o.directions[0], o, s) || !axisOverlap(o.directions[1], o, s) || !axisOverlap(o.directions[2], o, s) || !axisOverlap(s.directions[0], o, s) || !axisOverlap(s.directions[1], o, s) || !axisOverlap(s.directions[2], o, s) || !axisOverlap(Vector3.Cross(o.directions[0], s.directions[0]), o, s) || !axisOverlap(Vector3.Cross(o.directions[0], s.directions[1]), o, s) || !axisOverlap(Vector3.Cross(o.directions[0], s.directions[2]), o, s) || !axisOverlap(Vector3.Cross(o.directions[1], s.directions[0]), o, s) || !axisOverlap(Vector3.Cross(o.directions[1], s.directions[1]), o, s) || !axisOverlap(Vector3.Cross(o.directions[1], s.directions[2]), o, s) || !axisOverlap(Vector3.Cross(o.directions[2], s.directions[0]), o, s) || !axisOverlap(Vector3.Cross(o.directions[2], s.directions[1]), o, s) || !axisOverlap(Vector3.Cross(o.directions[2], s.directions[2]), o, s))
    }
    ,
    a.TmpVector3 = ArrayTools.BuildArray(2, Vector3.Zero),
    a
}();
ThinEngine.prototype.createUniformBuffer = function(a) {
    var e = this._gl.createBuffer();
    if (!e)
        throw new Error("Unable to create uniform buffer");
    var i = new WebGLDataBuffer(e);
    return this.bindUniformBuffer(i),
    a instanceof Float32Array ? this._gl.bufferData(this._gl.UNIFORM_BUFFER, a, this._gl.STATIC_DRAW) : this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(a), this._gl.STATIC_DRAW),
    this.bindUniformBuffer(null),
    i.references = 1,
    i
}
;
ThinEngine.prototype.createDynamicUniformBuffer = function(a) {
    var e = this._gl.createBuffer();
    if (!e)
        throw new Error("Unable to create dynamic uniform buffer");
    var i = new WebGLDataBuffer(e);
    return this.bindUniformBuffer(i),
    a instanceof Float32Array ? this._gl.bufferData(this._gl.UNIFORM_BUFFER, a, this._gl.DYNAMIC_DRAW) : this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(a), this._gl.DYNAMIC_DRAW),
    this.bindUniformBuffer(null),
    i.references = 1,
    i
}
;
ThinEngine.prototype.updateUniformBuffer = function(a, e, i, o) {
    this.bindUniformBuffer(a),
    i === void 0 && (i = 0),
    o === void 0 ? e instanceof Float32Array ? this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, i, e) : this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, i, new Float32Array(e)) : e instanceof Float32Array ? this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, e.subarray(i, i + o)) : this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(e).subarray(i, i + o)),
    this.bindUniformBuffer(null)
}
;
ThinEngine.prototype.bindUniformBuffer = function(a) {
    this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, a ? a.underlyingResource : null)
}
;
ThinEngine.prototype.bindUniformBufferBase = function(a, e, i) {
    this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, e, a ? a.underlyingResource : null)
}
;
ThinEngine.prototype.bindUniformBlock = function(a, e, i) {
    var o = a.program
      , s = this._gl.getUniformBlockIndex(o, e);
    this._gl.uniformBlockBinding(o, s, i)
}
;
var UniformBuffer = function() {
    function a(e, i, o, s) {
        this._valueCache = {},
        this._engine = e,
        this._noUBO = !e.supportsUniformBuffers,
        this._dynamic = o,
        this._name = s != null ? s : "no-name",
        this._data = i || [],
        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(a.prototype, "useUbo", {
        get: function() {
            return !this._noUBO
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isSync", {
        get: function() {
            return !this._needSync
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.isDynamic = function() {
        return this._dynamic !== void 0
    }
    ,
    a.prototype.getData = function() {
        return this._bufferData
    }
    ,
    a.prototype.getBuffer = function() {
        return this._buffer
    }
    ,
    a.prototype._fillAlignment = function(e) {
        var i;
        if (e <= 2 ? i = e : i = 4,
        this._uniformLocationPointer % i !== 0) {
            var o = this._uniformLocationPointer;
            this._uniformLocationPointer += i - this._uniformLocationPointer % i;
            for (var s = this._uniformLocationPointer - o, c = 0; c < s; c++)
                this._data.push(0)
        }
    }
    ,
    a.prototype.addUniform = function(e, i, o) {
        if (o === void 0 && (o = 0),
        !this._noUBO && this._uniformLocations[e] === void 0) {
            var s;
            if (o > 0) {
                if (i instanceof Array)
                    throw "addUniform should not be use with Array in UBO: " + e;
                if (this._fillAlignment(4),
                this._uniformArraySizes[e] = {
                    strideSize: i,
                    arraySize: o
                },
                i == 16)
                    i = i * o;
                else {
                    var c = 4 - i
                      , d = c * o;
                    i = i * o + d
                }
                s = [];
                for (var _ = 0; _ < i; _++)
                    s.push(0)
            } else {
                if (i instanceof Array)
                    s = i,
                    i = s.length;
                else {
                    i = i,
                    s = [];
                    for (var _ = 0; _ < i; _++)
                        s.push(0)
                }
                this._fillAlignment(i)
            }
            this._uniformSizes[e] = i,
            this._uniformLocations[e] = this._uniformLocationPointer,
            this._uniformLocationPointer += i;
            for (var _ = 0; _ < i; _++)
                this._data.push(s[_]);
            this._needSync = !0
        }
    }
    ,
    a.prototype.addMatrix = function(e, i) {
        this.addUniform(e, Array.prototype.slice.call(i.toArray()))
    }
    ,
    a.prototype.addFloat2 = function(e, i, o) {
        var s = [i, o];
        this.addUniform(e, s)
    }
    ,
    a.prototype.addFloat3 = function(e, i, o, s) {
        var c = [i, o, s];
        this.addUniform(e, c)
    }
    ,
    a.prototype.addColor3 = function(e, i) {
        var o = [i.r, i.g, i.b];
        this.addUniform(e, o)
    }
    ,
    a.prototype.addColor4 = function(e, i, o) {
        var s = [i.r, i.g, i.b, o];
        this.addUniform(e, s)
    }
    ,
    a.prototype.addVector3 = function(e, i) {
        var o = [i.x, i.y, i.z];
        this.addUniform(e, o)
    }
    ,
    a.prototype.addMatrix3x3 = function(e) {
        this.addUniform(e, 12)
    }
    ,
    a.prototype.addMatrix2x2 = function(e) {
        this.addUniform(e, 8)
    }
    ,
    a.prototype.create = function() {
        this._noUBO || this._buffer || (this._fillAlignment(4),
        this._bufferData = new Float32Array(this._data),
        this._rebuild(),
        this._needSync = !0)
    }
    ,
    a.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(a.prototype, "_numBuffers", {
        get: function() {
            return this._buffers.length
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "_indexBuffer", {
        get: function() {
            return this._bufferIndex
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "name", {
        get: function() {
            return this._name
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._buffersEqual = function(e, i) {
        for (var o = 0; o < e.length; ++o)
            if (e[o] !== i[o])
                return !1;
        return !0
    }
    ,
    a.prototype._copyBuffer = function(e, i) {
        for (var o = 0; o < e.length; ++o)
            i[o] = e[o]
    }
    ,
    a.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 && (a._updatedUbosInFrame[this._name] || (a._updatedUbosInFrame[this._name] = 0),
        a._updatedUbosInFrame[this._name]++),
        this._needSync = !1,
        this._createBufferOnWrite = this._engine._features.trackUbosInFrame
    }
    ,
    a.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()
    }
    ,
    a.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)
    }
    ,
    a.prototype.updateUniform = function(e, i, o) {
        this._checkNewFrame();
        var s = this._uniformLocations[e];
        if (s === void 0) {
            if (this._buffer) {
                Logger$2.Error("Cannot add an uniform after UBO has been created.");
                return
            }
            this.addUniform(e, o),
            s = this._uniformLocations[e]
        }
        if (this._buffer || this.create(),
        this._dynamic)
            for (var d = 0; d < o; d++)
                this._bufferData[s + d] = i[d];
        else {
            for (var c = !1, d = 0; d < o; d++)
                (o === 16 && !this._engine._features.uniformBufferHardCheckMatrix || this._bufferData[s + d] !== Tools.FloatRound(i[d])) && (c = !0,
                this._createBufferOnWrite && this._createNewBuffer(),
                this._bufferData[s + d] = i[d]);
            this._needSync = this._needSync || c
        }
    }
    ,
    a.prototype.updateUniformArray = function(e, i, o) {
        this._checkNewFrame();
        var s = this._uniformLocations[e];
        if (s === void 0) {
            Logger$2.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform.");
            return
        }
        this._buffer || this.create();
        var c = this._uniformArraySizes[e];
        if (this._dynamic)
            for (var k = 0; k < o; k++)
                this._bufferData[s + k] = i[k];
        else {
            for (var d = !1, _ = 0, b = 0, k = 0; k < o; k++)
                if (this._bufferData[s + b * 4 + _] !== Tools.FloatRound(i[k]) && (d = !0,
                this._createBufferOnWrite && this._createNewBuffer(),
                this._bufferData[s + b * 4 + _] = i[k]),
                _++,
                _ === c.strideSize) {
                    for (; _ < 4; _++)
                        this._bufferData[s + b * 4 + _] = 0;
                    _ = 0,
                    b++
                }
            this._needSync = this._needSync || d
        }
    }
    ,
    a.prototype._cacheMatrix = function(e, i) {
        this._checkNewFrame();
        var o = this._valueCache[e]
          , s = i.updateFlag;
        return o !== void 0 && o === s ? !1 : (this._valueCache[e] = s,
        !0)
    }
    ,
    a.prototype._updateMatrix3x3ForUniform = function(e, i) {
        for (var o = 0; o < 3; o++)
            a._tempBuffer[o * 4] = i[o * 3],
            a._tempBuffer[o * 4 + 1] = i[o * 3 + 1],
            a._tempBuffer[o * 4 + 2] = i[o * 3 + 2],
            a._tempBuffer[o * 4 + 3] = 0;
        this.updateUniform(e, a._tempBuffer, 12)
    }
    ,
    a.prototype._updateMatrix3x3ForEffect = function(e, i) {
        this._currentEffect.setMatrix3x3(e, i)
    }
    ,
    a.prototype._updateMatrix2x2ForEffect = function(e, i) {
        this._currentEffect.setMatrix2x2(e, i)
    }
    ,
    a.prototype._updateMatrix2x2ForUniform = function(e, i) {
        for (var o = 0; o < 2; o++)
            a._tempBuffer[o * 4] = i[o * 2],
            a._tempBuffer[o * 4 + 1] = i[o * 2 + 1],
            a._tempBuffer[o * 4 + 2] = 0,
            a._tempBuffer[o * 4 + 3] = 0;
        this.updateUniform(e, a._tempBuffer, 8)
    }
    ,
    a.prototype._updateFloatForEffect = function(e, i) {
        this._currentEffect.setFloat(e, i)
    }
    ,
    a.prototype._updateFloatForUniform = function(e, i) {
        a._tempBuffer[0] = i,
        this.updateUniform(e, a._tempBuffer, 1)
    }
    ,
    a.prototype._updateFloat2ForEffect = function(e, i, o, s) {
        s === void 0 && (s = ""),
        this._currentEffect.setFloat2(e + s, i, o)
    }
    ,
    a.prototype._updateFloat2ForUniform = function(e, i, o) {
        a._tempBuffer[0] = i,
        a._tempBuffer[1] = o,
        this.updateUniform(e, a._tempBuffer, 2)
    }
    ,
    a.prototype._updateFloat3ForEffect = function(e, i, o, s, c) {
        c === void 0 && (c = ""),
        this._currentEffect.setFloat3(e + c, i, o, s)
    }
    ,
    a.prototype._updateFloat3ForUniform = function(e, i, o, s) {
        a._tempBuffer[0] = i,
        a._tempBuffer[1] = o,
        a._tempBuffer[2] = s,
        this.updateUniform(e, a._tempBuffer, 3)
    }
    ,
    a.prototype._updateFloat4ForEffect = function(e, i, o, s, c, d) {
        d === void 0 && (d = ""),
        this._currentEffect.setFloat4(e + d, i, o, s, c)
    }
    ,
    a.prototype._updateFloat4ForUniform = function(e, i, o, s, c) {
        a._tempBuffer[0] = i,
        a._tempBuffer[1] = o,
        a._tempBuffer[2] = s,
        a._tempBuffer[3] = c,
        this.updateUniform(e, a._tempBuffer, 4)
    }
    ,
    a.prototype._updateFloatArrayForEffect = function(e, i) {
        this._currentEffect.setFloatArray(e, i)
    }
    ,
    a.prototype._updateFloatArrayForUniform = function(e, i) {
        this.updateUniformArray(e, i, i.length)
    }
    ,
    a.prototype._updateArrayForEffect = function(e, i) {
        this._currentEffect.setArray(e, i)
    }
    ,
    a.prototype._updateArrayForUniform = function(e, i) {
        this.updateUniformArray(e, i, i.length)
    }
    ,
    a.prototype._updateIntArrayForEffect = function(e, i) {
        this._currentEffect.setIntArray(e, i)
    }
    ,
    a.prototype._updateIntArrayForUniform = function(e, i) {
        a._tempBufferInt32View.set(i),
        this.updateUniformArray(e, a._tempBuffer, i.length)
    }
    ,
    a.prototype._updateMatrixForEffect = function(e, i) {
        this._currentEffect.setMatrix(e, i)
    }
    ,
    a.prototype._updateMatrixForUniform = function(e, i) {
        this._cacheMatrix(e, i) && this.updateUniform(e, i.toArray(), 16)
    }
    ,
    a.prototype._updateMatricesForEffect = function(e, i) {
        this._currentEffect.setMatrices(e, i)
    }
    ,
    a.prototype._updateMatricesForUniform = function(e, i) {
        this.updateUniform(e, i, i.length)
    }
    ,
    a.prototype._updateVector3ForEffect = function(e, i) {
        this._currentEffect.setVector3(e, i)
    }
    ,
    a.prototype._updateVector3ForUniform = function(e, i) {
        a._tempBuffer[0] = i.x,
        a._tempBuffer[1] = i.y,
        a._tempBuffer[2] = i.z,
        this.updateUniform(e, a._tempBuffer, 3)
    }
    ,
    a.prototype._updateVector4ForEffect = function(e, i) {
        this._currentEffect.setVector4(e, i)
    }
    ,
    a.prototype._updateVector4ForUniform = function(e, i) {
        a._tempBuffer[0] = i.x,
        a._tempBuffer[1] = i.y,
        a._tempBuffer[2] = i.z,
        a._tempBuffer[3] = i.w,
        this.updateUniform(e, a._tempBuffer, 4)
    }
    ,
    a.prototype._updateColor3ForEffect = function(e, i, o) {
        o === void 0 && (o = ""),
        this._currentEffect.setColor3(e + o, i)
    }
    ,
    a.prototype._updateColor3ForUniform = function(e, i) {
        a._tempBuffer[0] = i.r,
        a._tempBuffer[1] = i.g,
        a._tempBuffer[2] = i.b,
        this.updateUniform(e, a._tempBuffer, 3)
    }
    ,
    a.prototype._updateColor4ForEffect = function(e, i, o, s) {
        s === void 0 && (s = ""),
        this._currentEffect.setColor4(e + s, i, o)
    }
    ,
    a.prototype._updateDirectColor4ForEffect = function(e, i, o) {
        o === void 0 && (o = ""),
        this._currentEffect.setDirectColor4(e + o, i)
    }
    ,
    a.prototype._updateColor4ForUniform = function(e, i, o) {
        a._tempBuffer[0] = i.r,
        a._tempBuffer[1] = i.g,
        a._tempBuffer[2] = i.b,
        a._tempBuffer[3] = o,
        this.updateUniform(e, a._tempBuffer, 4)
    }
    ,
    a.prototype._updateDirectColor4ForUniform = function(e, i) {
        a._tempBuffer[0] = i.r,
        a._tempBuffer[1] = i.g,
        a._tempBuffer[2] = i.b,
        a._tempBuffer[3] = i.a,
        this.updateUniform(e, a._tempBuffer, 4)
    }
    ,
    a.prototype._updateIntForEffect = function(e, i, o) {
        o === void 0 && (o = ""),
        this._currentEffect.setInt(e + o, i)
    }
    ,
    a.prototype._updateIntForUniform = function(e, i) {
        a._tempBufferInt32View[0] = i,
        this.updateUniform(e, a._tempBuffer, 1)
    }
    ,
    a.prototype._updateInt2ForEffect = function(e, i, o, s) {
        s === void 0 && (s = ""),
        this._currentEffect.setInt2(e + s, i, o)
    }
    ,
    a.prototype._updateInt2ForUniform = function(e, i, o) {
        a._tempBufferInt32View[0] = i,
        a._tempBufferInt32View[1] = o,
        this.updateUniform(e, a._tempBuffer, 2)
    }
    ,
    a.prototype._updateInt3ForEffect = function(e, i, o, s, c) {
        c === void 0 && (c = ""),
        this._currentEffect.setInt3(e + c, i, o, s)
    }
    ,
    a.prototype._updateInt3ForUniform = function(e, i, o, s) {
        a._tempBufferInt32View[0] = i,
        a._tempBufferInt32View[1] = o,
        a._tempBufferInt32View[2] = s,
        this.updateUniform(e, a._tempBuffer, 3)
    }
    ,
    a.prototype._updateInt4ForEffect = function(e, i, o, s, c, d) {
        d === void 0 && (d = ""),
        this._currentEffect.setInt4(e + d, i, o, s, c)
    }
    ,
    a.prototype._updateInt4ForUniform = function(e, i, o, s, c) {
        a._tempBufferInt32View[0] = i,
        a._tempBufferInt32View[1] = o,
        a._tempBufferInt32View[2] = s,
        a._tempBufferInt32View[3] = c,
        this.updateUniform(e, a._tempBuffer, 4)
    }
    ,
    a.prototype.setTexture = function(e, i) {
        this._currentEffect.setTexture(e, i)
    }
    ,
    a.prototype.updateUniformDirectly = function(e, i) {
        this.updateUniform(e, i, i.length),
        this.update()
    }
    ,
    a.prototype.bindToEffect = function(e, i) {
        this._currentEffect = e,
        this._currentEffectName = i
    }
    ,
    a.prototype.bindUniformBuffer = function() {
        !this._noUBO && this._buffer && this._currentEffect && this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName)
    }
    ,
    a.prototype.unbindEffect = function() {
        this._currentEffect = void 0,
        this._currentEffectName = void 0
    }
    ,
    a.prototype.dispose = function() {
        if (!this._noUBO) {
            var e = this._engine._uniformBuffers
              , i = e.indexOf(this);
            if (i !== -1 && (e[i] = e[e.length - 1],
            e.pop()),
            this._engine._features.trackUbosInFrame && this._buffers)
                for (var o = 0; o < this._buffers.length; ++o) {
                    var s = this._buffers[o][0];
                    this._engine._releaseBuffer(s)
                }
            else
                this._buffer && this._engine._releaseBuffer(this._buffer) && (this._buffer = null)
        }
    }
    ,
    a._updatedUbosInFrame = {},
    a._MAX_UNIFORM_SIZE = 256,
    a._tempBuffer = new Float32Array(a._MAX_UNIFORM_SIZE),
    a._tempBufferInt32View = new Uint32Array(a._tempBuffer.buffer),
    a
}()
  , _MeshCollisionData = function() {
    function a() {
        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 a
}()
  , MathHelpers = function() {
    function a() {}
    return a.extractMinAndMaxIndexed = function(e, i, o, s, c, d) {
        for (var _ = o; _ < o + s; _++) {
            var b = i[_] * 3
              , k = e[b]
              , j = e[b + 1]
              , $ = e[b + 2];
            c.minimizeInPlaceFromFloats(k, j, $),
            d.maximizeInPlaceFromFloats(k, j, $)
        }
    }
    ,
    a.extractMinAndMax = function(e, i, o, s, c, d) {
        for (var _ = i, b = i * s; _ < i + o; _++,
        b += s) {
            var k = e[b]
              , j = e[b + 1]
              , $ = e[b + 2];
            c.minimizeInPlaceFromFloats(k, j, $),
            d.maximizeInPlaceFromFloats(k, j, $)
        }
    }
    ,
    __decorate([nativeOverride.filter(function() {
        for (var e = [], i = 0; i < arguments.length; i++)
            e[i] = arguments[i];
        var o = e[0]
          , s = e[1];
        return !Array.isArray(o) && !Array.isArray(s)
    })], a, "extractMinAndMaxIndexed", null),
    __decorate([nativeOverride.filter(function() {
        for (var e = [], i = 0; i < arguments.length; i++)
            e[i] = arguments[i];
        var o = e[0];
        return !Array.isArray(o)
    })], a, "extractMinAndMax", null),
    a
}();
function extractMinAndMaxIndexed(a, e, i, o, s) {
    s === void 0 && (s = null);
    var c = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)
      , d = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);
    return MathHelpers.extractMinAndMaxIndexed(a, e, i, o, c, d),
    s && (c.x -= c.x * s.x + s.y,
    c.y -= c.y * s.x + s.y,
    c.z -= c.z * s.x + s.y,
    d.x += d.x * s.x + s.y,
    d.y += d.y * s.x + s.y,
    d.z += d.z * s.x + s.y),
    {
        minimum: c,
        maximum: d
    }
}
function extractMinAndMax(a, e, i, o, s) {
    o === void 0 && (o = null);
    var c = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)
      , d = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);
    return s || (s = 3),
    MathHelpers.extractMinAndMax(a, e, i, s, c, d),
    o && (c.x -= c.x * o.x + o.y,
    c.y -= c.y * o.x + o.y,
    c.z -= c.z * o.x + o.y,
    d.x += d.x * o.x + o.y,
    d.y += d.y * o.x + o.y,
    d.z += d.z * o.x + o.y),
    {
        minimum: c,
        maximum: d
    }
}
var _FacetDataStorage = function() {
    function a() {
        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 a
}()
  , _InternalAbstractMeshDataInfo = function() {
    function a() {
        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 a
}()
  , AbstractMesh = function(a) {
    __extends(e, a);
    function e(i, o) {
        o === void 0 && (o = null);
        var s = a.call(this, i, o, !1) || this;
        return s._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo,
        s.cullingStrategy = e.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,
        s.onCollideObservable = new Observable,
        s.onCollisionPositionChangeObservable = new Observable,
        s.onMaterialChangedObservable = new Observable,
        s.definedFacingForward = !0,
        s._occlusionQuery = null,
        s._renderingGroup = null,
        s.alphaIndex = Number.MAX_VALUE,
        s.isVisible = !0,
        s.isPickable = !0,
        s.isNearPickable = !1,
        s.isNearGrabbable = !1,
        s.showSubMeshesBoundingBox = !1,
        s.isBlocker = !1,
        s.enablePointerMoveEvents = !1,
        s.outlineColor = Color3.Red(),
        s.outlineWidth = .02,
        s.overlayColor = Color3.Red(),
        s.overlayAlpha = .5,
        s.useOctreeForRenderingSelection = !0,
        s.useOctreeForPicking = !0,
        s.useOctreeForCollisions = !0,
        s.alwaysSelectAsActiveMesh = !1,
        s.doNotSyncBoundingInfo = !1,
        s.actionManager = null,
        s.ellipsoid = new Vector3(.5,1,.5),
        s.ellipsoidOffset = new Vector3(0,0,0),
        s.edgesWidth = 1,
        s.edgesColor = new Color4(1,0,0,1),
        s._edgesRenderer = null,
        s._masterMesh = null,
        s._boundingInfo = null,
        s._boundingInfoIsDirty = !0,
        s._renderId = 0,
        s._intersectionsInProgress = new Array,
        s._unIndexed = !1,
        s._lightSources = new Array,
        s._waitingData = {
            lods: null,
            actions: null,
            freezeWorldMatrix: null
        },
        s._bonesTransformMatrices = null,
        s._transformMatrixTexture = null,
        s.onRebuildObservable = new Observable,
        s._onCollisionPositionChange = function(c, d, _) {
            _ === void 0 && (_ = null),
            d.subtractToRef(s._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, s._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),
            s._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > Engine.CollisionsEpsilon && s.position.addInPlace(s._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),
            _ && s.onCollideObservable.notifyObservers(_),
            s.onCollisionPositionChangeObservable.notifyObservers(s.position)
        }
        ,
        s.getScene().addMesh(s),
        s._resyncLightSources(),
        s._uniformBuffer = new UniformBuffer(s.getScene().getEngine(),void 0,void 0,i),
        s._buildUniformLayout(),
        s
    }
    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(i) {
            this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "partitioningBBoxRatio", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "mustDepthSortFacets", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.facetDepthSort
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._facetData.facetDepthSort = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "facetDepthSortFrom", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionRetryCount", {
        get: function() {
            return this._internalAbstractMeshDataInfo._collisionRetryCount
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._collisionRetryCount = i
        },
        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(i) {
            this._internalAbstractMeshDataInfo._morphTargetManager !== i && (this._internalAbstractMeshDataInfo._morphTargetManager = i,
            this._syncGeometryWithMorphTargetManager())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bakedVertexAnimationManager", {
        get: function() {
            return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._bakedVertexAnimationManager !== i && (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = i,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._syncGeometryWithMorphTargetManager = function() {}
    ,
    e.prototype._updateNonUniformScalingState = function(i) {
        return a.prototype._updateNonUniformScalingState.call(this, i) ? (this._markSubMeshesAsMiscDirty(),
        !0) : !1
    }
    ,
    Object.defineProperty(e.prototype, "onCollide", {
        set: function(i) {
            this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver && this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),
            this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onCollisionPositionChange", {
        set: function(i) {
            this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver && this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),
            this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "visibility", {
        get: function() {
            return this._internalAbstractMeshDataInfo._visibility
        },
        set: function(i) {
            if (this._internalAbstractMeshDataInfo._visibility !== i) {
                var o = this._internalAbstractMeshDataInfo._visibility;
                this._internalAbstractMeshDataInfo._visibility = i,
                (o === 1 && i !== 1 || o !== 1 && i === 1) && this._markSubMeshesAsMiscDirty()
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "renderingGroupId", {
        get: function() {
            return this._internalAbstractMeshDataInfo._renderingGroupId
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._renderingGroupId = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "material", {
        get: function() {
            return this._internalAbstractMeshDataInfo._material
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._material !== i && (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap && (this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = void 0),
            this._internalAbstractMeshDataInfo._material = i,
            i && i.meshMap && (i.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(i) {
        var o;
        return (o = this._internalAbstractMeshDataInfo._materialForRenderPass) === null || o === void 0 ? void 0 : o[i]
    }
    ,
    e.prototype.setMaterialForRenderPass = function(i, o) {
        this._internalAbstractMeshDataInfo._materialForRenderPass || (this._internalAbstractMeshDataInfo._materialForRenderPass = []),
        this._internalAbstractMeshDataInfo._materialForRenderPass[i] = o
    }
    ,
    Object.defineProperty(e.prototype, "receiveShadows", {
        get: function() {
            return this._internalAbstractMeshDataInfo._receiveShadows
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._receiveShadows !== i && (this._internalAbstractMeshDataInfo._receiveShadows = i,
            this._markSubMeshesAsLightDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasVertexAlpha", {
        get: function() {
            return this._internalAbstractMeshDataInfo._hasVertexAlpha
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._hasVertexAlpha !== i && (this._internalAbstractMeshDataInfo._hasVertexAlpha = i,
            this._markSubMeshesAsAttributesDirty(),
            this._markSubMeshesAsMiscDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useVertexColors", {
        get: function() {
            return this._internalAbstractMeshDataInfo._useVertexColors
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._useVertexColors !== i && (this._internalAbstractMeshDataInfo._useVertexColors = i,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "computeBonesUsingShaders", {
        get: function() {
            return this._internalAbstractMeshDataInfo._computeBonesUsingShaders
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._computeBonesUsingShaders !== i && (this._internalAbstractMeshDataInfo._computeBonesUsingShaders = i,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "numBoneInfluencers", {
        get: function() {
            return this._internalAbstractMeshDataInfo._numBoneInfluencers
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._numBoneInfluencers !== i && (this._internalAbstractMeshDataInfo._numBoneInfluencers = i,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "applyFog", {
        get: function() {
            return this._internalAbstractMeshDataInfo._applyFog
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._applyFog !== i && (this._internalAbstractMeshDataInfo._applyFog = i,
            this._markSubMeshesAsMiscDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "layerMask", {
        get: function() {
            return this._internalAbstractMeshDataInfo._layerMask
        },
        set: function(i) {
            i !== this._internalAbstractMeshDataInfo._layerMask && (this._internalAbstractMeshDataInfo._layerMask = i,
            this._resyncLightSources())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionMask", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = isNaN(i) ? -1 : i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionResponse", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionGroup", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = isNaN(i) ? -1 : i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "surroundingMeshes", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = i
        },
        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(i) {
            var o = this._internalAbstractMeshDataInfo._skeleton;
            o && o.needInitialSkinMatrix && o._unregisterMeshWithPoseMatrix(this),
            i && i.needInitialSkinMatrix && i._registerMeshWithPoseMatrix(this),
            this._internalAbstractMeshDataInfo._skeleton = i,
            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(i) {
        var o = this._uniformBuffer;
        o.updateMatrix("world", i),
        o.updateFloat("visibility", this._internalAbstractMeshDataInfo._visibility),
        o.update()
    }
    ,
    e.prototype.getMeshUniformBuffer = function() {
        return this._uniformBuffer
    }
    ,
    e.prototype.getClassName = function() {
        return "AbstractMesh"
    }
    ,
    e.prototype.toString = function(i) {
        var o = "Name: " + this.name + ", isInstance: " + (this.getClassName() !== "InstancedMesh" ? "YES" : "NO");
        o += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
        var s = this._internalAbstractMeshDataInfo._skeleton;
        return s && (o += ", skeleton: " + s.name),
        i && (o += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode],
        o += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? "YES" : "NO")),
        o
    }
    ,
    e.prototype._getEffectiveParent = function() {
        return this._masterMesh && this.billboardMode !== TransformNode.BILLBOARDMODE_NONE ? this._masterMesh : a.prototype._getEffectiveParent.call(this)
    }
    ,
    e.prototype._getActionManagerForTrigger = function(i, o) {
        if (o === void 0 && (o = !0),
        this.actionManager && (o || this.actionManager.isRecursive))
            if (i) {
                if (this.actionManager.hasSpecificTrigger(i))
                    return this.actionManager
            } else
                return this.actionManager;
        return this.parent ? this.parent._getActionManagerForTrigger(i, !1) : null
    }
    ,
    e.prototype._rebuild = function(i) {
        if (this.onRebuildObservable.notifyObservers(this),
        this._occlusionQuery !== null && (this._occlusionQuery = null),
        !!this.subMeshes)
            for (var o = 0, s = this.subMeshes; o < s.length; o++) {
                var c = s[o];
                c._rebuild()
            }
    }
    ,
    e.prototype._resyncLightSources = function() {
        this._lightSources.length = 0;
        for (var i = 0, o = this.getScene().lights; i < o.length; i++) {
            var s = o[i];
            !s.isEnabled() || s.canAffectMesh(this) && this._lightSources.push(s)
        }
        this._markSubMeshesAsLightDirty()
    }
    ,
    e.prototype._resyncLightSource = function(i) {
        var o = i.isEnabled() && i.canAffectMesh(this)
          , s = this._lightSources.indexOf(i)
          , c = !1;
        if (s === -1) {
            if (!o)
                return;
            this._lightSources.push(i)
        } else {
            if (o)
                return;
            c = !0,
            this._lightSources.splice(s, 1)
        }
        this._markSubMeshesAsLightDirty(c)
    }
    ,
    e.prototype._unBindEffect = function() {
        for (var i = 0, o = this.subMeshes; i < o.length; i++) {
            var s = o[i];
            s.setEffect(null)
        }
    }
    ,
    e.prototype._removeLightSource = function(i, o) {
        var s = this._lightSources.indexOf(i);
        s !== -1 && (this._lightSources.splice(s, 1),
        this._markSubMeshesAsLightDirty(o))
    }
    ,
    e.prototype._markSubMeshesAsDirty = function(i) {
        if (!!this.subMeshes)
            for (var o = 0, s = this.subMeshes; o < s.length; o++)
                for (var c = s[o], d = 0; d < c._drawWrappers.length; ++d) {
                    var _ = c._drawWrappers[d];
                    !_ || !_.defines || !_.defines.markAllAsDirty || i(_.defines)
                }
    }
    ,
    e.prototype._markSubMeshesAsLightDirty = function(i) {
        i === void 0 && (i = !1),
        this._markSubMeshesAsDirty(function(o) {
            return o.markAsLightDirty(i)
        })
    }
    ,
    e.prototype._markSubMeshesAsAttributesDirty = function() {
        this._markSubMeshesAsDirty(function(i) {
            return i.markAsAttributesDirty()
        })
    }
    ,
    e.prototype._markSubMeshesAsMiscDirty = function() {
        this._markSubMeshesAsDirty(function(i) {
            return i.markAsMiscDirty()
        })
    }
    ,
    e.prototype.markAsDirty = function(i) {
        return this._currentRenderId = Number.MAX_VALUE,
        this._isDirty = !0,
        this
    }
    ,
    e.prototype.resetDrawCache = function() {
        if (!!this.subMeshes)
            for (var i = 0, o = this.subMeshes; i < o.length; i++) {
                var s = o[i];
                s.resetDrawCache()
            }
    }
    ,
    Object.defineProperty(e.prototype, "scaling", {
        get: function() {
            return this._scaling
        },
        set: function(i) {
            this._scaling = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isBlocked", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getLOD = function(i) {
        return this
    }
    ,
    e.prototype.getTotalVertices = function() {
        return 0
    }
    ,
    e.prototype.getTotalIndices = function() {
        return 0
    }
    ,
    e.prototype.getIndices = function() {
        return null
    }
    ,
    e.prototype.getVerticesData = function(i) {
        return null
    }
    ,
    e.prototype.setVerticesData = function(i, o, s, c) {
        return this
    }
    ,
    e.prototype.updateVerticesData = function(i, o, s, c) {
        return this
    }
    ,
    e.prototype.setIndices = function(i, o) {
        return this
    }
    ,
    e.prototype.isVerticesDataPresent = function(i) {
        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(i) {
        return this._boundingInfo = i,
        this
    }
    ,
    Object.defineProperty(e.prototype, "hasBoundingInfo", {
        get: function() {
            return this._boundingInfo !== null
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.buildBoundingInfo = function(i, o, s) {
        return this._boundingInfo = new BoundingInfo(i,o,s),
        this._boundingInfo
    }
    ,
    e.prototype.normalizeToUnitCube = function(i, o, s) {
        return i === void 0 && (i = !0),
        o === void 0 && (o = !1),
        a.prototype.normalizeToUnitCube.call(this, i, o, s)
    }
    ,
    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(i) {}
    ,
    e.prototype._activate = function(i, o) {
        return this._renderId = i,
        !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() : a.prototype.getWorldMatrix.call(this)
    }
    ,
    e.prototype._getWorldMatrixDeterminant = function() {
        return this._masterMesh ? this._masterMesh._getWorldMatrixDeterminant() : a.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(i, o, s) {
        return this.position.addInPlace(this.calcMovePOV(i, o, s)),
        this
    }
    ,
    e.prototype.calcMovePOV = function(i, o, s) {
        var c = new Matrix
          , d = this.rotationQuaternion ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
        d.toRotationMatrix(c);
        var _ = Vector3.Zero()
          , b = this.definedFacingForward ? -1 : 1;
        return Vector3.TransformCoordinatesFromFloatsToRef(i * b, o, s * b, c, _),
        _
    }
    ,
    e.prototype.rotatePOV = function(i, o, s) {
        return this.rotation.addInPlace(this.calcRotatePOV(i, o, s)),
        this
    }
    ,
    e.prototype.calcRotatePOV = function(i, o, s) {
        var c = this.definedFacingForward ? 1 : -1;
        return new Vector3(i * c,o,s * c)
    }
    ,
    e.prototype.refreshBoundingInfo = function(i, o) {
        return i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        this._boundingInfo && this._boundingInfo.isLocked ? this : (this._refreshBoundingInfo(this._getPositionData(i, o), null),
        this)
    }
    ,
    e.prototype._refreshBoundingInfo = function(i, o) {
        if (i) {
            var s = extractMinAndMax(i, 0, this.getTotalVertices(), o);
            this._boundingInfo ? this._boundingInfo.reConstruct(s.minimum, s.maximum) : this._boundingInfo = new BoundingInfo(s.minimum,s.maximum)
        }
        if (this.subMeshes)
            for (var c = 0; c < this.subMeshes.length; c++)
                this.subMeshes[c].refreshBoundingInfo(i);
        this._updateBoundingInfo()
    }
    ,
    e.prototype._getPositionData = function(i, o) {
        var s, c = this.getVerticesData(VertexBuffer.PositionKind);
        if (this._internalAbstractMeshDataInfo._positions && (this._internalAbstractMeshDataInfo._positions = null),
        c && (i && this.skeleton || o && this.morphTargetManager) && (c = Tools.Slice(c),
        this._generatePointsArray(),
        this._positions)) {
            var d = this._positions;
            this._internalAbstractMeshDataInfo._positions = new Array(d.length);
            for (var _ = 0; _ < d.length; _++)
                this._internalAbstractMeshDataInfo._positions[_] = ((s = d[_]) === null || s === void 0 ? void 0 : s.clone()) || new Vector3
        }
        if (c && o && this.morphTargetManager)
            for (var b = 0, k = 0, j = 0; j < c.length; j++) {
                for (var $ = 0; $ < this.morphTargetManager.numTargets; $++) {
                    var _e = this.morphTargetManager.getTarget($)
                      , et = _e.influence;
                    if (et > 0) {
                        var tt = _e.getPositions();
                        tt && (c[j] += (tt[j] - c[j]) * et)
                    }
                }
                if (b++,
                this._positions && b === 3) {
                    b = 0;
                    var rt = k * 3;
                    this._positions[k++].copyFromFloats(c[rt], c[rt + 1], c[rt + 2])
                }
            }
        if (c && i && this.skeleton) {
            var it = this.getVerticesData(VertexBuffer.MatricesIndicesKind)
              , nt = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
            if (nt && it) {
                var ot = this.numBoneInfluencers > 4
                  , at = ot ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null
                  , st = ot ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
                this.skeleton.prepare();
                for (var ut = this.skeleton.getTransformMatrices(this), ct = TmpVectors.Vector3[0], lt = TmpVectors.Matrix[0], ft = TmpVectors.Matrix[1], ht = 0, pt = 0; pt < c.length; pt += 3,
                ht += 4) {
                    lt.reset();
                    var dt, _t;
                    for (dt = 0; dt < 4; dt++)
                        _t = nt[ht + dt],
                        _t > 0 && (Matrix.FromFloat32ArrayToRefScaled(ut, Math.floor(it[ht + dt] * 16), _t, ft),
                        lt.addToSelf(ft));
                    if (ot)
                        for (dt = 0; dt < 4; dt++)
                            _t = st[ht + dt],
                            _t > 0 && (Matrix.FromFloat32ArrayToRefScaled(ut, Math.floor(at[ht + dt] * 16), _t, ft),
                            lt.addToSelf(ft));
                    Vector3.TransformCoordinatesFromFloatsToRef(c[pt], c[pt + 1], c[pt + 2], lt, ct),
                    ct.toArray(c, pt),
                    this._positions && this._positions[pt / 3].copyFrom(ct)
                }
            }
        }
        return c
    }
    ,
    e.prototype._updateBoundingInfo = function() {
        var i = this._effectiveMesh;
        return this._boundingInfo ? this._boundingInfo.update(i.worldMatrixFromCache) : this._boundingInfo = new BoundingInfo(this.position,this.position,i.worldMatrixFromCache),
        this._updateSubMeshesBoundingInfo(i.worldMatrixFromCache),
        this
    }
    ,
    e.prototype._updateSubMeshesBoundingInfo = function(i) {
        if (!this.subMeshes)
            return this;
        for (var o = this.subMeshes.length, s = 0; s < o; s++) {
            var c = this.subMeshes[s];
            (o > 1 || !c.IsGlobal) && c.updateBoundingInfo(i)
        }
        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(i) {
        return this.getBoundingInfo().isInFrustum(i, this.cullingStrategy)
    }
    ,
    e.prototype.isCompletelyInFrustum = function(i) {
        return this.getBoundingInfo().isCompletelyInFrustum(i)
    }
    ,
    e.prototype.intersectsMesh = function(i, o, s) {
        o === void 0 && (o = !1);
        var c = this.getBoundingInfo()
          , d = i.getBoundingInfo();
        if (c.intersects(d, o))
            return !0;
        if (s)
            for (var _ = 0, b = this.getChildMeshes(); _ < b.length; _++) {
                var k = b[_];
                if (k.intersectsMesh(i, o, !0))
                    return !0
            }
        return !1
    }
    ,
    e.prototype.intersectsPoint = function(i) {
        return this.getBoundingInfo().intersectsPoint(i)
    }
    ,
    Object.defineProperty(e.prototype, "checkCollisions", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collider", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._collider
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.moveWithCollisions = function(i) {
        var o = this.getAbsolutePosition();
        o.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);
        var s = this.getScene().collisionCoordinator;
        return this._internalAbstractMeshDataInfo._meshCollisionData._collider || (this._internalAbstractMeshDataInfo._meshCollisionData._collider = s.createCollider()),
        this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid,
        s.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, i, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId),
        this
    }
    ,
    e.prototype._collideForSubMesh = function(i, o, s) {
        if (this._generatePointsArray(),
        !this._positions)
            return this;
        if (!i._lastColliderWorldVertices || !i._lastColliderTransformMatrix.equals(o)) {
            i._lastColliderTransformMatrix = o.clone(),
            i._lastColliderWorldVertices = [],
            i._trianglePlanes = [];
            for (var c = i.verticesStart, d = i.verticesStart + i.verticesCount, _ = c; _ < d; _++)
                i._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[_], o))
        }
        return s._collide(i._trianglePlanes, i._lastColliderWorldVertices, this.getIndices(), i.indexStart, i.indexStart + i.indexCount, i.verticesStart, !!i.getMaterial(), this),
        this
    }
    ,
    e.prototype._processCollisionsForSubMeshes = function(i, o) {
        for (var s = this._scene.getCollidingSubMeshCandidates(this, i), c = s.length, d = 0; d < c; d++) {
            var _ = s.data[d];
            c > 1 && !_._checkCollision(i) || this._collideForSubMesh(_, o, i)
        }
        return this
    }
    ,
    e.prototype._checkCollision = function(i) {
        if (!this.getBoundingInfo()._checkCollision(i))
            return this;
        var o = TmpVectors.Matrix[0]
          , s = TmpVectors.Matrix[1];
        return Matrix.ScalingToRef(1 / i._radius.x, 1 / i._radius.y, 1 / i._radius.z, o),
        this.worldMatrixFromCache.multiplyToRef(o, s),
        this._processCollisionsForSubMeshes(i, s),
        this
    }
    ,
    e.prototype._generatePointsArray = function() {
        return !1
    }
    ,
    e.prototype.intersects = function(i, o, s, c, d, _) {
        c === void 0 && (c = !1),
        _ === void 0 && (_ = !1);
        var b = new PickingInfo
          , k = this.getClassName() === "InstancedLinesMesh" || this.getClassName() === "LinesMesh" ? this.intersectionThreshold : 0
          , j = this.getBoundingInfo();
        if (!this.subMeshes || !_ && (!i.intersectsSphere(j.boundingSphere, k) || !i.intersectsBox(j.boundingBox, k)))
            return b;
        if (c)
            return b.hit = !_,
            b.pickedMesh = _ ? null : this,
            b.distance = _ ? 0 : Vector3.Distance(i.origin, j.boundingSphere.center),
            b.subMeshId = 0,
            b;
        if (!this._generatePointsArray())
            return b;
        for (var $ = null, _e = this._scene.getIntersectingSubMeshCandidates(this, i), et = _e.length, tt = !1, rt = 0; rt < et; rt++) {
            var it = _e.data[rt]
              , nt = it.getMaterial();
            if (!!nt && (nt.fillMode == 7 || nt.fillMode == 0 || nt.fillMode == 1 || nt.fillMode == 2)) {
                tt = !0;
                break
            }
        }
        if (!tt)
            return b.hit = !0,
            b.pickedMesh = this,
            b.distance = Vector3.Distance(i.origin, j.boundingSphere.center),
            b.subMeshId = -1,
            b;
        for (var rt = 0; rt < et; rt++) {
            var it = _e.data[rt];
            if (!(et > 1 && !it.canIntersects(i))) {
                var ot = it.intersects(i, this._positions, this.getIndices(), o, s);
                if (ot && (o || !$ || ot.distance < $.distance) && ($ = ot,
                $.subMeshId = rt,
                o))
                    break
            }
        }
        if ($) {
            var at = d != null ? d : this.skeleton && this.skeleton.overrideMesh ? this.skeleton.overrideMesh.getWorldMatrix() : this.getWorldMatrix()
              , st = TmpVectors.Vector3[0]
              , ut = TmpVectors.Vector3[1];
            Vector3.TransformCoordinatesToRef(i.origin, at, st),
            i.direction.scaleToRef($.distance, ut);
            var ct = Vector3.TransformNormal(ut, at)
              , lt = ct.addInPlace(st);
            return b.hit = !0,
            b.distance = Vector3.Distance(st, lt),
            b.pickedPoint = lt,
            b.pickedMesh = this,
            b.bu = $.bu || 0,
            b.bv = $.bv || 0,
            b.subMeshFaceId = $.faceId,
            b.faceId = $.faceId + _e.data[$.subMeshId].indexStart / (this.getClassName().indexOf("LinesMesh") !== -1 ? 2 : 3),
            b.subMeshId = $.subMeshId,
            b
        }
        return b
    }
    ,
    e.prototype.clone = function(i, o, s) {
        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(i, o) {
        var s = this;
        o === void 0 && (o = !1);
        var c;
        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),
        c = 0; c < this._intersectionsInProgress.length; c++) {
            var d = this._intersectionsInProgress[c]
              , _ = d._intersectionsInProgress.indexOf(this);
            d._intersectionsInProgress.splice(_, 1)
        }
        this._intersectionsInProgress = [];
        var b = this.getScene().lights;
        b.forEach(function($) {
            var _e = $.includedOnlyMeshes.indexOf(s);
            _e !== -1 && $.includedOnlyMeshes.splice(_e, 1),
            _e = $.excludedMeshes.indexOf(s),
            _e !== -1 && $.excludedMeshes.splice(_e, 1);
            var et = $.getShadowGenerator();
            if (et) {
                var tt = et.getShadowMap();
                tt && tt.renderList && (_e = tt.renderList.indexOf(s),
                _e !== -1 && tt.renderList.splice(_e, 1))
            }
        }),
        (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") && this.releaseSubMeshes();
        var k = this.getScene().getEngine();
        if (this._occlusionQuery !== null && (this.isOcclusionQueryInProgress = !1,
        k.deleteQuery(this._occlusionQuery),
        this._occlusionQuery = null),
        k.wipeCaches(),
        this.getScene().removeMesh(this),
        this._parentContainer) {
            var j = this._parentContainer.meshes.indexOf(this);
            j > -1 && this._parentContainer.meshes.splice(j, 1),
            this._parentContainer = null
        }
        if (o && this.material && (this.material.getClassName() === "MultiMaterial" ? this.material.dispose(!1, !0, !0) : this.material.dispose(!1, !0)),
        !i)
            for (c = 0; c < this.getScene().particleSystems.length; c++)
                this.getScene().particleSystems[c].emitter === this && (this.getScene().particleSystems[c].dispose(),
                c--);
        this._internalAbstractMeshDataInfo._facetData.facetDataEnabled && this.disableFacetData(),
        this._uniformBuffer.dispose(),
        this.onAfterWorldMatrixUpdateObservable.clear(),
        this.onCollideObservable.clear(),
        this.onCollisionPositionChangeObservable.clear(),
        this.onRebuildObservable.clear(),
        a.prototype.dispose.call(this, i, o)
    }
    ,
    e.prototype.addChild = function(i, o) {
        return o === void 0 && (o = !1),
        i.setParent(this, o),
        this
    }
    ,
    e.prototype.removeChild = function(i, o) {
        return o === void 0 && (o = !1),
        i.setParent(null, o),
        this
    }
    ,
    e.prototype._initFacetData = function() {
        var i = this._internalAbstractMeshDataInfo._facetData;
        i.facetNormals || (i.facetNormals = new Array),
        i.facetPositions || (i.facetPositions = new Array),
        i.facetPartitioning || (i.facetPartitioning = new Array),
        i.facetNb = this.getIndices().length / 3 | 0,
        i.partitioningSubdivisions = i.partitioningSubdivisions ? i.partitioningSubdivisions : 10,
        i.partitioningBBoxRatio = i.partitioningBBoxRatio ? i.partitioningBBoxRatio : 1.01;
        for (var o = 0; o < i.facetNb; o++)
            i.facetNormals[o] = Vector3.Zero(),
            i.facetPositions[o] = Vector3.Zero();
        return i.facetDataEnabled = !0,
        this
    }
    ,
    e.prototype.updateFacetData = function() {
        var i = this._internalAbstractMeshDataInfo._facetData;
        i.facetDataEnabled || this._initFacetData();
        var o = this.getVerticesData(VertexBuffer.PositionKind)
          , s = this.getIndices()
          , c = this.getVerticesData(VertexBuffer.NormalKind)
          , d = this.getBoundingInfo();
        if (i.facetDepthSort && !i.facetDepthSortEnabled) {
            if (i.facetDepthSortEnabled = !0,
            s instanceof Uint16Array)
                i.depthSortedIndices = new Uint16Array(s);
            else if (s instanceof Uint32Array)
                i.depthSortedIndices = new Uint32Array(s);
            else {
                for (var _ = !1, b = 0; b < s.length; b++)
                    if (s[b] > 65535) {
                        _ = !0;
                        break
                    }
                _ ? i.depthSortedIndices = new Uint32Array(s) : i.depthSortedIndices = new Uint16Array(s)
            }
            if (i.facetDepthSortFunction = function(rt, it) {
                return it.sqDistance - rt.sqDistance
            }
            ,
            !i.facetDepthSortFrom) {
                var k = this.getScene().activeCamera;
                i.facetDepthSortFrom = k ? k.position : Vector3.Zero()
            }
            i.depthSortedFacets = [];
            for (var j = 0; j < i.facetNb; j++) {
                var $ = {
                    ind: j * 3,
                    sqDistance: 0
                };
                i.depthSortedFacets.push($)
            }
            i.invertedMatrix = Matrix.Identity(),
            i.facetDepthSortOrigin = Vector3.Zero()
        }
        i.bbSize.x = d.maximum.x - d.minimum.x > Epsilon ? d.maximum.x - d.minimum.x : Epsilon,
        i.bbSize.y = d.maximum.y - d.minimum.y > Epsilon ? d.maximum.y - d.minimum.y : Epsilon,
        i.bbSize.z = d.maximum.z - d.minimum.z > Epsilon ? d.maximum.z - d.minimum.z : Epsilon;
        var _e = i.bbSize.x > i.bbSize.y ? i.bbSize.x : i.bbSize.y;
        if (_e = _e > i.bbSize.z ? _e : i.bbSize.z,
        i.subDiv.max = i.partitioningSubdivisions,
        i.subDiv.X = Math.floor(i.subDiv.max * i.bbSize.x / _e),
        i.subDiv.Y = Math.floor(i.subDiv.max * i.bbSize.y / _e),
        i.subDiv.Z = Math.floor(i.subDiv.max * i.bbSize.z / _e),
        i.subDiv.X = i.subDiv.X < 1 ? 1 : i.subDiv.X,
        i.subDiv.Y = i.subDiv.Y < 1 ? 1 : i.subDiv.Y,
        i.subDiv.Z = i.subDiv.Z < 1 ? 1 : i.subDiv.Z,
        i.facetParameters.facetNormals = this.getFacetLocalNormals(),
        i.facetParameters.facetPositions = this.getFacetLocalPositions(),
        i.facetParameters.facetPartitioning = this.getFacetLocalPartitioning(),
        i.facetParameters.bInfo = d,
        i.facetParameters.bbSize = i.bbSize,
        i.facetParameters.subDiv = i.subDiv,
        i.facetParameters.ratio = this.partitioningBBoxRatio,
        i.facetParameters.depthSort = i.facetDepthSort,
        i.facetDepthSort && i.facetDepthSortEnabled && (this.computeWorldMatrix(!0),
        this._worldMatrix.invertToRef(i.invertedMatrix),
        Vector3.TransformCoordinatesToRef(i.facetDepthSortFrom, i.invertedMatrix, i.facetDepthSortOrigin),
        i.facetParameters.distanceTo = i.facetDepthSortOrigin),
        i.facetParameters.depthSortedFacets = i.depthSortedFacets,
        c && VertexData.ComputeNormals(o, s, c, i.facetParameters),
        i.facetDepthSort && i.facetDepthSortEnabled) {
            i.depthSortedFacets.sort(i.facetDepthSortFunction);
            for (var et = i.depthSortedIndices.length / 3 | 0, j = 0; j < et; j++) {
                var tt = i.depthSortedFacets[j].ind;
                i.depthSortedIndices[j * 3] = s[tt],
                i.depthSortedIndices[j * 3 + 1] = s[tt + 1],
                i.depthSortedIndices[j * 3 + 2] = s[tt + 2]
            }
            this.updateIndices(i.depthSortedIndices, void 0, !0)
        }
        return this
    }
    ,
    e.prototype.getFacetLocalNormals = function() {
        var i = this._internalAbstractMeshDataInfo._facetData;
        return i.facetNormals || this.updateFacetData(),
        i.facetNormals
    }
    ,
    e.prototype.getFacetLocalPositions = function() {
        var i = this._internalAbstractMeshDataInfo._facetData;
        return i.facetPositions || this.updateFacetData(),
        i.facetPositions
    }
    ,
    e.prototype.getFacetLocalPartitioning = function() {
        var i = this._internalAbstractMeshDataInfo._facetData;
        return i.facetPartitioning || this.updateFacetData(),
        i.facetPartitioning
    }
    ,
    e.prototype.getFacetPosition = function(i) {
        var o = Vector3.Zero();
        return this.getFacetPositionToRef(i, o),
        o
    }
    ,
    e.prototype.getFacetPositionToRef = function(i, o) {
        var s = this.getFacetLocalPositions()[i]
          , c = this.getWorldMatrix();
        return Vector3.TransformCoordinatesToRef(s, c, o),
        this
    }
    ,
    e.prototype.getFacetNormal = function(i) {
        var o = Vector3.Zero();
        return this.getFacetNormalToRef(i, o),
        o
    }
    ,
    e.prototype.getFacetNormalToRef = function(i, o) {
        var s = this.getFacetLocalNormals()[i];
        return Vector3.TransformNormalToRef(s, this.getWorldMatrix(), o),
        this
    }
    ,
    e.prototype.getFacetsAtLocalCoordinates = function(i, o, s) {
        var c = this.getBoundingInfo()
          , d = this._internalAbstractMeshDataInfo._facetData
          , _ = Math.floor((i - c.minimum.x * d.partitioningBBoxRatio) * d.subDiv.X * d.partitioningBBoxRatio / d.bbSize.x)
          , b = Math.floor((o - c.minimum.y * d.partitioningBBoxRatio) * d.subDiv.Y * d.partitioningBBoxRatio / d.bbSize.y)
          , k = Math.floor((s - c.minimum.z * d.partitioningBBoxRatio) * d.subDiv.Z * d.partitioningBBoxRatio / d.bbSize.z);
        return _ < 0 || _ > d.subDiv.max || b < 0 || b > d.subDiv.max || k < 0 || k > d.subDiv.max ? null : d.facetPartitioning[_ + d.subDiv.max * b + d.subDiv.max * d.subDiv.max * k]
    }
    ,
    e.prototype.getClosestFacetAtCoordinates = function(i, o, s, c, d, _) {
        d === void 0 && (d = !1),
        _ === void 0 && (_ = !0);
        var b = this.getWorldMatrix()
          , k = TmpVectors.Matrix[5];
        b.invertToRef(k);
        var j = TmpVectors.Vector3[8];
        Vector3.TransformCoordinatesFromFloatsToRef(i, o, s, k, j);
        var $ = this.getClosestFacetAtLocalCoordinates(j.x, j.y, j.z, c, d, _);
        return c && Vector3.TransformCoordinatesFromFloatsToRef(c.x, c.y, c.z, b, c),
        $
    }
    ,
    e.prototype.getClosestFacetAtLocalCoordinates = function(i, o, s, c, d, _) {
        d === void 0 && (d = !1),
        _ === void 0 && (_ = !0);
        var b = null
          , k = 0
          , j = 0
          , $ = 0
          , _e = 0
          , et = 0
          , tt = 0
          , rt = 0
          , it = 0
          , nt = this.getFacetLocalPositions()
          , ot = this.getFacetLocalNormals()
          , at = this.getFacetsAtLocalCoordinates(i, o, s);
        if (!at)
            return null;
        for (var st = Number.MAX_VALUE, ut = st, ct, lt, ft, ht = 0; ht < at.length; ht++)
            ct = at[ht],
            lt = ot[ct],
            ft = nt[ct],
            _e = (i - ft.x) * lt.x + (o - ft.y) * lt.y + (s - ft.z) * lt.z,
            (!d || d && _ && _e >= 0 || d && !_ && _e <= 0) && (_e = lt.x * ft.x + lt.y * ft.y + lt.z * ft.z,
            et = -(lt.x * i + lt.y * o + lt.z * s - _e) / (lt.x * lt.x + lt.y * lt.y + lt.z * lt.z),
            tt = i + lt.x * et,
            rt = o + lt.y * et,
            it = s + lt.z * et,
            k = tt - i,
            j = rt - o,
            $ = it - s,
            ut = k * k + j * j + $ * $,
            ut < st && (st = ut,
            b = ct,
            c && (c.x = tt,
            c.y = rt,
            c.z = it)));
        return b
    }
    ,
    e.prototype.getFacetDataParameters = function() {
        return this._internalAbstractMeshDataInfo._facetData.facetParameters
    }
    ,
    e.prototype.disableFacetData = function() {
        var i = this._internalAbstractMeshDataInfo._facetData;
        return i.facetDataEnabled && (i.facetDataEnabled = !1,
        i.facetPositions = new Array,
        i.facetNormals = new Array,
        i.facetPartitioning = new Array,
        i.facetParameters = null,
        i.depthSortedIndices = new Uint32Array(0)),
        this
    }
    ,
    e.prototype.updateIndices = function(i, o, s) {
        return this
    }
    ,
    e.prototype.createNormals = function(i) {
        var o = this.getVerticesData(VertexBuffer.PositionKind), s = this.getIndices(), c;
        return this.isVerticesDataPresent(VertexBuffer.NormalKind) ? c = this.getVerticesData(VertexBuffer.NormalKind) : c = [],
        VertexData.ComputeNormals(o, s, c, {
            useRightHandedSystem: this.getScene().useRightHandedSystem
        }),
        this.setVerticesData(VertexBuffer.NormalKind, c, i),
        this
    }
    ,
    e.prototype.alignWithNormal = function(i, o) {
        o || (o = Axis.Y);
        var s = TmpVectors.Vector3[0]
          , c = TmpVectors.Vector3[1];
        return Vector3.CrossToRef(o, i, c),
        Vector3.CrossToRef(i, c, s),
        this.rotationQuaternion ? Quaternion.RotationQuaternionFromAxisToRef(s, i, c, this.rotationQuaternion) : Vector3.RotationFromAxisToRef(s, i, c, this.rotation),
        this
    }
    ,
    e.prototype._checkOcclusionQuery = function() {
        return !1
    }
    ,
    e.prototype.disableEdgesRendering = function() {
        throw _WarnImport("EdgesRenderer")
    }
    ,
    e.prototype.enableEdgesRendering = function(i, o, s) {
        throw _WarnImport("EdgesRenderer")
    }
    ,
    e.prototype.getConnectedParticleSystems = function() {
        var i = this;
        return this._scene.particleSystems.filter(function(o) {
            return o.emitter === i
        })
    }
    ,
    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 _TimeToken = function() {
    function a() {
        this._timeElapsedQueryEnded = !1
    }
    return a
}()
  , _OcclusionDataStorage = function() {
    function a() {
        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 a
}();
Engine.prototype.createQuery = function() {
    return this._gl.createQuery()
}
;
Engine.prototype.deleteQuery = function(a) {
    return this._gl.deleteQuery(a),
    this
}
;
Engine.prototype.isQueryResultAvailable = function(a) {
    return this._gl.getQueryParameter(a, this._gl.QUERY_RESULT_AVAILABLE)
}
;
Engine.prototype.getQueryResult = function(a) {
    return this._gl.getQueryParameter(a, this._gl.QUERY_RESULT)
}
;
Engine.prototype.beginOcclusionQuery = function(a, e) {
    var i = this._getGlAlgorithmType(a);
    return this._gl.beginQuery(i, e),
    !0
}
;
Engine.prototype.endOcclusionQuery = function(a) {
    var e = this._getGlAlgorithmType(a);
    return this._gl.endQuery(e),
    this
}
;
Engine.prototype._createTimeQuery = function() {
    var a = this.getCaps().timerQuery;
    return a.createQueryEXT ? a.createQueryEXT() : this.createQuery()
}
;
Engine.prototype._deleteTimeQuery = function(a) {
    var e = this.getCaps().timerQuery;
    if (e.deleteQueryEXT) {
        e.deleteQueryEXT(a);
        return
    }
    this.deleteQuery(a)
}
;
Engine.prototype._getTimeQueryResult = function(a) {
    var e = this.getCaps().timerQuery;
    return e.getQueryObjectEXT ? e.getQueryObjectEXT(a, e.QUERY_RESULT_EXT) : this.getQueryResult(a)
}
;
Engine.prototype._getTimeQueryAvailability = function(a) {
    var e = this.getCaps().timerQuery;
    return e.getQueryObjectEXT ? e.getQueryObjectEXT(a, e.QUERY_RESULT_AVAILABLE_EXT) : this.isQueryResultAvailable(a)
}
;
Engine.prototype.startTimeQuery = function() {
    var a = this.getCaps()
      , e = a.timerQuery;
    if (!e)
        return null;
    var i = new _TimeToken;
    if (this._gl.getParameter(e.GPU_DISJOINT_EXT),
    a.canUseTimestampForTimerQuery)
        i._startTimeQuery = this._createTimeQuery(),
        e.queryCounterEXT(i._startTimeQuery, e.TIMESTAMP_EXT);
    else {
        if (this._currentNonTimestampToken)
            return this._currentNonTimestampToken;
        i._timeElapsedQuery = this._createTimeQuery(),
        e.beginQueryEXT ? e.beginQueryEXT(e.TIME_ELAPSED_EXT, i._timeElapsedQuery) : this._gl.beginQuery(e.TIME_ELAPSED_EXT, i._timeElapsedQuery),
        this._currentNonTimestampToken = i
    }
    return i
}
;
Engine.prototype.endTimeQuery = function(a) {
    var e = this.getCaps()
      , i = e.timerQuery;
    if (!i || !a)
        return -1;
    if (e.canUseTimestampForTimerQuery) {
        if (!a._startTimeQuery)
            return -1;
        a._endTimeQuery || (a._endTimeQuery = this._createTimeQuery(),
        i.queryCounterEXT(a._endTimeQuery, i.TIMESTAMP_EXT))
    } else if (!a._timeElapsedQueryEnded) {
        if (!a._timeElapsedQuery)
            return -1;
        i.endQueryEXT ? i.endQueryEXT(i.TIME_ELAPSED_EXT) : this._gl.endQuery(i.TIME_ELAPSED_EXT),
        a._timeElapsedQueryEnded = !0
    }
    var o = this._gl.getParameter(i.GPU_DISJOINT_EXT)
      , s = !1;
    if (a._endTimeQuery ? s = this._getTimeQueryAvailability(a._endTimeQuery) : a._timeElapsedQuery && (s = this._getTimeQueryAvailability(a._timeElapsedQuery)),
    s && !o) {
        var c = 0;
        if (e.canUseTimestampForTimerQuery) {
            if (!a._startTimeQuery || !a._endTimeQuery)
                return -1;
            var d = this._getTimeQueryResult(a._startTimeQuery)
              , _ = this._getTimeQueryResult(a._endTimeQuery);
            c = _ - d,
            this._deleteTimeQuery(a._startTimeQuery),
            this._deleteTimeQuery(a._endTimeQuery),
            a._startTimeQuery = null,
            a._endTimeQuery = null
        } else {
            if (!a._timeElapsedQuery)
                return -1;
            c = this._getTimeQueryResult(a._timeElapsedQuery),
            this._deleteTimeQuery(a._timeElapsedQuery),
            a._timeElapsedQuery = null,
            a._timeElapsedQueryEnded = !1,
            this._currentNonTimestampToken = null
        }
        return c
    }
    return -1
}
;
Engine.prototype._captureGPUFrameTime = !1;
Engine.prototype._gpuFrameTime = new PerfCounter;
Engine.prototype.getGPUFrameTimeCounter = function() {
    return this._gpuFrameTime
}
;
Engine.prototype.captureGPUFrameTime = function(a) {
    var e = this;
    a !== this._captureGPUFrameTime && (this._captureGPUFrameTime = a,
    a ? (this._onBeginFrameObserver = this.onBeginFrameObservable.add(function() {
        e._gpuFrameTimeToken || (e._gpuFrameTimeToken = e.startTimeQuery())
    }),
    this._onEndFrameObserver = this.onEndFrameObservable.add(function() {
        if (!!e._gpuFrameTimeToken) {
            var i = e.endTimeQuery(e._gpuFrameTimeToken);
            i > -1 && (e._gpuFrameTimeToken = null,
            e._gpuFrameTime.fetchNewFrame(),
            e._gpuFrameTime.addCount(i, !0))
        }
    })) : (this.onBeginFrameObservable.remove(this._onBeginFrameObserver),
    this._onBeginFrameObserver = null,
    this.onEndFrameObservable.remove(this._onEndFrameObserver),
    this._onEndFrameObserver = null))
}
;
Engine.prototype._getGlAlgorithmType = function(a) {
    return a === 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(a) {
        this._occlusionDataStorage.isOcclusionQueryInProgress = a
    },
    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(a) {
        this._occlusionDataStorage.isOccluded = a
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
    get: function() {
        return this._occlusionDataStorage.occlusionQueryAlgorithmType
    },
    set: function(a) {
        this._occlusionDataStorage.occlusionQueryAlgorithmType = a
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(AbstractMesh.prototype, "occlusionType", {
    get: function() {
        return this._occlusionDataStorage.occlusionType
    },
    set: function(a) {
        this._occlusionDataStorage.occlusionType = a
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(AbstractMesh.prototype, "occlusionRetryCount", {
    get: function() {
        return this._occlusionDataStorage.occlusionRetryCount
    },
    set: function(a) {
        this._occlusionDataStorage.occlusionRetryCount = a
    },
    enumerable: !0,
    configurable: !0
});
AbstractMesh.prototype._checkOcclusionQuery = function() {
    var a = this._occlusionDataStorage;
    if (a.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE)
        return a.isOccluded = !1,
        !1;
    var e = this.getEngine();
    if (!e.getCaps().supportOcclusionQuery || !e.isQueryResultAvailable)
        return a.isOccluded = !1,
        !1;
    if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
        var i = e.isQueryResultAvailable(this._occlusionQuery);
        if (i) {
            var o = e.getQueryResult(this._occlusionQuery);
            a.isOcclusionQueryInProgress = !1,
            a.occlusionInternalRetryCounter = 0,
            a.isOccluded = !(o > 0)
        } else if (a.occlusionInternalRetryCounter++,
        a.occlusionRetryCount !== -1 && a.occlusionInternalRetryCounter > a.occlusionRetryCount)
            a.isOcclusionQueryInProgress = !1,
            a.occlusionInternalRetryCounter = 0,
            a.isOccluded = a.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? !1 : a.isOccluded;
        else
            return a.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? !1 : a.isOccluded
    }
    var s = this.getScene();
    if (s.getBoundingBoxRenderer) {
        var c = s.getBoundingBoxRenderer();
        this._occlusionQuery === null && (this._occlusionQuery = e.createQuery()),
        e.beginOcclusionQuery(a.occlusionQueryAlgorithmType, this._occlusionQuery) && (c.renderOcclusionBoundingBox(this),
        e.endOcclusionQuery(a.occlusionQueryAlgorithmType),
        this._occlusionDataStorage.isOcclusionQueryInProgress = !0)
    }
    return a.isOccluded
}
;
Engine.prototype.createTransformFeedback = function() {
    return this._gl.createTransformFeedback()
}
;
Engine.prototype.deleteTransformFeedback = function(a) {
    this._gl.deleteTransformFeedback(a)
}
;
Engine.prototype.bindTransformFeedback = function(a) {
    this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, a)
}
;
Engine.prototype.beginTransformFeedback = function(a) {
    a === void 0 && (a = !0),
    this._gl.beginTransformFeedback(a ? this._gl.POINTS : this._gl.TRIANGLES)
}
;
Engine.prototype.endTransformFeedback = function() {
    this._gl.endTransformFeedback()
}
;
Engine.prototype.setTranformFeedbackVaryings = function(a, e) {
    this._gl.transformFeedbackVaryings(a, e, this._gl.INTERLEAVED_ATTRIBS)
}
;
Engine.prototype.bindTransformFeedbackBuffer = function(a) {
    this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, a ? a.underlyingResource : null)
}
;
var SmartArray = function() {
    function a(e) {
        this.length = 0,
        this.data = new Array(e),
        this._id = a._GlobalId++
    }
    return a.prototype.push = function(e) {
        this.data[this.length++] = e,
        this.length > this.data.length && (this.data.length *= 2)
    }
    ,
    a.prototype.forEach = function(e) {
        for (var i = 0; i < this.length; i++)
            e(this.data[i])
    }
    ,
    a.prototype.sort = function(e) {
        this.data.sort(e)
    }
    ,
    a.prototype.reset = function() {
        this.length = 0
    }
    ,
    a.prototype.dispose = function() {
        this.reset(),
        this.data && (this.data.length = 0,
        this.data = [])
    }
    ,
    a.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 i = 0; i < e.length; i++)
                this.data[this.length++] = (e.data || e)[i]
        }
    }
    ,
    a.prototype.indexOf = function(e) {
        var i = this.data.indexOf(e);
        return i >= this.length ? -1 : i
    }
    ,
    a.prototype.contains = function(e) {
        return this.indexOf(e) !== -1
    }
    ,
    a._GlobalId = 0,
    a
}()
  , SmartArrayNoDuplicate = function(a) {
    __extends(e, a);
    function e() {
        var i = a !== null && a.apply(this, arguments) || this;
        return i._duplicateId = 0,
        i
    }
    return e.prototype.push = function(i) {
        a.prototype.push.call(this, i),
        i.__smartArrayFlags || (i.__smartArrayFlags = {}),
        i.__smartArrayFlags[this._id] = this._duplicateId
    }
    ,
    e.prototype.pushNoDuplicate = function(i) {
        return i.__smartArrayFlags && i.__smartArrayFlags[this._id] === this._duplicateId ? !1 : (this.push(i),
        !0)
    }
    ,
    e.prototype.reset = function() {
        a.prototype.reset.call(this),
        this._duplicateId++
    }
    ,
    e.prototype.concatWithNoDuplicate = function(i) {
        if (i.length !== 0) {
            this.length + i.length > this.data.length && (this.data.length = (this.length + i.length) * 2);
            for (var o = 0; o < i.length; o++) {
                var s = (i.data || i)[o];
                this.pushNoDuplicate(s)
            }
        }
    }
    ,
    e
}(SmartArray)
  , Viewport = function() {
    function a(e, i, o, s) {
        this.x = e,
        this.y = i,
        this.width = o,
        this.height = s
    }
    return a.prototype.toGlobal = function(e, i) {
        return new a(this.x * e,this.y * i,this.width * e,this.height * i)
    }
    ,
    a.prototype.toGlobalToRef = function(e, i, o) {
        return o.x = this.x * e,
        o.y = this.y * i,
        o.width = this.width * e,
        o.height = this.height * i,
        this
    }
    ,
    a.prototype.clone = function() {
        return new a(this.x,this.y,this.width,this.height)
    }
    ,
    a
}()
  , Plane = function() {
    function a(e, i, o, s) {
        this.normal = new Vector3(e,i,o),
        this.d = s
    }
    return a.prototype.asArray = function() {
        return [this.normal.x, this.normal.y, this.normal.z, this.d]
    }
    ,
    a.prototype.clone = function() {
        return new a(this.normal.x,this.normal.y,this.normal.z,this.d)
    }
    ,
    a.prototype.getClassName = function() {
        return "Plane"
    }
    ,
    a.prototype.getHashCode = function() {
        var e = this.normal.getHashCode();
        return e = e * 397 ^ (this.d | 0),
        e
    }
    ,
    a.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)
          , i = 0;
        return e !== 0 && (i = 1 / e),
        this.normal.x *= i,
        this.normal.y *= i,
        this.normal.z *= i,
        this.d *= i,
        this
    }
    ,
    a.prototype.transform = function(e) {
        var i = a._TmpMatrix;
        e.invertToRef(i);
        var o = i.m
          , s = this.normal.x
          , c = this.normal.y
          , d = this.normal.z
          , _ = this.d
          , b = s * o[0] + c * o[1] + d * o[2] + _ * o[3]
          , k = s * o[4] + c * o[5] + d * o[6] + _ * o[7]
          , j = s * o[8] + c * o[9] + d * o[10] + _ * o[11]
          , $ = s * o[12] + c * o[13] + d * o[14] + _ * o[15];
        return new a(b,k,j,$)
    }
    ,
    a.prototype.dotCoordinate = function(e) {
        return this.normal.x * e.x + this.normal.y * e.y + this.normal.z * e.z + this.d
    }
    ,
    a.prototype.copyFromPoints = function(e, i, o) {
        var s = i.x - e.x, c = i.y - e.y, d = i.z - e.z, _ = o.x - e.x, b = o.y - e.y, k = o.z - e.z, j = c * k - d * b, $ = d * _ - s * k, _e = s * b - c * _, et = Math.sqrt(j * j + $ * $ + _e * _e), tt;
        return et !== 0 ? tt = 1 / et : tt = 0,
        this.normal.x = j * tt,
        this.normal.y = $ * tt,
        this.normal.z = _e * tt,
        this.d = -(this.normal.x * e.x + this.normal.y * e.y + this.normal.z * e.z),
        this
    }
    ,
    a.prototype.isFrontFacingTo = function(e, i) {
        var o = Vector3.Dot(this.normal, e);
        return o <= i
    }
    ,
    a.prototype.signedDistanceTo = function(e) {
        return Vector3.Dot(e, this.normal) + this.d
    }
    ,
    a.FromArray = function(e) {
        return new a(e[0],e[1],e[2],e[3])
    }
    ,
    a.FromPoints = function(e, i, o) {
        var s = new a(0,0,0,0);
        return s.copyFromPoints(e, i, o),
        s
    }
    ,
    a.FromPositionAndNormal = function(e, i) {
        var o = new a(0,0,0,0);
        return i.normalize(),
        o.normal = i,
        o.d = -(i.x * e.x + i.y * e.y + i.z * e.z),
        o
    }
    ,
    a.SignedDistanceToPlaneFromPositionAndNormal = function(e, i, o) {
        var s = -(i.x * e.x + i.y * e.y + i.z * e.z);
        return Vector3.Dot(o, i) + s
    }
    ,
    a._TmpMatrix = Matrix.Identity(),
    a
}()
  , Frustum = function() {
    function a() {}
    return a.GetPlanes = function(e) {
        for (var i = [], o = 0; o < 6; o++)
            i.push(new Plane(0,0,0,0));
        return a.GetPlanesToRef(e, i),
        i
    }
    ,
    a.GetNearPlaneToRef = function(e, i) {
        var o = e.m;
        i.normal.x = o[3] + o[2],
        i.normal.y = o[7] + o[6],
        i.normal.z = o[11] + o[10],
        i.d = o[15] + o[14],
        i.normalize()
    }
    ,
    a.GetFarPlaneToRef = function(e, i) {
        var o = e.m;
        i.normal.x = o[3] - o[2],
        i.normal.y = o[7] - o[6],
        i.normal.z = o[11] - o[10],
        i.d = o[15] - o[14],
        i.normalize()
    }
    ,
    a.GetLeftPlaneToRef = function(e, i) {
        var o = e.m;
        i.normal.x = o[3] + o[0],
        i.normal.y = o[7] + o[4],
        i.normal.z = o[11] + o[8],
        i.d = o[15] + o[12],
        i.normalize()
    }
    ,
    a.GetRightPlaneToRef = function(e, i) {
        var o = e.m;
        i.normal.x = o[3] - o[0],
        i.normal.y = o[7] - o[4],
        i.normal.z = o[11] - o[8],
        i.d = o[15] - o[12],
        i.normalize()
    }
    ,
    a.GetTopPlaneToRef = function(e, i) {
        var o = e.m;
        i.normal.x = o[3] - o[1],
        i.normal.y = o[7] - o[5],
        i.normal.z = o[11] - o[9],
        i.d = o[15] - o[13],
        i.normalize()
    }
    ,
    a.GetBottomPlaneToRef = function(e, i) {
        var o = e.m;
        i.normal.x = o[3] + o[1],
        i.normal.y = o[7] + o[5],
        i.normal.z = o[11] + o[9],
        i.d = o[15] + o[13],
        i.normalize()
    }
    ,
    a.GetPlanesToRef = function(e, i) {
        a.GetNearPlaneToRef(e, i[0]),
        a.GetFarPlaneToRef(e, i[1]),
        a.GetLeftPlaneToRef(e, i[2]),
        a.GetRightPlaneToRef(e, i[3]),
        a.GetTopPlaneToRef(e, i[4]),
        a.GetBottomPlaneToRef(e, i[5])
    }
    ,
    a
}()
  , Camera$1 = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        c === void 0 && (c = !0);
        var d = a.call(this, i, s) || this;
        return d._position = Vector3.Zero(),
        d._upVector = Vector3.Up(),
        d.orthoLeft = null,
        d.orthoRight = null,
        d.orthoBottom = null,
        d.orthoTop = null,
        d.fov = .8,
        d.projectionPlaneTilt = 0,
        d.minZ = 1,
        d.maxZ = 1e4,
        d.inertia = .9,
        d.mode = e.PERSPECTIVE_CAMERA,
        d.isIntermediate = !1,
        d.viewport = new Viewport(0,0,1,1),
        d.layerMask = 268435455,
        d.fovMode = e.FOVMODE_VERTICAL_FIXED,
        d.cameraRigMode = e.RIG_MODE_NONE,
        d.customRenderTargets = new Array,
        d.outputRenderTarget = null,
        d.onViewMatrixChangedObservable = new Observable,
        d.onProjectionMatrixChangedObservable = new Observable,
        d.onAfterCheckInputsObservable = new Observable,
        d.onRestoreStateObservable = new Observable,
        d.isRigCamera = !1,
        d._rigCameras = new Array,
        d._webvrViewMatrix = Matrix.Identity(),
        d._skipRendering = !1,
        d._projectionMatrix = new Matrix,
        d._postProcesses = new Array,
        d._activeMeshes = new SmartArray(256),
        d._globalPosition = Vector3.Zero(),
        d._computedViewMatrix = Matrix.Identity(),
        d._doNotComputeProjectionMatrix = !1,
        d._transformMatrix = Matrix.Zero(),
        d._refreshFrustumPlanes = !0,
        d._absoluteRotation = Quaternion.Identity(),
        d._isCamera = !0,
        d._isLeftCamera = !1,
        d._isRightCamera = !1,
        d.getScene().addCamera(d),
        c && !d.getScene().activeCamera && (d.getScene().activeCamera = d),
        d.position = o,
        d.renderPassId = d.getScene().getEngine().createRenderPassId("Camera " + i),
        d
    }
    return Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(i) {
            this._position = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "upVector", {
        get: function() {
            return this._upVector
        },
        set: function(i) {
            this._upVector = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "screenArea", {
        get: function() {
            var i, o, s, c, d = 0, _ = 0;
            if (this.mode === e.PERSPECTIVE_CAMERA)
                this.fovMode === e.FOVMODE_VERTICAL_FIXED ? (_ = this.minZ * 2 * Math.tan(this.fov / 2),
                d = this.getEngine().getAspectRatio(this) * _) : (d = this.minZ * 2 * Math.tan(this.fov / 2),
                _ = d / this.getEngine().getAspectRatio(this));
            else {
                var b = this.getEngine().getRenderWidth() / 2
                  , k = this.getEngine().getRenderHeight() / 2;
                d = ((i = this.orthoRight) !== null && i !== void 0 ? i : b) - ((o = this.orthoLeft) !== null && o !== void 0 ? o : -b),
                _ = ((s = this.orthoTop) !== null && s !== void 0 ? s : k) - ((c = this.orthoBottom) !== null && c !== void 0 ? c : -k)
            }
            return d * _
        },
        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(i) {
        var o = "Name: " + this.name;
        if (o += ", type: " + this.getClassName(),
        this.animations)
            for (var s = 0; s < this.animations.length; s++)
                o += ", animation[0]: " + this.animations[s].toString(i);
        return o
    }
    ,
    e.prototype.applyVerticalCorrection = function() {
        var i = this.absoluteRotation.toEulerAngles();
        this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -i.x : i.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(i) {
        return this._activeMeshes.indexOf(i) !== -1
    }
    ,
    e.prototype.isReady = function(i) {
        if (i === void 0 && (i = !1),
        i)
            for (var o = 0, s = this._postProcesses; o < s.length; o++) {
                var c = s[o];
                if (c && !c.isReady())
                    return !1
            }
        return a.prototype.isReady.call(this, i)
    }
    ,
    e.prototype._initCache = function() {
        a.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(i) {
        i || a.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 a.prototype._isSynchronized.call(this) ? this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent() : !1
    }
    ,
    e.prototype._isSynchronizedProjectionMatrix = function() {
        var i = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
        if (!i)
            return !1;
        var o = this.getEngine();
        return this.mode === e.PERSPECTIVE_CAMERA ? i = this._cache.fov === this.fov && this._cache.fovMode === this.fovMode && this._cache.aspectRatio === o.getAspectRatio(this) && this._cache.projectionPlaneTilt === this.projectionPlaneTilt : i = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === o.getRenderWidth() && this._cache.renderHeight === o.getRenderHeight(),
        i
    }
    ,
    e.prototype.attachControl = function(i, o) {}
    ,
    e.prototype.detachControl = function(i) {}
    ,
    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 i = 0; i < this._postProcesses.length; i++)
            if (this._postProcesses[i] !== null)
                return this._postProcesses[i];
        return null
    }
    ,
    e.prototype._cascadePostProcessesToRigCams = function() {
        var i = this._getFirstPostProcess();
        i && i.markTextureDirty();
        for (var o = 0, s = this._rigCameras.length; o < s; o++) {
            var c = this._rigCameras[o]
              , d = c._rigPostProcess;
            if (d) {
                var _ = d.getEffectName() === "pass";
                _ && (c.isIntermediate = this._postProcesses.length === 0),
                c._postProcesses = this._postProcesses.slice(0).concat(d),
                d.markTextureDirty()
            } else
                c._postProcesses = this._postProcesses.slice(0)
        }
    }
    ,
    e.prototype.attachPostProcess = function(i, o) {
        return o === void 0 && (o = null),
        !i.isReusable() && this._postProcesses.indexOf(i) > -1 ? (Logger$2.Error("You're trying to reuse a post process not defined as reusable."),
        0) : (o == null || o < 0 ? this._postProcesses.push(i) : this._postProcesses[o] === null ? this._postProcesses[o] = i : this._postProcesses.splice(o, 0, i),
        this._cascadePostProcessesToRigCams(),
        this._scene.prePassRenderer && this._scene.prePassRenderer.markAsDirty(),
        this._postProcesses.indexOf(i))
    }
    ,
    e.prototype.detachPostProcess = function(i) {
        var o = this._postProcesses.indexOf(i);
        o !== -1 && (this._postProcesses[o] = 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(i) {
        return !i && 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(i) {
        this._doNotComputeProjectionMatrix = !0,
        i !== void 0 && (this._projectionMatrix = i)
    }
    ,
    e.prototype.unfreezeProjectionMatrix = function() {
        this._doNotComputeProjectionMatrix = !1
    }
    ,
    e.prototype.getProjectionMatrix = function(i) {
        var o, s, c, d, _, b, k, j;
        if (this._doNotComputeProjectionMatrix || !i && this._isSynchronizedProjectionMatrix())
            return this._projectionMatrix;
        this._cache.mode = this.mode,
        this._cache.minZ = this.minZ,
        this._cache.maxZ = this.maxZ,
        this._refreshFrustumPlanes = !0;
        var $ = this.getEngine()
          , _e = this.getScene();
        if (this.mode === e.PERSPECTIVE_CAMERA) {
            this._cache.fov = this.fov,
            this._cache.fovMode = this.fovMode,
            this._cache.aspectRatio = $.getAspectRatio(this),
            this._cache.projectionPlaneTilt = this.projectionPlaneTilt,
            this.minZ <= 0 && (this.minZ = .1);
            var et = $.useReverseDepthBuffer
              , tt = void 0;
            _e.useRightHandedSystem ? tt = Matrix.PerspectiveFovRHToRef : tt = Matrix.PerspectiveFovLHToRef,
            tt(this.fov, $.getAspectRatio(this), et ? this.maxZ : this.minZ, et ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === e.FOVMODE_VERTICAL_FIXED, $.isNDCHalfZRange, this.projectionPlaneTilt, $.useReverseDepthBuffer)
        } else {
            var rt = $.getRenderWidth() / 2
              , it = $.getRenderHeight() / 2;
            _e.useRightHandedSystem ? Matrix.OrthoOffCenterRHToRef((o = this.orthoLeft) !== null && o !== void 0 ? o : -rt, (s = this.orthoRight) !== null && s !== void 0 ? s : rt, (c = this.orthoBottom) !== null && c !== void 0 ? c : -it, (d = this.orthoTop) !== null && d !== void 0 ? d : it, this.minZ, this.maxZ, this._projectionMatrix, $.isNDCHalfZRange) : Matrix.OrthoOffCenterLHToRef((_ = this.orthoLeft) !== null && _ !== void 0 ? _ : -rt, (b = this.orthoRight) !== null && b !== void 0 ? b : rt, (k = this.orthoBottom) !== null && k !== void 0 ? k : -it, (j = this.orthoTop) !== null && j !== void 0 ? j : it, this.minZ, this.maxZ, this._projectionMatrix, $.isNDCHalfZRange),
            this._cache.orthoLeft = this.orthoLeft,
            this._cache.orthoRight = this.orthoRight,
            this._cache.orthoBottom = this.orthoBottom,
            this._cache.orthoTop = this.orthoTop,
            this._cache.renderWidth = $.getRenderWidth(),
            this._cache.renderHeight = $.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(i, o) {
        if (o === void 0 && (o = !1),
        this._updateFrustumPlanes(),
        o && this.rigCameras.length > 0) {
            var s = !1;
            return this.rigCameras.forEach(function(c) {
                c._updateFrustumPlanes(),
                s = s || i.isInFrustum(c._frustumPlanes)
            }),
            s
        } else
            return i.isInFrustum(this._frustumPlanes)
    }
    ,
    e.prototype.isCompletelyInFrustum = function(i) {
        return this._updateFrustumPlanes(),
        i.isCompletelyInFrustum(this._frustumPlanes)
    }
    ,
    e.prototype.getForwardRay = function(i, o, s) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.getForwardRayToRef = function(i, o, s, c) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.dispose = function(i, o) {
        for (o === void 0 && (o = !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 s = this._rigCameras.pop();
            s && s.dispose()
        }
        if (this._parentContainer) {
            var c = this._parentContainer.cameras.indexOf(this);
            c > -1 && this._parentContainer.cameras.splice(c, 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 _ = this._postProcesses.length; --_ >= 0; ) {
                var d = this._postProcesses[_];
                d && d.dispose(this)
            }
        for (var _ = this.customRenderTargets.length; --_ >= 0; )
            this.customRenderTargets[_].dispose();
        this.customRenderTargets = [],
        this._activeMeshes.dispose(),
        this.getScene().getEngine().releaseRenderPassId(this.renderPassId),
        a.prototype.dispose.call(this, i, o)
    }
    ,
    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(i, o) {
        if (this.cameraRigMode !== i) {
            for (; this._rigCameras.length > 0; ) {
                var s = this._rigCameras.pop();
                s && s.dispose()
            }
            if (this.cameraRigMode = i,
            this._cameraRigParams = {},
            this._cameraRigParams.interaxialDistance = o.interaxialDistance || .0637,
            this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / .0637),
            this.cameraRigMode !== e.RIG_MODE_NONE) {
                var c = this.createRigCamera(this.name + "_L", 0);
                c && (c._isLeftCamera = !0);
                var d = this.createRigCamera(this.name + "_R", 1);
                d && (d._isRightCamera = !0),
                c && d && (this._rigCameras.push(c),
                this._rigCameras.push(d))
            }
            this._setRigMode(o),
            this._cascadePostProcessesToRigCams(),
            this.update()
        }
    }
    ,
    e.prototype._setRigMode = function(i) {}
    ,
    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(i, o) {
        this._cameraRigParams || (this._cameraRigParams = {}),
        this._cameraRigParams[i] = o,
        i === "interaxialDistance" && (this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(o / .0637))
    }
    ,
    e.prototype.createRigCamera = function(i, o) {
        return null
    }
    ,
    e.prototype._updateRigCameras = function() {
        for (var i = 0; i < this._rigCameras.length; i++)
            this._rigCameras[i].minZ = this.minZ,
            this._rigCameras[i].maxZ = this.maxZ,
            this._rigCameras[i].fov = this.fov,
            this._rigCameras[i].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 i = SerializationHelper.Serialize(this);
        return i.uniqueId = this.uniqueId,
        i.type = this.getClassName(),
        this.parent && (i.parentId = this.parent.uniqueId),
        this.inputs && this.inputs.serialize(i),
        SerializationHelper.AppendSerializedAnimations(this, i),
        i.ranges = this.serializeAnimationRanges(),
        i.isEnabled = this.isEnabled(),
        i
    }
    ,
    e.prototype.clone = function(i) {
        var o = SerializationHelper.Clone(e.GetConstructorFromName(this.getClassName(), i, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
        return o.name = i,
        this.onClonedObservable.notifyObservers(o),
        o
    }
    ,
    e.prototype.getDirection = function(i) {
        var o = Vector3.Zero();
        return this.getDirectionToRef(i, o),
        o
    }
    ,
    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(i, o) {
        Vector3.TransformNormalToRef(i, this.getWorldMatrix(), o)
    }
    ,
    e.GetConstructorFromName = function(i, o, s, c, d) {
        c === void 0 && (c = 0),
        d === void 0 && (d = !0);
        var _ = Node$2.Construct(i, o, s, {
            interaxial_distance: c,
            isStereoscopicSideBySide: d
        });
        return _ || function() {
            return e._createDefaultParsedCamera(o, s)
        }
    }
    ,
    e.prototype.computeWorldMatrix = function() {
        return this.getWorldMatrix()
    }
    ,
    e.Parse = function(i, o) {
        var s = i.type
          , c = e.GetConstructorFromName(s, i.name, o, i.interaxial_distance, i.isStereoscopicSideBySide)
          , d = SerializationHelper.Parse(c, i, o);
        if (i.parentId && (d._waitingParentId = i.parentId),
        d.inputs && (d.inputs.parse(i),
        d._setupInputs()),
        i.upVector && (d.upVector = Vector3.FromArray(i.upVector)),
        d.setPosition && (d.position.copyFromFloats(0, 0, 0),
        d.setPosition(Vector3.FromArray(i.position))),
        i.target && d.setTarget && d.setTarget(Vector3.FromArray(i.target)),
        i.cameraRigMode) {
            var _ = i.interaxial_distance ? {
                interaxialDistance: i.interaxial_distance
            } : {};
            d.setCameraRigMode(i.cameraRigMode, _)
        }
        if (i.animations) {
            for (var b = 0; b < i.animations.length; b++) {
                var k = i.animations[b]
                  , j = GetClass("BABYLON.Animation");
                j && d.animations.push(j.Parse(k))
            }
            Node$2.ParseAnimationRanges(d, i, o)
        }
        return i.autoAnimate && o.beginAnimation(d, i.autoAnimateFrom, i.autoAnimateTo, i.autoAnimateLoop, i.autoAnimateSpeed || 1),
        i.isEnabled !== void 0 && d.setEnabled(i.isEnabled),
        d
    }
    ,
    e._createDefaultParsedCamera = function(i, o) {
        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)
  , StringDictionary = function() {
    function a() {
        this._count = 0,
        this._data = {}
    }
    return a.prototype.copyFrom = function(e) {
        var i = this;
        this.clear(),
        e.forEach(function(o, s) {
            return i.add(o, s)
        })
    }
    ,
    a.prototype.get = function(e) {
        var i = this._data[e];
        if (i !== void 0)
            return i
    }
    ,
    a.prototype.getOrAddWithFactory = function(e, i) {
        var o = this.get(e);
        return o !== void 0 || (o = i(e),
        o && this.add(e, o)),
        o
    }
    ,
    a.prototype.getOrAdd = function(e, i) {
        var o = this.get(e);
        return o !== void 0 ? o : (this.add(e, i),
        i)
    }
    ,
    a.prototype.contains = function(e) {
        return this._data[e] !== void 0
    }
    ,
    a.prototype.add = function(e, i) {
        return this._data[e] !== void 0 ? !1 : (this._data[e] = i,
        ++this._count,
        !0)
    }
    ,
    a.prototype.set = function(e, i) {
        return this._data[e] === void 0 ? !1 : (this._data[e] = i,
        !0)
    }
    ,
    a.prototype.getAndRemove = function(e) {
        var i = this.get(e);
        return i !== void 0 ? (delete this._data[e],
        --this._count,
        i) : null
    }
    ,
    a.prototype.remove = function(e) {
        return this.contains(e) ? (delete this._data[e],
        --this._count,
        !0) : !1
    }
    ,
    a.prototype.clear = function() {
        this._data = {},
        this._count = 0
    }
    ,
    Object.defineProperty(a.prototype, "count", {
        get: function() {
            return this._count
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.forEach = function(e) {
        for (var i in this._data) {
            var o = this._data[i];
            e(i, o)
        }
    }
    ,
    a.prototype.first = function(e) {
        for (var i in this._data) {
            var o = this._data[i]
              , s = e(i, o);
            if (s)
                return s
        }
        return null
    }
    ,
    a
}()
  , AbstractScene = function() {
    function a() {
        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 a.AddParser = function(e, i) {
        this._BabylonFileParsers[e] = i
    }
    ,
    a.GetParser = function(e) {
        return this._BabylonFileParsers[e] ? this._BabylonFileParsers[e] : null
    }
    ,
    a.AddIndividualParser = function(e, i) {
        this._IndividualBabylonFileParsers[e] = i
    }
    ,
    a.GetIndividualParser = function(e) {
        return this._IndividualBabylonFileParsers[e] ? this._IndividualBabylonFileParsers[e] : null
    }
    ,
    a.Parse = function(e, i, o, s) {
        for (var c in this._BabylonFileParsers)
            this._BabylonFileParsers.hasOwnProperty(c) && this._BabylonFileParsers[c](e, i, o, s)
    }
    ,
    Object.defineProperty(a.prototype, "environmentTexture", {
        get: function() {
            return this._environmentTexture
        },
        set: function(e) {
            this._environmentTexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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(i) {
            return e = e.concat(i.bones)
        }),
        e
    }
    ,
    a._BabylonFileParsers = {},
    a._IndividualBabylonFileParsers = {},
    a
}()
  , MaterialDefines = function() {
    function a() {
        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(a.prototype, "isDirty", {
        get: function() {
            return this._isDirty
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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
    }
    ,
    a.prototype.markAsUnprocessed = function() {
        this._isDirty = !0
    }
    ,
    a.prototype.markAllAsDirty = function() {
        this._areTexturesDirty = !0,
        this._areAttributesDirty = !0,
        this._areLightsDirty = !0,
        this._areFresnelDirty = !0,
        this._areMiscDirty = !0,
        this._areImageProcessingDirty = !0,
        this._isDirty = !0
    }
    ,
    a.prototype.markAsImageProcessingDirty = function() {
        this._areImageProcessingDirty = !0,
        this._isDirty = !0
    }
    ,
    a.prototype.markAsLightDirty = function(e) {
        e === void 0 && (e = !1),
        this._areLightsDirty = !0,
        this._areLightsDisposed = this._areLightsDisposed || e,
        this._isDirty = !0
    }
    ,
    a.prototype.markAsAttributesDirty = function() {
        this._areAttributesDirty = !0,
        this._isDirty = !0
    }
    ,
    a.prototype.markAsTexturesDirty = function() {
        this._areTexturesDirty = !0,
        this._isDirty = !0
    }
    ,
    a.prototype.markAsFresnelDirty = function() {
        this._areFresnelDirty = !0,
        this._isDirty = !0
    }
    ,
    a.prototype.markAsMiscDirty = function() {
        this._areMiscDirty = !0,
        this._isDirty = !0
    }
    ,
    a.prototype.markAsPrePassDirty = function() {
        this._arePrePassDirty = !0,
        this._isDirty = !0
    }
    ,
    a.prototype.rebuild = function() {
        this._keys = [];
        for (var e = 0, i = Object.keys(this); e < i.length; e++) {
            var o = i[e];
            o[0] !== "_" && this._keys.push(o)
        }
    }
    ,
    a.prototype.isEqual = function(e) {
        if (this._keys.length !== e._keys.length)
            return !1;
        for (var i = 0; i < this._keys.length; i++) {
            var o = this._keys[i];
            if (this[o] !== e[o])
                return !1
        }
        return !0
    }
    ,
    a.prototype.cloneTo = function(e) {
        this._keys.length !== e._keys.length && (e._keys = this._keys.slice(0));
        for (var i = 0; i < this._keys.length; i++) {
            var o = this._keys[i];
            e[o] = this[o]
        }
    }
    ,
    a.prototype.reset = function() {
        for (var e = 0; e < this._keys.length; e++) {
            var i = this._keys[e]
              , o = typeof this[i];
            switch (o) {
            case "number":
                this[i] = 0;
                break;
            case "string":
                this[i] = "";
                break;
            default:
                this[i] = !1;
                break
            }
        }
    }
    ,
    a.prototype.toString = function() {
        for (var e = "", i = 0; i < this._keys.length; i++) {
            var o = this._keys[i]
              , s = this[o]
              , c = typeof s;
            switch (c) {
            case "number":
            case "string":
                e += "#define " + o + " " + s + `
`;
                break;
            default:
                s && (e += "#define " + o + `
`);
                break
            }
        }
        return e
    }
    ,
    a
}()
  , ColorCurves = function() {
    function a() {
        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(a.prototype, "globalHue", {
        get: function() {
            return this._globalHue
        },
        set: function(e) {
            this._globalHue = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "globalDensity", {
        get: function() {
            return this._globalDensity
        },
        set: function(e) {
            this._globalDensity = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "globalSaturation", {
        get: function() {
            return this._globalSaturation
        },
        set: function(e) {
            this._globalSaturation = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "globalExposure", {
        get: function() {
            return this._globalExposure
        },
        set: function(e) {
            this._globalExposure = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "highlightsHue", {
        get: function() {
            return this._highlightsHue
        },
        set: function(e) {
            this._highlightsHue = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "highlightsDensity", {
        get: function() {
            return this._highlightsDensity
        },
        set: function(e) {
            this._highlightsDensity = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "highlightsSaturation", {
        get: function() {
            return this._highlightsSaturation
        },
        set: function(e) {
            this._highlightsSaturation = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "highlightsExposure", {
        get: function() {
            return this._highlightsExposure
        },
        set: function(e) {
            this._highlightsExposure = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "midtonesHue", {
        get: function() {
            return this._midtonesHue
        },
        set: function(e) {
            this._midtonesHue = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "midtonesDensity", {
        get: function() {
            return this._midtonesDensity
        },
        set: function(e) {
            this._midtonesDensity = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "midtonesSaturation", {
        get: function() {
            return this._midtonesSaturation
        },
        set: function(e) {
            this._midtonesSaturation = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "midtonesExposure", {
        get: function() {
            return this._midtonesExposure
        },
        set: function(e) {
            this._midtonesExposure = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "shadowsHue", {
        get: function() {
            return this._shadowsHue
        },
        set: function(e) {
            this._shadowsHue = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "shadowsDensity", {
        get: function() {
            return this._shadowsDensity
        },
        set: function(e) {
            this._shadowsDensity = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "shadowsSaturation", {
        get: function() {
            return this._shadowsSaturation
        },
        set: function(e) {
            this._shadowsSaturation = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "shadowsExposure", {
        get: function() {
            return this._shadowsExposure
        },
        set: function(e) {
            this._shadowsExposure = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getClassName = function() {
        return "ColorCurves"
    }
    ,
    a.Bind = function(e, i, o, s, c) {
        o === void 0 && (o = "vCameraColorCurvePositive"),
        s === void 0 && (s = "vCameraColorCurveNeutral"),
        c === void 0 && (c = "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)),
        i && (i.setFloat4(o, e._positiveCurve.r, e._positiveCurve.g, e._positiveCurve.b, e._positiveCurve.a),
        i.setFloat4(s, e._midtonesCurve.r, e._midtonesCurve.g, e._midtonesCurve.b, e._midtonesCurve.a),
        i.setFloat4(c, e._negativeCurve.r, e._negativeCurve.g, e._negativeCurve.b, e._negativeCurve.a))
    }
    ,
    a.PrepareUniforms = function(e) {
        e.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative")
    }
    ,
    a.prototype.getColorGradingDataToRef = function(e, i, o, s, c) {
        e != null && (e = a.clamp(e, 0, 360),
        i = a.clamp(i, -100, 100),
        o = a.clamp(o, -100, 100),
        s = a.clamp(s, -100, 100),
        i = a.applyColorGradingSliderNonlinear(i),
        i *= .5,
        s = a.applyColorGradingSliderNonlinear(s),
        i < 0 && (i *= -1,
        e = (e + 180) % 360),
        a.fromHSBToRef(e, i, 50 + .25 * s, c),
        c.scaleToRef(2, c),
        c.a = 1 + .01 * o)
    }
    ,
    a.applyColorGradingSliderNonlinear = function(e) {
        e /= 100;
        var i = Math.abs(e);
        return i = Math.pow(i, 2),
        e < 0 && (i *= -1),
        i *= 100,
        i
    }
    ,
    a.fromHSBToRef = function(e, i, o, s) {
        var c = a.clamp(e, 0, 360)
          , d = a.clamp(i / 100, 0, 1)
          , _ = a.clamp(o / 100, 0, 1);
        if (d === 0)
            s.r = _,
            s.g = _,
            s.b = _;
        else {
            c /= 60;
            var b = Math.floor(c)
              , k = c - b
              , j = _ * (1 - d)
              , $ = _ * (1 - d * k)
              , _e = _ * (1 - d * (1 - k));
            switch (b) {
            case 0:
                s.r = _,
                s.g = _e,
                s.b = j;
                break;
            case 1:
                s.r = $,
                s.g = _,
                s.b = j;
                break;
            case 2:
                s.r = j,
                s.g = _,
                s.b = _e;
                break;
            case 3:
                s.r = j,
                s.g = $,
                s.b = _;
                break;
            case 4:
                s.r = _e,
                s.g = j,
                s.b = _;
                break;
            default:
                s.r = _,
                s.g = j,
                s.b = $;
                break
            }
        }
        s.a = 1
    }
    ,
    a.clamp = function(e, i, o) {
        return Math.min(Math.max(e, i), o)
    }
    ,
    a.prototype.clone = function() {
        return SerializationHelper.Clone(function() {
            return new a
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.Parse = function(e) {
        return SerializationHelper.Parse(function() {
            return new a
        }, e, null, null)
    }
    ,
    __decorate([serialize()], a.prototype, "_globalHue", void 0),
    __decorate([serialize()], a.prototype, "_globalDensity", void 0),
    __decorate([serialize()], a.prototype, "_globalSaturation", void 0),
    __decorate([serialize()], a.prototype, "_globalExposure", void 0),
    __decorate([serialize()], a.prototype, "_highlightsHue", void 0),
    __decorate([serialize()], a.prototype, "_highlightsDensity", void 0),
    __decorate([serialize()], a.prototype, "_highlightsSaturation", void 0),
    __decorate([serialize()], a.prototype, "_highlightsExposure", void 0),
    __decorate([serialize()], a.prototype, "_midtonesHue", void 0),
    __decorate([serialize()], a.prototype, "_midtonesDensity", void 0),
    __decorate([serialize()], a.prototype, "_midtonesSaturation", void 0),
    __decorate([serialize()], a.prototype, "_midtonesExposure", void 0),
    a
}();
SerializationHelper._ColorCurvesParser = ColorCurves.Parse;
var ImageProcessingConfigurationDefines = function(a) {
    __extends(e, a);
    function e() {
        var i = a.call(this) || this;
        return i.IMAGEPROCESSING = !1,
        i.VIGNETTE = !1,
        i.VIGNETTEBLENDMODEMULTIPLY = !1,
        i.VIGNETTEBLENDMODEOPAQUE = !1,
        i.TONEMAPPING = !1,
        i.TONEMAPPING_ACES = !1,
        i.CONTRAST = !1,
        i.COLORCURVES = !1,
        i.COLORGRADING = !1,
        i.COLORGRADING3D = !1,
        i.SAMPLER3DGREENDEPTH = !1,
        i.SAMPLER3DBGRMAP = !1,
        i.IMAGEPROCESSINGPOSTPROCESS = !1,
        i.EXPOSURE = !1,
        i.SKIPFINALCOLORCLAMP = !1,
        i.rebuild(),
        i
    }
    return e
}(MaterialDefines)
  , ImageProcessingConfiguration = function() {
    function a() {
        this.colorCurves = new ColorCurves,
        this._colorCurvesEnabled = !1,
        this._colorGradingEnabled = !1,
        this._colorGradingWithGreenDepth = !0,
        this._colorGradingBGR = !0,
        this._exposure = 1,
        this._toneMappingEnabled = !1,
        this._toneMappingType = a.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 = a.VIGNETTEMODE_MULTIPLY,
        this._vignetteEnabled = !1,
        this._skipFinalColorClamp = !1,
        this._applyByPostProcess = !1,
        this._isEnabled = !0,
        this.onUpdateParameters = new Observable
    }
    return Object.defineProperty(a.prototype, "colorCurvesEnabled", {
        get: function() {
            return this._colorCurvesEnabled
        },
        set: function(e) {
            this._colorCurvesEnabled !== e && (this._colorCurvesEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "colorGradingTexture", {
        get: function() {
            return this._colorGradingTexture
        },
        set: function(e) {
            this._colorGradingTexture !== e && (this._colorGradingTexture = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "colorGradingEnabled", {
        get: function() {
            return this._colorGradingEnabled
        },
        set: function(e) {
            this._colorGradingEnabled !== e && (this._colorGradingEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "colorGradingWithGreenDepth", {
        get: function() {
            return this._colorGradingWithGreenDepth
        },
        set: function(e) {
            this._colorGradingWithGreenDepth !== e && (this._colorGradingWithGreenDepth = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "colorGradingBGR", {
        get: function() {
            return this._colorGradingBGR
        },
        set: function(e) {
            this._colorGradingBGR !== e && (this._colorGradingBGR = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "exposure", {
        get: function() {
            return this._exposure
        },
        set: function(e) {
            this._exposure !== e && (this._exposure = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "toneMappingEnabled", {
        get: function() {
            return this._toneMappingEnabled
        },
        set: function(e) {
            this._toneMappingEnabled !== e && (this._toneMappingEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "toneMappingType", {
        get: function() {
            return this._toneMappingType
        },
        set: function(e) {
            this._toneMappingType !== e && (this._toneMappingType = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "contrast", {
        get: function() {
            return this._contrast
        },
        set: function(e) {
            this._contrast !== e && (this._contrast = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "vignetteBlendMode", {
        get: function() {
            return this._vignetteBlendMode
        },
        set: function(e) {
            this._vignetteBlendMode !== e && (this._vignetteBlendMode = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "vignetteEnabled", {
        get: function() {
            return this._vignetteEnabled
        },
        set: function(e) {
            this._vignetteEnabled !== e && (this._vignetteEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "skipFinalColorClamp", {
        get: function() {
            return this._skipFinalColorClamp
        },
        set: function(e) {
            this._skipFinalColorClamp !== e && (this._skipFinalColorClamp = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "applyByPostProcess", {
        get: function() {
            return this._applyByPostProcess
        },
        set: function(e) {
            this._applyByPostProcess !== e && (this._applyByPostProcess = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(e) {
            this._isEnabled !== e && (this._isEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._updateParameters = function() {
        this.onUpdateParameters.notifyObservers(this)
    }
    ,
    a.prototype.getClassName = function() {
        return "ImageProcessingConfiguration"
    }
    ,
    a.PrepareUniforms = function(e, i) {
        i.EXPOSURE && e.push("exposureLinear"),
        i.CONTRAST && e.push("contrast"),
        i.COLORGRADING && e.push("colorTransformSettings"),
        i.VIGNETTE && (e.push("vInverseScreenSize"),
        e.push("vignetteSettings1"),
        e.push("vignetteSettings2")),
        i.COLORCURVES && ColorCurves.PrepareUniforms(e)
    }
    ,
    a.PrepareSamplers = function(e, i) {
        i.COLORGRADING && e.push("txColorTransform")
    }
    ,
    a.prototype.prepareDefines = function(e, i) {
        if (i === void 0 && (i = !1),
        i !== 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 === a._VIGNETTEMODE_MULTIPLY,
        e.VIGNETTEBLENDMODEOPAQUE = !e.VIGNETTEBLENDMODEMULTIPLY,
        e.TONEMAPPING = this.toneMappingEnabled,
        this._toneMappingType) {
        case a.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
    }
    ,
    a.prototype.isReady = function() {
        return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady()
    }
    ,
    a.prototype.bind = function(e, i) {
        if (this._colorCurvesEnabled && this.colorCurves && ColorCurves.Bind(this.colorCurves, e),
        this._vignetteEnabled) {
            var o = 1 / e.getEngine().getRenderWidth()
              , s = 1 / e.getEngine().getRenderHeight();
            e.setFloat2("vInverseScreenSize", o, s);
            var c = i != null ? i : s / o
              , d = Math.tan(this.vignetteCameraFov * .5)
              , _ = d * c
              , b = Math.sqrt(_ * d);
            _ = Tools.Mix(_, b, this.vignetteStretch),
            d = Tools.Mix(d, b, this.vignetteStretch),
            e.setFloat4("vignetteSettings1", _, d, -_ * this.vignetteCentreX, -d * this.vignetteCentreY);
            var k = -2 * this.vignetteWeight;
            e.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, k)
        }
        if (e.setFloat("exposureLinear", this.exposure),
        e.setFloat("contrast", this.contrast),
        this.colorGradingTexture) {
            e.setTexture("txColorTransform", this.colorGradingTexture);
            var j = this.colorGradingTexture.getSize().height;
            e.setFloat4("colorTransformSettings", (j - 1) / j, .5 / j, j, this.colorGradingTexture.level)
        }
    }
    ,
    a.prototype.clone = function() {
        return SerializationHelper.Clone(function() {
            return new a
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.Parse = function(e) {
        return SerializationHelper.Parse(function() {
            return new a
        }, e, null, null)
    }
    ,
    Object.defineProperty(a, "VIGNETTEMODE_MULTIPLY", {
        get: function() {
            return this._VIGNETTEMODE_MULTIPLY
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "VIGNETTEMODE_OPAQUE", {
        get: function() {
            return this._VIGNETTEMODE_OPAQUE
        },
        enumerable: !1,
        configurable: !0
    }),
    a.TONEMAPPING_STANDARD = 0,
    a.TONEMAPPING_ACES = 1,
    a._VIGNETTEMODE_MULTIPLY = 0,
    a._VIGNETTEMODE_OPAQUE = 1,
    __decorate([serializeAsColorCurves()], a.prototype, "colorCurves", void 0),
    __decorate([serialize()], a.prototype, "_colorCurvesEnabled", void 0),
    __decorate([serializeAsTexture("colorGradingTexture")], a.prototype, "_colorGradingTexture", void 0),
    __decorate([serialize()], a.prototype, "_colorGradingEnabled", void 0),
    __decorate([serialize()], a.prototype, "_colorGradingWithGreenDepth", void 0),
    __decorate([serialize()], a.prototype, "_colorGradingBGR", void 0),
    __decorate([serialize()], a.prototype, "_exposure", void 0),
    __decorate([serialize()], a.prototype, "_toneMappingEnabled", void 0),
    __decorate([serialize()], a.prototype, "_toneMappingType", void 0),
    __decorate([serialize()], a.prototype, "_contrast", void 0),
    __decorate([serialize()], a.prototype, "vignetteStretch", void 0),
    __decorate([serialize()], a.prototype, "vignetteCentreX", void 0),
    __decorate([serialize()], a.prototype, "vignetteCentreY", void 0),
    __decorate([serialize()], a.prototype, "vignetteWeight", void 0),
    __decorate([serializeAsColor4()], a.prototype, "vignetteColor", void 0),
    __decorate([serialize()], a.prototype, "vignetteCameraFov", void 0),
    __decorate([serialize()], a.prototype, "_vignetteBlendMode", void 0),
    __decorate([serialize()], a.prototype, "_vignetteEnabled", void 0),
    __decorate([serialize()], a.prototype, "_skipFinalColorClamp", void 0),
    __decorate([serialize()], a.prototype, "_applyByPostProcess", void 0),
    __decorate([serialize()], a.prototype, "_isEnabled", void 0),
    a
}();
SerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse;
var ActionEvent = function() {
    function a(e, i, o, s, c, d) {
        this.source = e,
        this.pointerX = i,
        this.pointerY = o,
        this.meshUnderPointer = s,
        this.sourceEvent = c,
        this.additionalData = d
    }
    return a.CreateNew = function(e, i, o) {
        var s = e.getScene();
        return new a(e,s.pointerX,s.pointerY,s.meshUnderPointer || e,i,o)
    }
    ,
    a.CreateNewFromSprite = function(e, i, o, s) {
        return new a(e,i.pointerX,i.pointerY,i.meshUnderPointer,o,s)
    }
    ,
    a.CreateNewFromScene = function(e, i) {
        return new a(null,e.pointerX,e.pointerY,e.meshUnderPointer,i)
    }
    ,
    a.CreateNewFromPrimitive = function(e, i, o, s) {
        return new a(e,i.x,i.y,null,o,s)
    }
    ,
    a
}(), PostProcessManager = function() {
    function a(e) {
        this._vertexBuffers = {},
        this._scene = e
    }
    return a.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()
        }
    }
    ,
    a.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)
    }
    ,
    a.prototype._rebuild = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        !e || (e._rebuild(),
        this._buildIndexBuffer())
    }
    ,
    a.prototype._prepareFrame = function(e, i) {
        e === void 0 && (e = null),
        i === void 0 && (i = null);
        var o = this._scene.activeCamera;
        return !o || (i = i || o._postProcesses.filter(function(s) {
            return s != null
        }),
        !i || i.length === 0 || !this._scene.postProcessesEnabled) ? !1 : (i[0].activate(o, e, i != null),
        !0)
    }
    ,
    a.prototype.directRender = function(e, i, o, s, c, d) {
        var _;
        i === void 0 && (i = null),
        o === void 0 && (o = !1),
        s === void 0 && (s = 0),
        c === void 0 && (c = 0),
        d === void 0 && (d = !1);
        for (var b = this._scene.getEngine(), k = 0; k < e.length; k++) {
            k < e.length - 1 ? e[k + 1].activate(this._scene.activeCamera, i == null ? void 0 : i.texture) : (i ? b.bindFramebuffer(i, s, void 0, void 0, o, c) : d || b.restoreDefaultFramebuffer(),
            (_ = b._debugInsertMarker) === null || _ === void 0 || _.call(b, "post process " + e[k].name + " output"));
            var j = e[k]
              , $ = j.apply();
            $ && (j.onBeforeRenderObservable.notifyObservers($),
            this._prepareBuffers(),
            b.bindBuffers(this._vertexBuffers, this._indexBuffer, $),
            b.drawElementsType(0, 0, 6),
            j.onAfterRenderObservable.notifyObservers($))
        }
        b.setDepthBuffer(!0),
        b.setDepthWrite(!0)
    }
    ,
    a.prototype._finalizeFrame = function(e, i, o, s, c) {
        var d;
        c === void 0 && (c = !1);
        var _ = this._scene.activeCamera;
        if (!!_ && (s = s || _._postProcesses.filter(function(et) {
            return et != null
        }),
        !(s.length === 0 || !this._scene.postProcessesEnabled))) {
            for (var b = this._scene.getEngine(), k = 0, j = s.length; k < j; k++) {
                var $ = s[k];
                if (k < j - 1 ? $._outputTexture = s[k + 1].activate(_, i == null ? void 0 : i.texture) : (i ? (b.bindFramebuffer(i, o, void 0, void 0, c),
                $._outputTexture = i) : (b.restoreDefaultFramebuffer(),
                $._outputTexture = null),
                (d = b._debugInsertMarker) === null || d === void 0 || d.call(b, "post process " + s[k].name + " output")),
                e)
                    break;
                var _e = $.apply();
                _e && ($.onBeforeRenderObservable.notifyObservers(_e),
                this._prepareBuffers(),
                b.bindBuffers(this._vertexBuffers, this._indexBuffer, _e),
                b.drawElementsType(0, 0, 6),
                $.onAfterRenderObservable.notifyObservers(_e))
            }
            b.setDepthBuffer(!0),
            b.setDepthWrite(!0),
            b.setAlphaMode(0)
        }
    }
    ,
    a.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)
    }
    ,
    a
}(), RenderingGroup = function() {
    function a(e, i, o, s, c) {
        o === void 0 && (o = null),
        s === void 0 && (s = null),
        c === void 0 && (c = 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 = i,
        this.opaqueSortCompareFn = o,
        this.alphaTestSortCompareFn = s,
        this.transparentSortCompareFn = c
    }
    return Object.defineProperty(a.prototype, "opaqueSortCompareFn", {
        set: function(e) {
            this._opaqueSortCompareFn = e,
            e ? this._renderOpaque = this.renderOpaqueSorted : this._renderOpaque = a.renderUnsorted
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "alphaTestSortCompareFn", {
        set: function(e) {
            this._alphaTestSortCompareFn = e,
            e ? this._renderAlphaTest = this.renderAlphaTestSorted : this._renderAlphaTest = a.renderUnsorted
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "transparentSortCompareFn", {
        set: function(e) {
            e ? this._transparentSortCompareFn = e : this._transparentSortCompareFn = a.defaultTransparentSortCompare,
            this._renderTransparent = this.renderTransparentSorted
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.render = function(e, i, o, s) {
        if (e) {
            e(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
            return
        }
        var c = this._scene.getEngine();
        this._depthOnlySubMeshes.length !== 0 && (c.setColorWrite(!1),
        this._renderAlphaTest(this._depthOnlySubMeshes),
        c.setColorWrite(!0)),
        this._opaqueSubMeshes.length !== 0 && this._renderOpaque(this._opaqueSubMeshes),
        this._alphaTestSubMeshes.length !== 0 && this._renderAlphaTest(this._alphaTestSubMeshes);
        var d = c.getStencilBuffer();
        if (c.setStencilBuffer(!1),
        i && this._renderSprites(),
        o && this._renderParticles(s),
        this.onBeforeTransparentRendering && this.onBeforeTransparentRendering(),
        (this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) && (c.setStencilBuffer(d),
        this._scene.useOrderIndependentTransparency ? this._scene.depthPeelingRenderer.render(this._transparentSubMeshes) : this._renderTransparent(this._transparentSubMeshes),
        c.setAlphaMode(0)),
        c.setStencilBuffer(!1),
        this._edgesRenderers.length) {
            for (var _ = 0; _ < this._edgesRenderers.length; _++)
                this._edgesRenderers.data[_].render();
            c.setAlphaMode(0)
        }
        c.setStencilBuffer(d)
    }
    ,
    a.prototype.renderOpaqueSorted = function(e) {
        return a.renderSorted(e, this._opaqueSortCompareFn, this._scene.activeCamera, !1)
    }
    ,
    a.prototype.renderAlphaTestSorted = function(e) {
        return a.renderSorted(e, this._alphaTestSortCompareFn, this._scene.activeCamera, !1)
    }
    ,
    a.prototype.renderTransparentSorted = function(e) {
        return a.renderSorted(e, this._transparentSortCompareFn, this._scene.activeCamera, !0)
    }
    ,
    a.renderSorted = function(e, i, o, s) {
        for (var c = 0, d, _ = o ? o.globalPosition : a._zeroVector; c < e.length; c++)
            d = e.data[c],
            d._alphaIndex = d.getMesh().alphaIndex,
            d._distanceToCamera = Vector3.Distance(d.getBoundingInfo().boundingSphere.centerWorld, _);
        var b = e.data.slice(0, e.length);
        for (i && b.sort(i),
        c = 0; c < b.length; c++) {
            if (d = b[c],
            s) {
                var k = d.getMaterial();
                if (k && k.needDepthPrePass) {
                    var j = k.getScene().getEngine();
                    j.setColorWrite(!1),
                    j.setAlphaMode(0),
                    d.render(!1),
                    j.setColorWrite(!0)
                }
            }
            d.render(s)
        }
    }
    ,
    a.renderUnsorted = function(e) {
        for (var i = 0; i < e.length; i++) {
            var o = e.data[i];
            o.render(!1)
        }
    }
    ,
    a.defaultTransparentSortCompare = function(e, i) {
        return e._alphaIndex > i._alphaIndex ? 1 : e._alphaIndex < i._alphaIndex ? -1 : a.backToFrontSortCompare(e, i)
    }
    ,
    a.backToFrontSortCompare = function(e, i) {
        return e._distanceToCamera < i._distanceToCamera ? 1 : e._distanceToCamera > i._distanceToCamera ? -1 : 0
    }
    ,
    a.frontToBackSortCompare = function(e, i) {
        return e._distanceToCamera < i._distanceToCamera ? -1 : e._distanceToCamera > i._distanceToCamera ? 1 : 0
    }
    ,
    a.prototype.prepare = function() {
        this._opaqueSubMeshes.reset(),
        this._transparentSubMeshes.reset(),
        this._alphaTestSubMeshes.reset(),
        this._depthOnlySubMeshes.reset(),
        this._particleSystems.reset(),
        this._spriteManagers.reset(),
        this._edgesRenderers.reset()
    }
    ,
    a.prototype.dispose = function() {
        this._opaqueSubMeshes.dispose(),
        this._transparentSubMeshes.dispose(),
        this._alphaTestSubMeshes.dispose(),
        this._depthOnlySubMeshes.dispose(),
        this._particleSystems.dispose(),
        this._spriteManagers.dispose(),
        this._edgesRenderers.dispose()
    }
    ,
    a.prototype.dispatch = function(e, i, o) {
        i === void 0 && (i = e.getMesh()),
        o === void 0 && (o = e.getMaterial()),
        o != null && (o.needAlphaBlendingForMesh(i) ? this._transparentSubMeshes.push(e) : o.needAlphaTesting() ? (o.needDepthPrePass && this._depthOnlySubMeshes.push(e),
        this._alphaTestSubMeshes.push(e)) : (o.needDepthPrePass && this._depthOnlySubMeshes.push(e),
        this._opaqueSubMeshes.push(e)),
        i._renderingGroup = this,
        i._edgesRenderer && i._edgesRenderer.isEnabled && this._edgesRenderers.pushNoDuplicate(i._edgesRenderer))
    }
    ,
    a.prototype.dispatchSprites = function(e) {
        this._spriteManagers.push(e)
    }
    ,
    a.prototype.dispatchParticles = function(e) {
        this._particleSystems.push(e)
    }
    ,
    a.prototype._renderParticles = function(e) {
        if (this._particleSystems.length !== 0) {
            var i = this._scene.activeCamera;
            this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
            for (var o = 0; o < this._particleSystems.length; o++) {
                var s = this._particleSystems.data[o];
                if ((i && i.layerMask & s.layerMask) !== 0) {
                    var c = s.emitter;
                    (!c.position || !e || e.indexOf(c) !== -1) && this._scene._activeParticles.addCount(s.render(), !1)
                }
            }
            this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)
        }
    }
    ,
    a.prototype._renderSprites = function() {
        if (!(!this._scene.spritesEnabled || this._spriteManagers.length === 0)) {
            var e = this._scene.activeCamera;
            this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
            for (var i = 0; i < this._spriteManagers.length; i++) {
                var o = this._spriteManagers.data[i];
                (e && e.layerMask & o.layerMask) !== 0 && o.render()
            }
            this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)
        }
    }
    ,
    a._zeroVector = Vector3.Zero(),
    a
}(), RenderingGroupInfo = function() {
    function a() {}
    return a
}(), RenderingManager = function() {
    function a(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 i = a.MIN_RENDERINGGROUPS; i < a.MAX_RENDERINGGROUPS; i++)
            this._autoClearDepthStencil[i] = {
                autoClear: !0,
                depth: !0,
                stencil: !0
            }
    }
    return a.prototype._clearDepthStencilBuffer = function(e, i) {
        e === void 0 && (e = !0),
        i === void 0 && (i = !0),
        !this._depthStencilBufferAlreadyCleaned && (this._scene.getEngine().clear(null, !1, e, i),
        this._depthStencilBufferAlreadyCleaned = !0)
    }
    ,
    a.prototype.render = function(e, i, o, s) {
        var c = this._renderingGroupInfo;
        if (c.scene = this._scene,
        c.camera = this._scene.activeCamera,
        this._scene.spriteManagers && s)
            for (var d = 0; d < this._scene.spriteManagers.length; d++) {
                var _ = this._scene.spriteManagers[d];
                this.dispatchSprites(_)
            }
        for (var d = a.MIN_RENDERINGGROUPS; d < a.MAX_RENDERINGGROUPS; d++) {
            this._depthStencilBufferAlreadyCleaned = d === a.MIN_RENDERINGGROUPS;
            var b = this._renderingGroups[d];
            if (!!b) {
                var k = Math.pow(2, d);
                if (c.renderingGroupId = d,
                this._scene.onBeforeRenderingGroupObservable.notifyObservers(c, k),
                a.AUTOCLEAR) {
                    var j = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(d) : this._autoClearDepthStencil[d];
                    j && j.autoClear && this._clearDepthStencilBuffer(j.depth, j.stencil)
                }
                for (var $ = 0, _e = this._scene._beforeRenderingGroupDrawStage; $ < _e.length; $++) {
                    var et = _e[$];
                    et.action(d)
                }
                b.render(e, s, o, i);
                for (var tt = 0, rt = this._scene._afterRenderingGroupDrawStage; tt < rt.length; tt++) {
                    var et = rt[tt];
                    et.action(d)
                }
                this._scene.onAfterRenderingGroupObservable.notifyObservers(c, k)
            }
        }
    }
    ,
    a.prototype.reset = function() {
        for (var e = a.MIN_RENDERINGGROUPS; e < a.MAX_RENDERINGGROUPS; e++) {
            var i = this._renderingGroups[e];
            i && i.prepare()
        }
    }
    ,
    a.prototype.dispose = function() {
        this.freeRenderingGroups(),
        this._renderingGroups.length = 0,
        this._renderingGroupInfo = null
    }
    ,
    a.prototype.freeRenderingGroups = function() {
        for (var e = a.MIN_RENDERINGGROUPS; e < a.MAX_RENDERINGGROUPS; e++) {
            var i = this._renderingGroups[e];
            i && i.dispose()
        }
    }
    ,
    a.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]))
    }
    ,
    a.prototype.dispatchSprites = function(e) {
        var i = e.renderingGroupId || 0;
        this._prepareRenderingGroup(i),
        this._renderingGroups[i].dispatchSprites(e)
    }
    ,
    a.prototype.dispatchParticles = function(e) {
        var i = e.renderingGroupId || 0;
        this._prepareRenderingGroup(i),
        this._renderingGroups[i].dispatchParticles(e)
    }
    ,
    a.prototype.dispatch = function(e, i, o) {
        i === void 0 && (i = e.getMesh());
        var s = i.renderingGroupId || 0;
        this._prepareRenderingGroup(s),
        this._renderingGroups[s].dispatch(e, i, o)
    }
    ,
    a.prototype.setRenderingOrder = function(e, i, o, s) {
        if (i === void 0 && (i = null),
        o === void 0 && (o = null),
        s === void 0 && (s = null),
        this._customOpaqueSortCompareFn[e] = i,
        this._customAlphaTestSortCompareFn[e] = o,
        this._customTransparentSortCompareFn[e] = s,
        this._renderingGroups[e]) {
            var c = this._renderingGroups[e];
            c.opaqueSortCompareFn = this._customOpaqueSortCompareFn[e],
            c.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[e],
            c.transparentSortCompareFn = this._customTransparentSortCompareFn[e]
        }
    }
    ,
    a.prototype.setRenderingAutoClearDepthStencil = function(e, i, o, s) {
        o === void 0 && (o = !0),
        s === void 0 && (s = !0),
        this._autoClearDepthStencil[e] = {
            autoClear: i,
            depth: o,
            stencil: s
        }
    }
    ,
    a.prototype.getAutoClearDepthStencilSetup = function(e) {
        return this._autoClearDepthStencil[e]
    }
    ,
    a.MAX_RENDERINGGROUPS = 4,
    a.MIN_RENDERINGGROUPS = 0,
    a.AUTOCLEAR = !0,
    a
}(), SceneComponentConstants = function() {
    function a() {}
    return a.NAME_EFFECTLAYER = "EffectLayer",
    a.NAME_LAYER = "Layer",
    a.NAME_LENSFLARESYSTEM = "LensFlareSystem",
    a.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer",
    a.NAME_PARTICLESYSTEM = "ParticleSystem",
    a.NAME_GAMEPAD = "Gamepad",
    a.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue",
    a.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer",
    a.NAME_PREPASSRENDERER = "PrePassRenderer",
    a.NAME_DEPTHRENDERER = "DepthRenderer",
    a.NAME_DEPTHPEELINGRENDERER = "DepthPeelingRenderer",
    a.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager",
    a.NAME_SPRITE = "Sprite",
    a.NAME_SUBSURFACE = "SubSurface",
    a.NAME_OUTLINERENDERER = "Outline",
    a.NAME_PROCEDURALTEXTURE = "ProceduralTexture",
    a.NAME_SHADOWGENERATOR = "ShadowGenerator",
    a.NAME_OCTREE = "Octree",
    a.NAME_PHYSICSENGINE = "PhysicsEngine",
    a.NAME_AUDIO = "Audio",
    a.STEP_ISREADYFORMESH_EFFECTLAYER = 0,
    a.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0,
    a.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0,
    a.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0,
    a.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1,
    a.STEP_BEFORECAMERADRAW_PREPASS = 0,
    a.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1,
    a.STEP_BEFORECAMERADRAW_LAYER = 2,
    a.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0,
    a.STEP_BEFORERENDERTARGETDRAW_LAYER = 1,
    a.STEP_BEFORERENDERINGMESH_PREPASS = 0,
    a.STEP_BEFORERENDERINGMESH_OUTLINE = 1,
    a.STEP_AFTERRENDERINGMESH_PREPASS = 0,
    a.STEP_AFTERRENDERINGMESH_OUTLINE = 1,
    a.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0,
    a.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1,
    a.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0,
    a.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1,
    a.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0,
    a.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0,
    a.STEP_AFTERRENDERTARGETDRAW_LAYER = 1,
    a.STEP_AFTERCAMERADRAW_PREPASS = 0,
    a.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1,
    a.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2,
    a.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3,
    a.STEP_AFTERCAMERADRAW_LAYER = 4,
    a.STEP_AFTERRENDER_AUDIO = 0,
    a.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0,
    a.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1,
    a.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2,
    a.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3,
    a.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0,
    a.STEP_BEFORECLEARSTAGE_PREPASS = 0,
    a.STEP_BEFORERENDERTARGETCLEARSTAGE_PREPASS = 0,
    a.STEP_POINTERMOVE_SPRITE = 0,
    a.STEP_POINTERDOWN_SPRITE = 0,
    a.STEP_POINTERUP_SPRITE = 0,
    a
}(), Stage = function(a) {
    __extends(e, a);
    function e(i) {
        return a.apply(this, i) || this
    }
    return e.Create = function() {
        return Object.create(e.prototype)
    }
    ,
    e.prototype.registerStep = function(i, o, s) {
        for (var c = 0, d = Number.MAX_VALUE; c < this.length; c++) {
            var _ = this[c];
            if (d = _.index,
            i < d)
                break
        }
        this.splice(c, 0, {
            index: i,
            component: o,
            action: s.bind(o)
        })
    }
    ,
    e.prototype.clear = function() {
        this.length = 0
    }
    ,
    e
}(Array), PointerEventTypes = function() {
    function a() {}
    return a.POINTERDOWN = 1,
    a.POINTERUP = 2,
    a.POINTERMOVE = 4,
    a.POINTERWHEEL = 8,
    a.POINTERPICK = 16,
    a.POINTERTAP = 32,
    a.POINTERDOUBLETAP = 64,
    a
}(), PointerInfoBase = function() {
    function a(e, i) {
        this.type = e,
        this.event = i
    }
    return a
}(), PointerInfoPre = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        var d = a.call(this, i, o) || this;
        return d.ray = null,
        d.skipOnPointerObservable = !1,
        d.localPosition = new Vector2(s,c),
        d
    }
    return e
}(PointerInfoBase), PointerInfo = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, o) || this;
        return c.pickInfo = s,
        c
    }
    return e
}(PointerInfoBase), AbstractActionManager = function() {
    function a() {
        this.hoverCursor = "",
        this.actions = new Array,
        this.isRecursive = !1
    }
    return Object.defineProperty(a, "HasTriggers", {
        get: function() {
            for (var e in a.Triggers)
                if (a.Triggers.hasOwnProperty(e))
                    return !0;
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "HasPickTriggers", {
        get: function() {
            for (var e in a.Triggers)
                if (a.Triggers.hasOwnProperty(e)) {
                    var i = parseInt(e);
                    if (i >= 1 && i <= 7)
                        return !0
                }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    a.HasSpecificTrigger = function(e) {
        for (var i in a.Triggers)
            if (a.Triggers.hasOwnProperty(i)) {
                var o = parseInt(i);
                if (o === e)
                    return !0
            }
        return !1
    }
    ,
    a.Triggers = {},
    a
}(), KeyboardEventTypes = function() {
    function a() {}
    return a.KEYDOWN = 1,
    a.KEYUP = 2,
    a
}(), KeyboardInfo = function() {
    function a(e, i) {
        this.type = e,
        this.event = i
    }
    return a
}(), KeyboardInfoPre = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o) || this;
        return s.type = i,
        s.event = o,
        s.skipOnPointerObservable = !1,
        s
    }
    return e
}(KeyboardInfo), DeviceType;
(function(a) {
    a[a.Generic = 0] = "Generic",
    a[a.Keyboard = 1] = "Keyboard",
    a[a.Mouse = 2] = "Mouse",
    a[a.Touch = 3] = "Touch",
    a[a.DualShock = 4] = "DualShock",
    a[a.Xbox = 5] = "Xbox",
    a[a.Switch = 6] = "Switch"
}
)(DeviceType || (DeviceType = {}));
var PointerInput;
(function(a) {
    a[a.Horizontal = 0] = "Horizontal",
    a[a.Vertical = 1] = "Vertical",
    a[a.LeftClick = 2] = "LeftClick",
    a[a.MiddleClick = 3] = "MiddleClick",
    a[a.RightClick = 4] = "RightClick",
    a[a.BrowserBack = 5] = "BrowserBack",
    a[a.BrowserForward = 6] = "BrowserForward",
    a[a.MouseWheelX = 7] = "MouseWheelX",
    a[a.MouseWheelY = 8] = "MouseWheelY",
    a[a.MouseWheelZ = 9] = "MouseWheelZ",
    a[a.DeltaHorizontal = 10] = "DeltaHorizontal",
    a[a.DeltaVertical = 11] = "DeltaVertical"
}
)(PointerInput || (PointerInput = {}));
var DualShockInput;
(function(a) {
    a[a.Cross = 0] = "Cross",
    a[a.Circle = 1] = "Circle",
    a[a.Square = 2] = "Square",
    a[a.Triangle = 3] = "Triangle",
    a[a.L1 = 4] = "L1",
    a[a.R1 = 5] = "R1",
    a[a.L2 = 6] = "L2",
    a[a.R2 = 7] = "R2",
    a[a.Share = 8] = "Share",
    a[a.Options = 9] = "Options",
    a[a.L3 = 10] = "L3",
    a[a.R3 = 11] = "R3",
    a[a.DPadUp = 12] = "DPadUp",
    a[a.DPadDown = 13] = "DPadDown",
    a[a.DPadLeft = 14] = "DPadLeft",
    a[a.DPadRight = 15] = "DPadRight",
    a[a.Home = 16] = "Home",
    a[a.TouchPad = 17] = "TouchPad",
    a[a.LStickXAxis = 18] = "LStickXAxis",
    a[a.LStickYAxis = 19] = "LStickYAxis",
    a[a.RStickXAxis = 20] = "RStickXAxis",
    a[a.RStickYAxis = 21] = "RStickYAxis"
}
)(DualShockInput || (DualShockInput = {}));
var XboxInput;
(function(a) {
    a[a.A = 0] = "A",
    a[a.B = 1] = "B",
    a[a.X = 2] = "X",
    a[a.Y = 3] = "Y",
    a[a.LB = 4] = "LB",
    a[a.RB = 5] = "RB",
    a[a.LT = 6] = "LT",
    a[a.RT = 7] = "RT",
    a[a.Back = 8] = "Back",
    a[a.Start = 9] = "Start",
    a[a.LS = 10] = "LS",
    a[a.RS = 11] = "RS",
    a[a.DPadUp = 12] = "DPadUp",
    a[a.DPadDown = 13] = "DPadDown",
    a[a.DPadLeft = 14] = "DPadLeft",
    a[a.DPadRight = 15] = "DPadRight",
    a[a.Home = 16] = "Home",
    a[a.LStickXAxis = 17] = "LStickXAxis",
    a[a.LStickYAxis = 18] = "LStickYAxis",
    a[a.RStickXAxis = 19] = "RStickXAxis",
    a[a.RStickYAxis = 20] = "RStickYAxis"
}
)(XboxInput || (XboxInput = {}));
var SwitchInput;
(function(a) {
    a[a.B = 0] = "B",
    a[a.A = 1] = "A",
    a[a.Y = 2] = "Y",
    a[a.X = 3] = "X",
    a[a.L = 4] = "L",
    a[a.R = 5] = "R",
    a[a.ZL = 6] = "ZL",
    a[a.ZR = 7] = "ZR",
    a[a.Minus = 8] = "Minus",
    a[a.Plus = 9] = "Plus",
    a[a.LS = 10] = "LS",
    a[a.RS = 11] = "RS",
    a[a.DPadUp = 12] = "DPadUp",
    a[a.DPadDown = 13] = "DPadDown",
    a[a.DPadLeft = 14] = "DPadLeft",
    a[a.DPadRight = 15] = "DPadRight",
    a[a.Home = 16] = "Home",
    a[a.Capture = 17] = "Capture",
    a[a.LStickXAxis = 18] = "LStickXAxis",
    a[a.LStickYAxis = 19] = "LStickYAxis",
    a[a.RStickXAxis = 20] = "RStickXAxis",
    a[a.RStickYAxis = 21] = "RStickYAxis"
}
)(SwitchInput || (SwitchInput = {}));
var DeviceInputEventType;
(function(a) {
    a[a.PointerMove = 0] = "PointerMove",
    a[a.PointerDown = 1] = "PointerDown",
    a[a.PointerUp = 2] = "PointerUp"
}
)(DeviceInputEventType || (DeviceInputEventType = {}));
var EventConstants = function() {
    function a() {}
    return a.DOM_DELTA_PIXEL = 0,
    a.DOM_DELTA_LINE = 1,
    a.DOM_DELTA_PAGE = 2,
    a
}()
  , DeviceEventFactory = function() {
    function a() {}
    return a.CreateDeviceEvent = function(e, i, o, s, c, d) {
        switch (e) {
        case DeviceType.Keyboard:
            return this._createKeyboardEvent(o, s, c, d);
        case DeviceType.Mouse:
            if (o === PointerInput.MouseWheelX || o === PointerInput.MouseWheelY || o === PointerInput.MouseWheelZ)
                return this._createWheelEvent(e, i, o, s, c, d);
        case DeviceType.Touch:
            return this._createPointerEvent(e, i, o, s, c, d);
        default:
            throw "Unable to generate event for device " + DeviceType[e]
        }
    }
    ,
    a._createPointerEvent = function(e, i, o, s, c, d) {
        var _ = this._createMouseEvent(e, i, o, s, c, d);
        return _.pointerId = e === DeviceType.Mouse ? 1 : i,
        o === PointerInput.Horizontal || o === PointerInput.Vertical || o === PointerInput.DeltaHorizontal || o === PointerInput.DeltaVertical ? _.type = "pointermove" : o >= PointerInput.LeftClick && o <= PointerInput.RightClick && (_.type = s === 1 ? "pointerdown" : "pointerup",
        _.button = o - 2),
        _
    }
    ,
    a._createWheelEvent = function(e, i, o, s, c, d) {
        var _ = this._createMouseEvent(e, i, o, s, c, d);
        return _.type = "wheel",
        _.deltaMode = EventConstants.DOM_DELTA_PIXEL,
        _.deltaX = o === PointerInput.MouseWheelX ? s : c.pollInput(e, i, PointerInput.MouseWheelX),
        _.deltaY = o === PointerInput.MouseWheelY ? s : c.pollInput(e, i, PointerInput.MouseWheelY),
        _.deltaZ = o === PointerInput.MouseWheelZ ? s : c.pollInput(e, i, PointerInput.MouseWheelZ),
        _
    }
    ,
    a._createMouseEvent = function(e, i, o, s, c, d) {
        var _ = this._createEvent(d)
          , b = c.pollInput(e, i, PointerInput.Horizontal)
          , k = c.pollInput(e, i, PointerInput.Vertical)
          , j = o === PointerInput.DeltaHorizontal ? s : 0
          , $ = o === PointerInput.DeltaVertical ? s : 0
          , _e = o === PointerInput.DeltaHorizontal && d ? j - d.getBoundingClientRect().x : 0
          , et = o === PointerInput.DeltaVertical && d ? $ - d.getBoundingClientRect().y : 0;
        return this._checkNonCharacterKeys(_, c),
        _.clientX = b,
        _.clientY = k,
        _.movementX = j,
        _.movementY = $,
        _.offsetX = _e,
        _.offsetY = et,
        _.x = b,
        _.y = k,
        _
    }
    ,
    a._createKeyboardEvent = function(e, i, o, s) {
        var c = this._createEvent(s);
        return this._checkNonCharacterKeys(c, o),
        c.type = i === 1 ? "keydown" : "keyup",
        c.key = String.fromCharCode(e),
        c.keyCode = e,
        c
    }
    ,
    a._checkNonCharacterKeys = function(e, i) {
        var o = i.isDeviceAvailable(DeviceType.Keyboard)
          , s = o && i.pollInput(DeviceType.Keyboard, 0, 18) === 1
          , c = o && i.pollInput(DeviceType.Keyboard, 0, 17) === 1
          , d = o && (i.pollInput(DeviceType.Keyboard, 0, 91) === 1 || i.pollInput(DeviceType.Keyboard, 0, 92) === 1 || i.pollInput(DeviceType.Keyboard, 0, 93) === 1)
          , _ = o && i.pollInput(DeviceType.Keyboard, 0, 16) === 1;
        e.altKey = s,
        e.ctrlKey = c,
        e.metaKey = d,
        e.shiftKey = _
    }
    ,
    a._createEvent = function(e) {
        var i = {};
        return i.preventDefault = function() {}
        ,
        i.target = e,
        i
    }
    ,
    a
}()
  , NativeDeviceInputSystemImpl = function() {
    function a(e) {
        var i = this;
        this.onDeviceConnected = function(o, s) {}
        ,
        this.onDeviceDisconnected = function(o, s) {}
        ,
        this.onInputChanged = function(o) {}
        ,
        this._nativeInput = e || this._createDummyNativeInput(),
        this._nativeInput.onDeviceConnected = function(o, s) {
            i.onDeviceConnected(o, s)
        }
        ,
        this._nativeInput.onDeviceDisconnected = function(o, s) {
            i.onDeviceDisconnected(o, s)
        }
        ,
        this._nativeInput.onInputChanged = function(o, s, c, d, _, b) {
            var k = DeviceEventFactory.CreateDeviceEvent(o, s, c, _, i)
              , j = k;
            j.deviceType = o,
            j.deviceSlot = s,
            j.inputIndex = c,
            j.previousState = d,
            j.currentState = _,
            i.onInputChanged(j)
        }
    }
    return a.prototype.configureEvents = function() {}
    ,
    a.prototype.pollInput = function(e, i, o) {
        return this._nativeInput.pollInput(e, i, o)
    }
    ,
    a.prototype.isDeviceAvailable = function(e) {
        return e === DeviceType.Mouse || e === DeviceType.Touch
    }
    ,
    a.prototype.dispose = function() {
        this.onDeviceConnected = function() {}
        ,
        this.onDeviceDisconnected = function() {}
        ,
        this.onInputChanged = function() {}
    }
    ,
    a.prototype._createDummyNativeInput = function() {
        var e = {
            onDeviceConnected: function(i, o) {},
            onDeviceDisconnected: function(i, o) {},
            onInputChanged: function(i, o, s, c, d, _) {},
            pollInput: function() {
                return 0
            },
            isDeviceAvailable: function() {
                return !1
            },
            dispose: function() {}
        };
        return e
    }
    ,
    a
}()
  , WebDeviceInputSystemImpl = function() {
    function a(e) {
        this._inputs = [],
        this._keyboardActive = !1,
        this._pointerActive = !1,
        this._usingSafari = Tools.IsSafari(),
        this._keyboardDownEvent = function(i) {}
        ,
        this._keyboardUpEvent = function(i) {}
        ,
        this._keyboardBlurEvent = function(i) {}
        ,
        this._pointerMoveEvent = function(i) {}
        ,
        this._pointerDownEvent = function(i) {}
        ,
        this._pointerUpEvent = function(i) {}
        ,
        this._pointerWheelEvent = function(i) {}
        ,
        this._pointerBlurEvent = function(i) {}
        ,
        this._mouseId = -1,
        this._isUsingFirefox = navigator && navigator.userAgent && navigator.userAgent.indexOf("Firefox") !== -1,
        this._activeTouchIds = [],
        this._rollingTouchId = 0,
        this._pointerInputClearObserver = null,
        this._gamepadConnectedEvent = function(i) {}
        ,
        this._gamepadDisconnectedEvent = function(i) {}
        ,
        this._eventPrefix = Tools.GetPointerPrefix(e),
        this._engine = e,
        this.onDeviceConnected = function(i, o) {}
        ,
        this.onDeviceDisconnected = function(i, o) {}
        ,
        this.onInputChanged = function(i) {}
        ,
        this.configureEvents()
    }
    return Object.defineProperty(a.prototype, "onDeviceConnected", {
        get: function() {
            return this._onDeviceConnected
        },
        set: function(e) {
            this._onDeviceConnected = e;
            for (var i = 0; i < this._inputs.length; i++) {
                var o = this._inputs[i];
                if (o)
                    for (var s in o) {
                        var c = +s;
                        this._inputs[i][c] && this._onDeviceConnected(i, c)
                    }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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())
    }
    ,
    a.prototype.pollInput = function(e, i, o) {
        var s = this._inputs[e][i];
        if (!s)
            throw "Unable to find device " + DeviceType[e];
        e >= DeviceType.Xbox && e <= DeviceType.Switch && navigator.getGamepads && this._updateDevice(e, i, o);
        var c = s[o];
        if (c === void 0)
            throw "Unable to find input " + o + " for device " + DeviceType[e] + " in slot " + i;
        return c
    }
    ,
    a.prototype.isDeviceAvailable = function(e) {
        return this._inputs[e] !== void 0
    }
    ,
    a.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))
    }
    ,
    a.prototype._checkForConnectedDevices = function() {
        if (navigator.getGamepads)
            for (var e = navigator.getGamepads(), i = 0, o = e; i < o.length; i++) {
                var s = o[i];
                s && this._addGamePad(s)
            }
        matchMedia("(pointer:fine)").matches && this._addPointerDevice(DeviceType.Mouse, 0, 0, 0)
    }
    ,
    a.prototype._addGamePad = function(e) {
        var i = this._getGamepadDeviceType(e.id)
          , o = e.index;
        this._registerDevice(i, o, e.buttons.length + e.axes.length),
        this._gamepads = this._gamepads || new Array(e.index + 1),
        this._gamepads[o] = i
    }
    ,
    a.prototype._addPointerDevice = function(e, i, o, s) {
        this._pointerActive = !0,
        this._registerDevice(e, i, a.MAX_POINTER_INPUTS);
        var c = this._inputs[e][i];
        c[0] = o,
        c[1] = s
    }
    ,
    a.prototype._registerDevice = function(e, i, o) {
        if (i === void 0)
            throw "Unable to register device " + DeviceType[e] + " to undefined slot.";
        if (this._inputs[e] || (this._inputs[e] = {}),
        !this._inputs[e][i]) {
            for (var s = new Array(o), c = 0; c < o; c++)
                s[c] = 0;
            this._inputs[e][i] = s,
            this.onDeviceConnected(e, i)
        }
    }
    ,
    a.prototype._unregisterDevice = function(e, i) {
        this._inputs[e][i] && (delete this._inputs[e][i],
        this.onDeviceDisconnected(e, i))
    }
    ,
    a.prototype._handleKeyActions = function() {
        var e = this;
        this._keyboardDownEvent = function(i) {
            e._keyboardActive || (e._keyboardActive = !0,
            e._registerDevice(DeviceType.Keyboard, 0, a.MAX_KEYCODES));
            var o = e._inputs[DeviceType.Keyboard][0];
            if (o) {
                o[i.keyCode] = 1;
                var s = i;
                s.deviceType = DeviceType.Keyboard,
                s.deviceSlot = 0,
                s.inputIndex = i.keyCode,
                s.previousState = 0,
                s.currentState = o[i.keyCode],
                e.onInputChanged(s)
            }
        }
        ,
        this._keyboardUpEvent = function(i) {
            e._keyboardActive || (e._keyboardActive = !0,
            e._registerDevice(DeviceType.Keyboard, 0, a.MAX_KEYCODES));
            var o = e._inputs[DeviceType.Keyboard][0];
            if (o) {
                o[i.keyCode] = 0;
                var s = i;
                s.deviceType = DeviceType.Keyboard,
                s.deviceSlot = 0,
                s.inputIndex = i.keyCode,
                s.previousState = 1,
                s.currentState = o[i.keyCode],
                e.onInputChanged(s)
            }
        }
        ,
        this._keyboardBlurEvent = function(i) {
            if (e._keyboardActive) {
                for (var o = e._inputs[DeviceType.Keyboard][0], s = 0; s < o.length; s++)
                    if (o[s] !== 0) {
                        o[s] = 0;
                        var c = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, s, 1, e, e._elementToAttachTo)
                          , d = c;
                        d.deviceType = DeviceType.Keyboard,
                        d.deviceSlot = 0,
                        d.inputIndex = s,
                        d.currentState = 0,
                        d.previousState = 1,
                        e.onInputChanged(d)
                    }
            }
        }
        ,
        this._elementToAttachTo.addEventListener("keydown", this._keyboardDownEvent),
        this._elementToAttachTo.addEventListener("keyup", this._keyboardUpEvent),
        this._elementToAttachTo.addEventListener("blur", this._keyboardBlurEvent)
    }
    ,
    a.prototype._handlePointerActions = function() {
        var e = this;
        this._pointerMoveEvent = function(c) {
            var d = e._getPointerType(c)
              , _ = d === DeviceType.Mouse ? 0 : e._activeTouchIds.indexOf(c.pointerId);
            e._inputs[d] || (e._inputs[d] = {}),
            e._inputs[d][_] || e._addPointerDevice(d, _, c.clientX, c.clientY);
            var b = e._inputs[d][_];
            if (b) {
                var k = b[PointerInput.Horizontal]
                  , j = b[PointerInput.Vertical]
                  , $ = b[PointerInput.DeltaHorizontal]
                  , _e = b[PointerInput.DeltaVertical];
                b[PointerInput.Horizontal] = c.clientX,
                b[PointerInput.Vertical] = c.clientY,
                b[PointerInput.DeltaHorizontal] = c.movementX,
                b[PointerInput.DeltaVertical] = c.movementY;
                var et = c;
                et.deviceType = d,
                et.deviceSlot = _,
                k !== c.clientX && (et.inputIndex = PointerInput.Horizontal,
                et.previousState = k,
                et.currentState = b[PointerInput.Horizontal],
                e.onInputChanged(et)),
                j !== c.clientY && (et.inputIndex = PointerInput.Vertical,
                et.previousState = j,
                et.currentState = b[PointerInput.Vertical],
                e.onInputChanged(et)),
                b[PointerInput.DeltaHorizontal] !== 0 && (et.inputIndex = PointerInput.DeltaHorizontal,
                et.previousState = $,
                et.currentState = b[PointerInput.DeltaHorizontal],
                e.onInputChanged(et)),
                b[PointerInput.DeltaVertical] !== 0 && (et.inputIndex = PointerInput.DeltaVertical,
                et.previousState = _e,
                et.currentState = b[PointerInput.DeltaVertical],
                e.onInputChanged(et)),
                !e._usingSafari && c.button !== -1 && (et.inputIndex = c.button + 2,
                et.previousState = b[c.button + 2],
                b[c.button + 2] = b[c.button + 2] ? 0 : 1,
                et.currentState = b[c.button + 2],
                e.onInputChanged(et))
            }
        }
        ,
        this._pointerDownEvent = function(c) {
            var d = e._getPointerType(c)
              , _ = d === DeviceType.Mouse ? 0 : c.pointerId;
            d === DeviceType.Touch && (_ = e._rollingTouchId++,
            e._activeTouchIds[_] = c.pointerId),
            e._inputs[d] || (e._inputs[d] = {}),
            e._inputs[d][_] || e._addPointerDevice(d, _, c.clientX, c.clientY);
            var b = e._inputs[d][_];
            if (b) {
                var k = b[PointerInput.Horizontal]
                  , j = b[PointerInput.Vertical]
                  , $ = b[c.button + 2];
                if (d === DeviceType.Mouse) {
                    if (e._mouseId === -1 && (c.pointerId === void 0 ? e._mouseId = e._isUsingFirefox ? 0 : 1 : e._mouseId = c.pointerId),
                    !document.pointerLockElement && e._elementToAttachTo.hasPointerCapture)
                        try {
                            e._elementToAttachTo.setPointerCapture(e._mouseId)
                        } catch {}
                } else if (c.pointerId && !document.pointerLockElement && e._elementToAttachTo.hasPointerCapture)
                    try {
                        e._elementToAttachTo.setPointerCapture(c.pointerId)
                    } catch {}
                b[PointerInput.Horizontal] = c.clientX,
                b[PointerInput.Vertical] = c.clientY,
                b[c.button + 2] = 1;
                var _e = c;
                _e.deviceType = d,
                _e.deviceSlot = _,
                k !== c.clientX && (_e.inputIndex = PointerInput.Horizontal,
                _e.previousState = k,
                _e.currentState = b[PointerInput.Horizontal],
                e.onInputChanged(_e)),
                j !== c.clientY && (_e.inputIndex = PointerInput.Vertical,
                _e.previousState = j,
                _e.currentState = b[PointerInput.Vertical],
                e.onInputChanged(_e)),
                _e.inputIndex = c.button + 2,
                _e.previousState = $,
                _e.currentState = b[c.button + 2],
                e.onInputChanged(_e)
            }
        }
        ,
        this._pointerUpEvent = function(c) {
            var d, _, b, k, j, $ = e._getPointerType(c), _e = $ === DeviceType.Mouse ? 0 : e._activeTouchIds.indexOf(c.pointerId), et = (d = e._inputs[$]) === null || d === void 0 ? void 0 : d[_e];
            if (et && et[c.button + 2] !== 0) {
                var tt = et[PointerInput.Horizontal]
                  , rt = et[PointerInput.Vertical]
                  , it = et[c.button + 2];
                et[PointerInput.Horizontal] = c.clientX,
                et[PointerInput.Vertical] = c.clientY,
                et[c.button + 2] = 0;
                var nt = c;
                if (nt.deviceType = $,
                nt.deviceSlot = _e,
                tt !== c.clientX && (nt.inputIndex = PointerInput.Horizontal,
                nt.previousState = tt,
                nt.currentState = et[PointerInput.Horizontal],
                e.onInputChanged(nt)),
                rt !== c.clientY && (nt.inputIndex = PointerInput.Vertical,
                nt.previousState = rt,
                nt.currentState = et[PointerInput.Vertical],
                e.onInputChanged(nt)),
                nt.inputIndex = c.button + 2,
                nt.previousState = it,
                nt.currentState = et[c.button + 2],
                $ === DeviceType.Mouse && e._mouseId >= 0 && ((b = (_ = e._elementToAttachTo).hasPointerCapture) === null || b === void 0 ? void 0 : b.call(_, e._mouseId)) ? e._elementToAttachTo.releasePointerCapture(e._mouseId) : c.pointerId && ((j = (k = e._elementToAttachTo).hasPointerCapture) === null || j === void 0 ? void 0 : j.call(k, c.pointerId)) && e._elementToAttachTo.releasePointerCapture(c.pointerId),
                e.onInputChanged(nt),
                $ !== DeviceType.Mouse) {
                    var ot = e._activeTouchIds.indexOf(c.pointerId);
                    delete e._activeTouchIds[ot],
                    e._unregisterDevice($, _e)
                }
            }
        }
        ,
        this._wheelEventName = "onwheel"in document.createElement("div") ? "wheel" : document.onmousewheel !== void 0 ? "mousewheel" : "DOMMouseScroll";
        var i = !1
          , o = function() {};
        try {
            var s = {
                passive: {
                    get: function() {
                        i = !0
                    }
                }
            };
            this._elementToAttachTo.addEventListener("test", o, s),
            this._elementToAttachTo.removeEventListener("test", o, s)
        } catch {}
        this._pointerBlurEvent = function(c) {
            var d, _, b, k, j;
            if (e.isDeviceAvailable(DeviceType.Mouse)) {
                var $ = e._inputs[DeviceType.Mouse][0];
                e._mouseId >= 0 && ((_ = (d = e._elementToAttachTo).hasPointerCapture) === null || _ === void 0 ? void 0 : _.call(d, e._mouseId)) && e._elementToAttachTo.releasePointerCapture(e._mouseId);
                for (var _e = 0; _e <= PointerInput.BrowserForward; _e++)
                    if ($[_e + 2] === 1) {
                        $[_e + 2] = 0;
                        var et = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, _e + 2, 1, e, e._elementToAttachTo)
                          , tt = et;
                        tt.deviceType = DeviceType.Mouse,
                        tt.deviceSlot = 0,
                        tt.inputIndex = _e + 2,
                        tt.currentState = $[_e + 2],
                        tt.previousState = 1,
                        e.onInputChanged(tt)
                    }
            }
            if (e.isDeviceAvailable(DeviceType.Touch)) {
                var $ = e._inputs[DeviceType.Touch];
                for (var rt in Object.keys(e._activeTouchIds)) {
                    var it = +rt
                      , nt = e._activeTouchIds[it];
                    if (!((k = (b = e._elementToAttachTo).hasPointerCapture) === null || k === void 0) && k.call(b, nt) && e._elementToAttachTo.releasePointerCapture(nt),
                    ((j = $[it]) === null || j === void 0 ? void 0 : j[PointerInput.LeftClick]) === 1) {
                        $[it][PointerInput.LeftClick] = 0;
                        var ot = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, nt, PointerInput.LeftClick, 1, e, e._elementToAttachTo)
                          , tt = ot;
                        tt.deviceType = DeviceType.Mouse,
                        tt.deviceSlot = it,
                        tt.inputIndex = PointerInput.LeftClick,
                        tt.currentState = $[it][PointerInput.LeftClick],
                        tt.previousState = 1,
                        e.onInputChanged(tt),
                        e._unregisterDevice(DeviceType.Touch, it)
                    }
                }
                for (; e._activeTouchIds.pop() !== void 0; )
                    ;
            }
        }
        ,
        this._pointerWheelEvent = function(c) {
            var d = DeviceType.Mouse
              , _ = 0;
            e._inputs[d] || (e._inputs[d] = []),
            e._inputs[d][_] || (e._pointerActive = !0,
            e._registerDevice(d, _, a.MAX_POINTER_INPUTS));
            var b = e._inputs[d][_];
            if (b) {
                var k = b[PointerInput.MouseWheelX]
                  , j = b[PointerInput.MouseWheelY]
                  , $ = b[PointerInput.MouseWheelZ];
                b[PointerInput.MouseWheelX] = c.deltaX || 0,
                b[PointerInput.MouseWheelY] = c.deltaY || c.wheelDelta || 0,
                b[PointerInput.MouseWheelZ] = c.deltaZ || 0;
                var _e = c;
                _e.deviceType = d,
                _e.deviceSlot = _,
                b[PointerInput.MouseWheelX] !== 0 && (_e.inputIndex = PointerInput.MouseWheelX,
                _e.previousState = k,
                _e.currentState = b[PointerInput.MouseWheelX],
                e.onInputChanged(_e)),
                b[PointerInput.MouseWheelY] !== 0 && (_e.inputIndex = PointerInput.MouseWheelY,
                _e.previousState = j,
                _e.currentState = b[PointerInput.MouseWheelY],
                e.onInputChanged(_e)),
                b[PointerInput.MouseWheelZ] !== 0 && (_e.inputIndex = PointerInput.MouseWheelZ,
                _e.previousState = $,
                _e.currentState = b[PointerInput.MouseWheelZ],
                e.onInputChanged(_e))
            }
        }
        ,
        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, i ? {
            passive: !1
        } : !1),
        this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(function() {
            if (e.isDeviceAvailable(DeviceType.Mouse)) {
                var c = e._inputs[DeviceType.Mouse][0];
                c[PointerInput.MouseWheelX] = 0,
                c[PointerInput.MouseWheelY] = 0,
                c[PointerInput.MouseWheelZ] = 0,
                c[PointerInput.DeltaHorizontal] = 0,
                c[PointerInput.DeltaVertical] = 0
            }
        })
    }
    ,
    a.prototype._handleGamepadActions = function() {
        var e = this;
        this._gamepadConnectedEvent = function(i) {
            e._addGamePad(i.gamepad)
        }
        ,
        this._gamepadDisconnectedEvent = function(i) {
            if (e._gamepads) {
                var o = e._getGamepadDeviceType(i.gamepad.id)
                  , s = i.gamepad.index;
                e._unregisterDevice(o, s),
                delete e._gamepads[s]
            }
        }
        ,
        window.addEventListener("gamepadconnected", this._gamepadConnectedEvent),
        window.addEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent)
    }
    ,
    a.prototype._updateDevice = function(e, i, o) {
        var s = navigator.getGamepads()[i];
        if (s && e === this._gamepads[i]) {
            var c = this._inputs[e][i];
            o >= s.buttons.length ? c[o] = s.axes[o - s.buttons.length].valueOf() : c[o] = s.buttons[o].value
        }
    }
    ,
    a.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
    }
    ,
    a.prototype._getPointerType = function(e) {
        var i = DeviceType.Mouse;
        return (e.pointerType === "touch" || e.pointerType === "pen" || e.touches) && (i = DeviceType.Touch),
        i
    }
    ,
    a.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))
    }
    ,
    a.MAX_KEYCODES = 255,
    a.MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2,
    a
}()
  , DeviceInputSystem = function() {
    function a(e) {
        var i = this;
        this._deviceInputSystem = e,
        this.onDeviceConnectedObservable = new Observable,
        this.onDeviceDisconnectedObservable = new Observable,
        this.onInputChangedObservable = new Observable,
        this._deviceInputSystem.onDeviceConnected = function(o, s) {
            i.onDeviceConnectedObservable.notifyObservers({
                deviceType: o,
                deviceSlot: s
            })
        }
        ,
        this._deviceInputSystem.onDeviceDisconnected = function(o, s) {
            i.onDeviceDisconnectedObservable.notifyObservers({
                deviceType: o,
                deviceSlot: s
            })
        }
        ,
        this._deviceInputSystem.onInputChanged = function(o) {
            i.onInputChangedObservable.notifyObservers(o)
        }
    }
    return a._Create = function(e) {
        if (!e.deviceInputSystem) {
            var i = void 0;
            typeof _native != "undefined" ? i = _native.DeviceInputSystem ? new NativeDeviceInputSystemImpl(new _native.DeviceInputSystem) : new NativeDeviceInputSystemImpl : i = new WebDeviceInputSystemImpl(e),
            i && (e.deviceInputSystem = new a(i))
        }
        return e.deviceInputSystem
    }
    ,
    a.prototype.configureEvents = function() {
        this._deviceInputSystem.configureEvents()
    }
    ,
    a.prototype.pollInput = function(e, i, o) {
        return this._deviceInputSystem.pollInput(e, i, o)
    }
    ,
    a.prototype.isDeviceAvailable = function(e) {
        return this._deviceInputSystem.isDeviceAvailable(e)
    }
    ,
    a.prototype.dispose = function() {
        this.onDeviceConnectedObservable.clear(),
        this.onDeviceDisconnectedObservable.clear(),
        this.onInputChangedObservable.clear(),
        this._deviceInputSystem.dispose()
    }
    ,
    a
}()
  , _ClickInfo = function() {
    function a() {
        this._singleClick = !1,
        this._doubleClick = !1,
        this._hasSwiped = !1,
        this._ignore = !1
    }
    return Object.defineProperty(a.prototype, "singleClick", {
        get: function() {
            return this._singleClick
        },
        set: function(e) {
            this._singleClick = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "doubleClick", {
        get: function() {
            return this._doubleClick
        },
        set: function(e) {
            this._doubleClick = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasSwiped", {
        get: function() {
            return this._hasSwiped
        },
        set: function(e) {
            this._hasSwiped = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "ignore", {
        get: function() {
            return this._ignore
        },
        set: function(e) {
            this._ignore = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a
}()
  , InputManager = function() {
    function a(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(a.prototype, "meshUnderPointer", {
        get: function() {
            return this._pointerOverMesh
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getMeshUnderPointerByPointerId = function(e) {
        return this._meshUnderPointerId[e] || null
    }
    ,
    Object.defineProperty(a.prototype, "unTranslatedPointer", {
        get: function() {
            return new Vector2(this._unTranslatedPointerX,this._unTranslatedPointerY)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "pointerX", {
        get: function() {
            return this._pointerX
        },
        set: function(e) {
            this._pointerX = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "pointerY", {
        get: function() {
            return this._pointerY
        },
        set: function(e) {
            this._pointerY = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._updatePointerPosition = function(e) {
        var i = this._scene.getEngine().getInputElementClientRect();
        !i || (this._pointerX = e.clientX - i.left,
        this._pointerY = e.clientY - i.top,
        this._unTranslatedPointerX = this._pointerX,
        this._unTranslatedPointerY = this._pointerY)
    }
    ,
    a.prototype._processPointerMove = function(e, i) {
        var o = this._scene
          , s = o.getEngine()
          , c = s.getInputElement();
        c && (c.tabIndex = s.canvasTabIndex,
        o.doNotHandleCursors || (c.style.cursor = o.defaultCursor));
        var d = !!(e && e.hit && e.pickedMesh);
        d ? (o.setPointerOverMesh(e.pickedMesh, i.pointerId, e),
        this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers && !o.doNotHandleCursors && c && (this._pointerOverMesh.actionManager.hoverCursor ? c.style.cursor = this._pointerOverMesh.actionManager.hoverCursor : c.style.cursor = o.hoverCursor)) : o.setPointerOverMesh(null, i.pointerId, e);
        for (var _ = 0, b = o._pointerMoveStage; _ < b.length; _++) {
            var k = b[_];
            e = k.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, d, c)
        }
        if (e) {
            var j = i.type === "wheel" || i.type === "mousewheel" || i.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
            if (o.onPointerMove && o.onPointerMove(i, e, j),
            o.onPointerObservable.hasObservers()) {
                var $ = new PointerInfo(j,i,e);
                this._setRayOnPointerInfo($),
                o.onPointerObservable.notifyObservers($, j)
            }
        }
    }
    ,
    a.prototype._setRayOnPointerInfo = function(e) {
        var i = this._scene;
        e.pickInfo && !e.pickInfo._pickingUnavailable && (e.pickInfo.ray || (e.pickInfo.ray = i.createPickingRay(e.event.offsetX, e.event.offsetY, Matrix.Identity(), i.activeCamera)))
    }
    ,
    a.prototype._checkPrePointerObservable = function(e, i, o) {
        var s = this._scene
          , c = new PointerInfoPre(o,i,this._unTranslatedPointerX,this._unTranslatedPointerY);
        return e && (c.ray = e.ray,
        e.originMesh && (c.nearInteractionPickingInfo = e)),
        s.onPrePointerObservable.notifyObservers(c, o),
        !!c.skipOnPointerObservable
    }
    ,
    a.prototype.simulatePointerMove = function(e, i) {
        var o = new PointerEvent("pointermove",i);
        this._checkPrePointerObservable(e, o, PointerEventTypes.POINTERMOVE) || this._processPointerMove(e, o)
    }
    ,
    a.prototype.simulatePointerDown = function(e, i) {
        var o = new PointerEvent("pointerdown",i);
        this._checkPrePointerObservable(e, o, PointerEventTypes.POINTERDOWN) || this._processPointerDown(e, o)
    }
    ,
    a.prototype._processPointerDown = function(e, i) {
        var o = this
          , s = this._scene;
        if (e && e.hit && e.pickedMesh) {
            this._pickedDownMesh = e.pickedMesh;
            var c = e.pickedMesh._getActionManagerForTrigger();
            if (c) {
                if (c.hasPickTriggers)
                    switch (c.processTrigger(5, ActionEvent.CreateNew(e.pickedMesh, i)),
                    i.button) {
                    case 0:
                        c.processTrigger(2, ActionEvent.CreateNew(e.pickedMesh, i));
                        break;
                    case 1:
                        c.processTrigger(4, ActionEvent.CreateNew(e.pickedMesh, i));
                        break;
                    case 2:
                        c.processTrigger(3, ActionEvent.CreateNew(e.pickedMesh, i));
                        break
                    }
                c.hasSpecificTrigger(8) && window.setTimeout(function() {
                    var $ = s.pick(o._unTranslatedPointerX, o._unTranslatedPointerY, function(_e) {
                        return _e.isPickable && _e.isVisible && _e.isReady() && _e.actionManager && _e.actionManager.hasSpecificTrigger(8) && _e === o._pickedDownMesh
                    }, !1, s.cameraToUseForPointers);
                    $ && $.hit && $.pickedMesh && c && o._totalPointersPressed !== 0 && Date.now() - o._startingPointerTime > a.LongPressDelay && !o._isPointerSwiping() && (o._startingPointerTime = 0,
                    c.processTrigger(8, ActionEvent.CreateNew($.pickedMesh, i)))
                }, a.LongPressDelay)
            }
        } else
            for (var d = 0, _ = s._pointerDownStage; d < _.length; d++) {
                var b = _[d];
                e = b.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, i)
            }
        if (e) {
            var k = PointerEventTypes.POINTERDOWN;
            if (s.onPointerDown && s.onPointerDown(i, e, k),
            s.onPointerObservable.hasObservers()) {
                var j = new PointerInfo(k,i,e);
                this._setRayOnPointerInfo(j),
                s.onPointerObservable.notifyObservers(j, k)
            }
        }
    }
    ,
    a.prototype._isPointerSwiping = function() {
        return Math.abs(this._startingPointerPosition.x - this._pointerX) > a.DragMovementThreshold || Math.abs(this._startingPointerPosition.y - this._pointerY) > a.DragMovementThreshold
    }
    ,
    a.prototype.simulatePointerUp = function(e, i, o) {
        var s = new PointerEvent("pointerup",i)
          , c = new _ClickInfo;
        o ? c.doubleClick = !0 : c.singleClick = !0,
        !this._checkPrePointerObservable(e, s, PointerEventTypes.POINTERUP) && this._processPointerUp(e, s, c)
    }
    ,
    a.prototype._processPointerUp = function(e, i, o) {
        var s = this._scene;
        if (e && e && e.pickedMesh) {
            if (this._pickedUpMesh = e.pickedMesh,
            this._pickedDownMesh === this._pickedUpMesh && (s.onPointerPick && s.onPointerPick(i, e),
            o.singleClick && !o.ignore && s.onPointerObservable.hasObservers())) {
                var c = PointerEventTypes.POINTERPICK
                  , d = new PointerInfo(c,i,e);
                this._setRayOnPointerInfo(d),
                s.onPointerObservable.notifyObservers(d, c)
            }
            var _ = e.pickedMesh._getActionManagerForTrigger();
            if (_ && !o.ignore) {
                _.processTrigger(7, ActionEvent.CreateNew(e.pickedMesh, i, e)),
                !o.hasSwiped && o.singleClick && _.processTrigger(1, ActionEvent.CreateNew(e.pickedMesh, i, e));
                var b = e.pickedMesh._getActionManagerForTrigger(6);
                o.doubleClick && b && b.processTrigger(6, ActionEvent.CreateNew(e.pickedMesh, i, e))
            }
        } else if (!o.ignore)
            for (var k = 0, j = s._pointerUpStage; k < j.length; k++) {
                var $ = j[k];
                e = $.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, i)
            }
        if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) {
            var _e = this._pickedDownMesh._getActionManagerForTrigger(16);
            _e && _e.processTrigger(16, ActionEvent.CreateNew(this._pickedDownMesh, i))
        }
        var et = 0;
        if (s.onPointerObservable.hasObservers()) {
            if (!o.ignore && !o.hasSwiped && (o.singleClick && s.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP) ? et = PointerEventTypes.POINTERTAP : o.doubleClick && s.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && (et = PointerEventTypes.POINTERDOUBLETAP),
            et)) {
                var d = new PointerInfo(et,i,e);
                this._setRayOnPointerInfo(d),
                s.onPointerObservable.notifyObservers(d, et)
            }
            if (!o.ignore) {
                et = PointerEventTypes.POINTERUP;
                var d = new PointerInfo(et,i,e);
                this._setRayOnPointerInfo(d),
                s.onPointerObservable.notifyObservers(d, et)
            }
        }
        s.onPointerUp && !o.ignore && s.onPointerUp(i, e, et)
    }
    ,
    a.prototype.isPointerCaptured = function(e) {
        return e === void 0 && (e = 0),
        this._pointerCaptures[e]
    }
    ,
    a.prototype.attachControl = function(e, i, o, s) {
        var c = this;
        e === void 0 && (e = !0),
        i === void 0 && (i = !0),
        o === void 0 && (o = !0),
        s === void 0 && (s = null);
        var d = this._scene
          , _ = d.getEngine();
        s || (s = _.getInputElement()),
        this._alreadyAttached && this.detachControl(),
        s && (this._alreadyAttachedTo = s),
        this._deviceInputSystem ? this._deviceInputSystem.configureEvents() : this._deviceInputSystem = DeviceInputSystem._Create(_),
        this._initActionManager = function(b, k) {
            if (!c._meshPickProceed) {
                var j = d.pick(c._unTranslatedPointerX, c._unTranslatedPointerY, d.pointerDownPredicate, !1, d.cameraToUseForPointers);
                c._currentPickResult = j,
                j && (b = j.hit && j.pickedMesh ? j.pickedMesh._getActionManagerForTrigger() : null),
                c._meshPickProceed = !0
            }
            return b
        }
        ,
        this._delayedSimpleClick = function(b, k, j) {
            (Date.now() - c._previousStartingPointerTime > a.DoubleClickDelay && !c._doubleClickOccured || b !== c._previousButtonPressed) && (c._doubleClickOccured = !1,
            k.singleClick = !0,
            k.ignore = !1,
            j(k, c._currentPickResult))
        }
        ,
        this._initClickEvent = function(b, k, j, $) {
            var _e = new _ClickInfo;
            c._currentPickResult = null;
            var et = null
              , tt = b.hasSpecificMask(PointerEventTypes.POINTERPICK) || k.hasSpecificMask(PointerEventTypes.POINTERPICK) || b.hasSpecificMask(PointerEventTypes.POINTERTAP) || k.hasSpecificMask(PointerEventTypes.POINTERTAP) || b.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || k.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
            !tt && AbstractActionManager && (et = c._initActionManager(et, _e),
            et && (tt = et.hasPickTriggers));
            var rt = !1;
            if (tt) {
                var it = j.button;
                if (_e.hasSwiped = c._isPointerSwiping(),
                !_e.hasSwiped) {
                    var nt = !a.ExclusiveDoubleClickMode;
                    nt || (nt = !b.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && !k.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP),
                    nt && !AbstractActionManager.HasSpecificTrigger(6) && (et = c._initActionManager(et, _e),
                    et && (nt = !et.hasSpecificTrigger(6)))),
                    nt ? (Date.now() - c._previousStartingPointerTime > a.DoubleClickDelay || it !== c._previousButtonPressed) && (_e.singleClick = !0,
                    $(_e, c._currentPickResult),
                    rt = !0) : (c._previousDelayedSimpleClickTimeout = c._delayedSimpleClickTimeout,
                    c._delayedSimpleClickTimeout = window.setTimeout(c._delayedSimpleClick.bind(c, it, _e, $), a.DoubleClickDelay));
                    var ot = b.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || k.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
                    !ot && AbstractActionManager.HasSpecificTrigger(6) && (et = c._initActionManager(et, _e),
                    et && (ot = et.hasSpecificTrigger(6))),
                    ot && (it === c._previousButtonPressed && Date.now() - c._previousStartingPointerTime < a.DoubleClickDelay && !c._doubleClickOccured ? (!_e.hasSwiped && !c._isPointerSwiping() ? (c._previousStartingPointerTime = 0,
                    c._doubleClickOccured = !0,
                    _e.doubleClick = !0,
                    _e.ignore = !1,
                    a.ExclusiveDoubleClickMode && c._previousDelayedSimpleClickTimeout && clearTimeout(c._previousDelayedSimpleClickTimeout),
                    c._previousDelayedSimpleClickTimeout = c._delayedSimpleClickTimeout,
                    $(_e, c._currentPickResult)) : (c._doubleClickOccured = !1,
                    c._previousStartingPointerTime = c._startingPointerTime,
                    c._previousStartingPointerPosition.x = c._startingPointerPosition.x,
                    c._previousStartingPointerPosition.y = c._startingPointerPosition.y,
                    c._previousButtonPressed = it,
                    a.ExclusiveDoubleClickMode ? (c._previousDelayedSimpleClickTimeout && clearTimeout(c._previousDelayedSimpleClickTimeout),
                    c._previousDelayedSimpleClickTimeout = c._delayedSimpleClickTimeout,
                    $(_e, c._previousPickResult)) : $(_e, c._currentPickResult)),
                    rt = !0) : (c._doubleClickOccured = !1,
                    c._previousStartingPointerTime = c._startingPointerTime,
                    c._previousStartingPointerPosition.x = c._startingPointerPosition.x,
                    c._previousStartingPointerPosition.y = c._startingPointerPosition.y,
                    c._previousButtonPressed = it))
                }
            }
            rt || $(_e, c._currentPickResult)
        }
        ,
        this._onPointerMove = function(b) {
            if (b.pointerId === void 0 && (b.pointerId = 0),
            c._updatePointerPosition(b),
            !c._checkPrePointerObservable(null, b, b.type === "wheel" || b.type === "mousewheel" || b.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE) && !(!d.cameraToUseForPointers && !d.activeCamera)) {
                if (d.skipPointerMovePicking) {
                    c._processPointerMove(new PickingInfo, b);
                    return
                }
                d.pointerMovePredicate || (d.pointerMovePredicate = function(j) {
                    return j.isPickable && j.isVisible && j.isReady() && j.isEnabled() && (j.enablePointerMoveEvents || d.constantlyUpdateMeshUnderPointer || j._getActionManagerForTrigger() !== null) && (!d.cameraToUseForPointers || (d.cameraToUseForPointers.layerMask & j.layerMask) !== 0)
                }
                );
                var k = d.pick(c._unTranslatedPointerX, c._unTranslatedPointerY, d.pointerMovePredicate, !1, d.cameraToUseForPointers, d.pointerMoveTrianglePredicate);
                c._processPointerMove(k, b)
            }
        }
        ,
        this._onPointerDown = function(b) {
            if (c._totalPointersPressed++,
            c._pickedDownMesh = null,
            c._meshPickProceed = !1,
            b.pointerId === void 0 && (b.pointerId = 0),
            c._updatePointerPosition(b),
            d.preventDefaultOnPointerDown && s && (b.preventDefault(),
            s.focus()),
            c._startingPointerPosition.x = c._pointerX,
            c._startingPointerPosition.y = c._pointerY,
            c._startingPointerTime = Date.now(),
            !c._checkPrePointerObservable(null, b, PointerEventTypes.POINTERDOWN) && !(!d.cameraToUseForPointers && !d.activeCamera)) {
                c._pointerCaptures[b.pointerId] = !0,
                d.pointerDownPredicate || (d.pointerDownPredicate = function(j) {
                    return j.isPickable && j.isVisible && j.isReady() && j.isEnabled() && (!d.cameraToUseForPointers || (d.cameraToUseForPointers.layerMask & j.layerMask) !== 0)
                }
                ),
                c._pickedDownMesh = null;
                var k = d.pick(c._unTranslatedPointerX, c._unTranslatedPointerY, d.pointerDownPredicate, !1, d.cameraToUseForPointers);
                c._processPointerDown(k, b)
            }
        }
        ,
        this._onPointerUp = function(b) {
            c._totalPointersPressed !== 0 && (c._totalPointersPressed--,
            c._pickedUpMesh = null,
            c._meshPickProceed = !1,
            b.pointerId === void 0 && (b.pointerId = 0),
            c._updatePointerPosition(b),
            d.preventDefaultOnPointerUp && s && (b.preventDefault(),
            s.focus()),
            c._initClickEvent(d.onPrePointerObservable, d.onPointerObservable, b, function(k, j) {
                d.onPrePointerObservable.hasObservers() && !k.ignore && (!k.hasSwiped && (k.singleClick && d.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP) && c._checkPrePointerObservable(null, b, PointerEventTypes.POINTERTAP) || k.doubleClick && d.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && c._checkPrePointerObservable(null, b, PointerEventTypes.POINTERDOUBLETAP)) || c._checkPrePointerObservable(null, b, PointerEventTypes.POINTERUP)) || !c._pointerCaptures[b.pointerId] && b.buttons > 0 || (c._pointerCaptures[b.pointerId] = !1,
                !(!d.cameraToUseForPointers && !d.activeCamera) && (d.pointerUpPredicate || (d.pointerUpPredicate = function($) {
                    return $.isPickable && $.isVisible && $.isReady() && $.isEnabled() && (!d.cameraToUseForPointers || (d.cameraToUseForPointers.layerMask & $.layerMask) !== 0)
                }
                ),
                !c._meshPickProceed && (AbstractActionManager && AbstractActionManager.HasTriggers || d.onPointerObservable.hasObservers()) && c._initActionManager(null, k),
                j || (j = c._currentPickResult),
                c._processPointerUp(j, b, k),
                c._previousPickResult = c._currentPickResult))
            }))
        }
        ,
        this._onKeyDown = function(b) {
            var k = KeyboardEventTypes.KEYDOWN;
            if (d.onPreKeyboardObservable.hasObservers()) {
                var j = new KeyboardInfoPre(k,b);
                if (d.onPreKeyboardObservable.notifyObservers(j, k),
                j.skipOnPointerObservable)
                    return
            }
            if (d.onKeyboardObservable.hasObservers()) {
                var j = new KeyboardInfo(k,b);
                d.onKeyboardObservable.notifyObservers(j, k)
            }
            d.actionManager && d.actionManager.processTrigger(14, ActionEvent.CreateNewFromScene(d, b))
        }
        ,
        this._onKeyUp = function(b) {
            var k = KeyboardEventTypes.KEYUP;
            if (d.onPreKeyboardObservable.hasObservers()) {
                var j = new KeyboardInfoPre(k,b);
                if (d.onPreKeyboardObservable.notifyObservers(j, k),
                j.skipOnPointerObservable)
                    return
            }
            if (d.onKeyboardObservable.hasObservers()) {
                var j = new KeyboardInfo(k,b);
                d.onKeyboardObservable.notifyObservers(j, k)
            }
            d.actionManager && d.actionManager.processTrigger(15, ActionEvent.CreateNewFromScene(d, b))
        }
        ,
        this._onInputObserver = this._deviceInputSystem.onInputChangedObservable.add(function(b) {
            var k = b;
            b.deviceType === DeviceType.Keyboard && (b.currentState === 1 && c._onKeyDown(k),
            b.currentState === 0 && c._onKeyUp(k)),
            (b.deviceType === DeviceType.Mouse || b.deviceType === DeviceType.Touch) && (i && b.inputIndex >= PointerInput.LeftClick && b.inputIndex <= PointerInput.RightClick && b.currentState === 1 && c._onPointerDown(k),
            e && b.inputIndex >= PointerInput.LeftClick && b.inputIndex <= PointerInput.RightClick && b.currentState === 0 && c._onPointerUp(k),
            o && (b.inputIndex === PointerInput.Horizontal || b.inputIndex === PointerInput.Vertical || b.inputIndex === PointerInput.DeltaHorizontal || b.inputIndex === PointerInput.DeltaVertical || b.inputIndex === PointerInput.MouseWheelX || b.inputIndex === PointerInput.MouseWheelY || b.inputIndex === PointerInput.MouseWheelZ) && c._onPointerMove(k))
        }),
        this._alreadyAttached = !0
    }
    ,
    a.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)
    }
    ,
    a.prototype.setPointerOverMesh = function(e, i, o) {
        if (i === void 0 && (i = 0),
        this._meshUnderPointerId[i] !== e) {
            var s = this._meshUnderPointerId[i], c;
            s && (c = s._getActionManagerForTrigger(10),
            c && c.processTrigger(10, ActionEvent.CreateNew(s, void 0, {
                pointerId: i
            }))),
            e ? (this._meshUnderPointerId[i] = e,
            this._pointerOverMesh = e,
            c = e._getActionManagerForTrigger(9),
            c && c.processTrigger(9, ActionEvent.CreateNew(e, void 0, {
                pointerId: i,
                pickResult: o
            }))) : (delete this._meshUnderPointerId[i],
            this._pointerOverMesh = null)
        }
    }
    ,
    a.prototype.getPointerOverMesh = function() {
        return this._pointerOverMesh
    }
    ,
    a.prototype._invalidateMesh = function(e) {
        this._pointerOverMesh === e && (this._pointerOverMesh = null),
        this._pickedDownMesh === e && (this._pickedDownMesh = null),
        this._pickedUpMesh === e && (this._pickedUpMesh = null);
        for (var i in this._meshUnderPointerId)
            this._meshUnderPointerId[i] === e && delete this._meshUnderPointerId[i]
    }
    ,
    a.DragMovementThreshold = 10,
    a.LongPressDelay = 500,
    a.DoubleClickDelay = 300,
    a.ExclusiveDoubleClickMode = !1,
    a
}()
  , UniqueIdGenerator = function() {
    function a() {}
    return Object.defineProperty(a, "UniqueId", {
        get: function() {
            var e = this._UniqueIdCounter;
            return this._UniqueIdCounter++,
            e
        },
        enumerable: !1,
        configurable: !0
    }),
    a._UniqueIdCounter = 0,
    a
}()
  , LightConstants = function() {
    function a() {}
    return a.CompareLightsPriority = function(e, i) {
        return e.shadowEnabled !== i.shadowEnabled ? (i.shadowEnabled ? 1 : 0) - (e.shadowEnabled ? 1 : 0) : i.renderPriority - e.renderPriority
    }
    ,
    a.FALLOFF_DEFAULT = 0,
    a.FALLOFF_PHYSICAL = 1,
    a.FALLOFF_GLTF = 2,
    a.FALLOFF_STANDARD = 3,
    a.LIGHTMAP_DEFAULT = 0,
    a.LIGHTMAP_SPECULAR = 1,
    a.LIGHTMAP_SHADOWSONLY = 2,
    a.INTENSITYMODE_AUTOMATIC = 0,
    a.INTENSITYMODE_LUMINOUSPOWER = 1,
    a.INTENSITYMODE_LUMINOUSINTENSITY = 2,
    a.INTENSITYMODE_ILLUMINANCE = 3,
    a.INTENSITYMODE_LUMINANCE = 4,
    a.LIGHTTYPEID_POINTLIGHT = 0,
    a.LIGHTTYPEID_DIRECTIONALLIGHT = 1,
    a.LIGHTTYPEID_SPOTLIGHT = 2,
    a.LIGHTTYPEID_HEMISPHERICLIGHT = 3,
    a
}()
  , ComputePressureObserverWrapper = function() {
    function a(e, i) {
        a.IsAvailable && (this._observer = new window.ComputePressureObserver(e,i))
    }
    return Object.defineProperty(a, "IsAvailable", {
        get: function() {
            return IsWindowObjectExist() && "ComputePressureObserver"in window
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.observe = function() {
        var e, i;
        !((e = this._observer) === null || e === void 0) && e.observe && ((i = this._observer) === null || i === void 0 || i.observe())
    }
    ,
    a.prototype.unobserve = function() {
        var e, i;
        !((e = this._observer) === null || e === void 0) && e.unobserve && ((i = this._observer) === null || i === void 0 || i.unobserve())
    }
    ,
    a
}()
  , _injectLTSScene = function(a) {
    a.prototype.setActiveCameraByID = function(e) {
        return this.setActiveCameraById(e)
    }
    ,
    a.prototype.getLastMaterialByID = function(e) {
        return this.getLastMaterialById(e)
    }
    ,
    a.prototype.getMaterialByID = function(e) {
        return this.getMaterialById(e)
    }
    ,
    a.prototype.getTextureByUniqueID = function(e) {
        return this.getTextureByUniqueId(e)
    }
    ,
    a.prototype.getCameraByID = function(e) {
        return this.getCameraById(e)
    }
    ,
    a.prototype.getCameraByUniqueID = function(e) {
        return this.getCameraByUniqueId(e)
    }
    ,
    a.prototype.getBoneByID = function(e) {
        return this.getBoneById(e)
    }
    ,
    a.prototype.getLightByID = function(e) {
        return this.getLightById(e)
    }
    ,
    a.prototype.getLightByUniqueID = function(e) {
        return this.getLightByUniqueId(e)
    }
    ,
    a.prototype.getParticleSystemByID = function(e) {
        return this.getParticleSystemById(e)
    }
    ,
    a.prototype.getGeometryByID = function(e) {
        return this.getGeometryById(e)
    }
    ,
    a.prototype.getMeshByID = function(e) {
        return this.getMeshById(e)
    }
    ,
    a.prototype.getMeshesByID = function(e) {
        return this.getMeshesById(e)
    }
    ,
    a.prototype.getTransformNodeByID = function(e) {
        return this.getTransformNodeById(e)
    }
    ,
    a.prototype.getTransformNodeByUniqueID = function(e) {
        return this.getTransformNodeByUniqueId(e)
    }
    ,
    a.prototype.getTransformNodesByID = function(e) {
        return this.getTransformNodesById(e)
    }
    ,
    a.prototype.getMeshByUniqueID = function(e) {
        return this.getMeshByUniqueId(e)
    }
    ,
    a.prototype.getLastMeshByID = function(e) {
        return this.getLastMeshById(e)
    }
    ,
    a.prototype.getLastEntryByID = function(e) {
        return this.getLastEntryById(e)
    }
    ,
    a.prototype.getNodeByID = function(e) {
        return this.getNodeById(e)
    }
    ,
    a.prototype.getLastSkeletonByID = function(e) {
        return this.getLastSkeletonById(e)
    }
}
  , Scene = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this) || this;
        s._inputManager = new InputManager(s),
        s.cameraToUseForPointers = null,
        s._isScene = !0,
        s._blockEntityCollection = !1,
        s.autoClear = !0,
        s.autoClearDepthAndStencil = !0,
        s.clearColor = new Color4(.2,.2,.3,1),
        s.ambientColor = new Color3(0,0,0),
        s._environmentIntensity = 1,
        s._forceWireframe = !1,
        s._skipFrustumClipping = !1,
        s._forcePointsCloud = !1,
        s.animationsEnabled = !0,
        s._animationPropertiesOverride = null,
        s.useConstantAnimationDeltaTime = !1,
        s.constantlyUpdateMeshUnderPointer = !1,
        s.hoverCursor = "pointer",
        s.defaultCursor = "",
        s.doNotHandleCursors = !1,
        s.preventDefaultOnPointerDown = !0,
        s.preventDefaultOnPointerUp = !0,
        s.metadata = null,
        s.reservedDataStore = null,
        s.disableOfflineSupportExceptionRules = new Array,
        s.onDisposeObservable = new Observable,
        s._onDisposeObserver = null,
        s.onBeforeRenderObservable = new Observable,
        s._onBeforeRenderObserver = null,
        s.onAfterRenderObservable = new Observable,
        s.onBeforeRunRegisterBeforeRenderObservable = new Observable,
        s.onAfterRunRegisterBeforeRenderObservable = new Observable,
        s.onBeforeRunRegisterAfterRenderObservable = new Observable,
        s.onAfterRunRegisterAfterRenderObservable = new Observable,
        s.onBeforeRTT1Observable = new Observable,
        s.onAfterRTT1Observable = new Observable,
        s.onAfterRenderCameraObservable = new Observable,
        s._onAfterRenderObserver = null,
        s.onBeforeAnimationsObservable = new Observable,
        s.onAfterAnimationsObservable = new Observable,
        s.onBeforeDrawPhaseObservable = new Observable,
        s.onAfterDrawPhaseObservable = new Observable,
        s.onReadyObservable = new Observable,
        s.onBeforeCameraRenderObservable = new Observable,
        s._onBeforeCameraRenderObserver = null,
        s.onAfterCameraRenderObservable = new Observable,
        s._onAfterCameraRenderObserver = null,
        s.onBeforeActiveMeshesEvaluationObservable = new Observable,
        s.onAfterActiveMeshesEvaluationObservable = new Observable,
        s.onBeforeParticlesRenderingObservable = new Observable,
        s.onAfterParticlesRenderingObservable = new Observable,
        s.onDataLoadedObservable = new Observable,
        s.onNewCameraAddedObservable = new Observable,
        s.onCameraRemovedObservable = new Observable,
        s.onNewLightAddedObservable = new Observable,
        s.onLightRemovedObservable = new Observable,
        s.onNewGeometryAddedObservable = new Observable,
        s.onGeometryRemovedObservable = new Observable,
        s.onNewTransformNodeAddedObservable = new Observable,
        s.onTransformNodeRemovedObservable = new Observable,
        s.onNewMeshAddedObservable = new Observable,
        s.onMeshRemovedObservable = new Observable,
        s.onNewSkeletonAddedObservable = new Observable,
        s.onSkeletonRemovedObservable = new Observable,
        s.onNewMaterialAddedObservable = new Observable,
        s.onNewMultiMaterialAddedObservable = new Observable,
        s.onMaterialRemovedObservable = new Observable,
        s.onMultiMaterialRemovedObservable = new Observable,
        s.onNewTextureAddedObservable = new Observable,
        s.onTextureRemovedObservable = new Observable,
        s.onBeforeRenderTargetsRenderObservable = new Observable,
        s.onAfterRenderTargetsRenderObservable = new Observable,
        s.onBeforeStepObservable = new Observable,
        s.onAfterStepObservable = new Observable,
        s.onActiveCameraChanged = new Observable,
        s.onBeforeRenderingGroupObservable = new Observable,
        s.onAfterRenderingGroupObservable = new Observable,
        s.onMeshImportedObservable = new Observable,
        s.onAnimationFileImportedObservable = new Observable,
        s._registeredForLateAnimationBindings = new SmartArrayNoDuplicate(256),
        s.skipPointerMovePicking = !1,
        s.onPrePointerObservable = new Observable,
        s.onPointerObservable = new Observable,
        s.onPreKeyboardObservable = new Observable,
        s.onKeyboardObservable = new Observable,
        s._useRightHandedSystem = !1,
        s._timeAccumulator = 0,
        s._currentStepId = 0,
        s._currentInternalStep = 0,
        s._fogEnabled = !0,
        s._fogMode = e.FOGMODE_NONE,
        s.fogColor = new Color3(.2,.2,.3),
        s.fogDensity = .1,
        s.fogStart = 0,
        s.fogEnd = 1e3,
        s.needsPreviousWorldMatrices = !1,
        s._shadowsEnabled = !0,
        s._lightsEnabled = !0,
        s.activeCameras = new Array,
        s._texturesEnabled = !0,
        s.physicsEnabled = !0,
        s.particlesEnabled = !0,
        s.spritesEnabled = !0,
        s._skeletonsEnabled = !0,
        s.lensFlaresEnabled = !0,
        s.collisionsEnabled = !0,
        s.gravity = new Vector3(0,-9.807,0),
        s.postProcessesEnabled = !0,
        s.renderTargetsEnabled = !0,
        s.dumpNextRenderTargets = !1,
        s.customRenderTargets = new Array,
        s.importedMeshesFiles = new Array,
        s.probesEnabled = !0,
        s._meshesForIntersections = new SmartArrayNoDuplicate(256),
        s.proceduralTexturesEnabled = !0,
        s._totalVertices = new PerfCounter,
        s._activeIndices = new PerfCounter,
        s._activeParticles = new PerfCounter,
        s._activeBones = new PerfCounter,
        s._animationTime = 0,
        s.animationTimeScale = 1,
        s._renderId = 0,
        s._frameId = 0,
        s._executeWhenReadyTimeoutId = -1,
        s._intermediateRendering = !1,
        s._defaultFrameBufferCleared = !1,
        s._viewUpdateFlag = -1,
        s._projectionUpdateFlag = -1,
        s._toBeDisposed = new Array(256),
        s._activeRequests = new Array,
        s._pendingData = new Array,
        s._isDisposed = !1,
        s.dispatchAllSubMeshesOfActiveMeshes = !1,
        s._activeMeshes = new SmartArray(256),
        s._processedMaterials = new SmartArray(256),
        s._renderTargets = new SmartArrayNoDuplicate(256),
        s._activeParticleSystems = new SmartArray(256),
        s._activeSkeletons = new SmartArrayNoDuplicate(32),
        s._softwareSkinnedMeshes = new SmartArrayNoDuplicate(32),
        s._activeAnimatables = new Array,
        s._transformMatrix = Matrix.Zero(),
        s.requireLightSorting = !1,
        s._components = [],
        s._serializableComponents = [],
        s._transientComponents = [],
        s._beforeCameraUpdateStage = Stage.Create(),
        s._beforeClearStage = Stage.Create(),
        s._beforeRenderTargetClearStage = Stage.Create(),
        s._gatherRenderTargetsStage = Stage.Create(),
        s._gatherActiveCameraRenderTargetsStage = Stage.Create(),
        s._isReadyForMeshStage = Stage.Create(),
        s._beforeEvaluateActiveMeshStage = Stage.Create(),
        s._evaluateSubMeshStage = Stage.Create(),
        s._preActiveMeshStage = Stage.Create(),
        s._cameraDrawRenderTargetStage = Stage.Create(),
        s._beforeCameraDrawStage = Stage.Create(),
        s._beforeRenderTargetDrawStage = Stage.Create(),
        s._beforeRenderingGroupDrawStage = Stage.Create(),
        s._beforeRenderingMeshStage = Stage.Create(),
        s._afterRenderingMeshStage = Stage.Create(),
        s._afterRenderingGroupDrawStage = Stage.Create(),
        s._afterCameraDrawStage = Stage.Create(),
        s._afterRenderTargetDrawStage = Stage.Create(),
        s._afterRenderStage = Stage.Create(),
        s._pointerMoveStage = Stage.Create(),
        s._pointerDownStage = Stage.Create(),
        s._pointerUpStage = Stage.Create(),
        s.geometriesByUniqueId = null,
        s._defaultMeshCandidates = {
            data: [],
            length: 0
        },
        s._defaultSubMeshCandidates = {
            data: [],
            length: 0
        },
        s._preventFreeActiveMeshesAndRenderingGroups = !1,
        s._activeMeshesFrozen = !1,
        s._skipEvaluateActiveMeshesCompletely = !1,
        s._allowPostProcessClearColor = !0,
        s.getDeterministicFrameTime = function() {
            return s._engine.getTimeStep()
        }
        ,
        s._blockMaterialDirtyMechanism = !1,
        s._perfCollector = null,
        s.onComputePressureChanged = new Observable;
        var c = __assign({
            useGeometryUniqueIdsMap: !0,
            useMaterialMeshMap: !0,
            useClonedMeshMap: !0,
            virtual: !1
        }, o);
        return s._engine = i || EngineStore.LastCreatedEngine,
        c.virtual ? s._engine._virtualScenes.push(s) : (EngineStore._LastCreatedScene = s,
        s._engine.scenes.push(s)),
        s._uid = null,
        s._renderingManager = new RenderingManager(s),
        PostProcessManager && (s.postProcessManager = new PostProcessManager(s)),
        IsWindowObjectExist() && s.attachControl(),
        s._createUbo(),
        ImageProcessingConfiguration && (s._imageProcessingConfiguration = new ImageProcessingConfiguration),
        s.setDefaultCandidateProviders(),
        c.useGeometryUniqueIdsMap && (s.geometriesByUniqueId = {}),
        s.useMaterialMeshMap = c.useMaterialMeshMap,
        s.useClonedMeshMap = c.useClonedMeshMap,
        (!o || !o.virtual) && s._engine.onNewSceneAddedObservable.notifyObservers(s),
        ComputePressureObserverWrapper.IsAvailable && (s._computePressureObserver = new ComputePressureObserverWrapper(function(d) {
            s.onComputePressureChanged.notifyObservers(d)
        }
        ,{
            cpuUtilizationThresholds: [.25, .5, .75, .9],
            cpuSpeedThresholds: [.5]
        }),
        s._computePressureObserver.observe()),
        s
    }
    return e.DefaultMaterialFactory = function(i) {
        throw _WarnImport("StandardMaterial")
    }
    ,
    e.CollisionCoordinatorFactory = function() {
        throw _WarnImport("DefaultCollisionCoordinator")
    }
    ,
    Object.defineProperty(e.prototype, "environmentTexture", {
        get: function() {
            return this._environmentTexture
        },
        set: function(i) {
            this._environmentTexture !== i && (this._environmentTexture = i,
            this.markAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "environmentIntensity", {
        get: function() {
            return this._environmentIntensity
        },
        set: function(i) {
            this._environmentIntensity !== i && (this._environmentIntensity = i,
            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(i) {
            this._forceWireframe !== i && (this._forceWireframe = i,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "skipFrustumClipping", {
        get: function() {
            return this._skipFrustumClipping
        },
        set: function(i) {
            this._skipFrustumClipping !== i && (this._skipFrustumClipping = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "forcePointsCloud", {
        get: function() {
            return this._forcePointsCloud
        },
        set: function(i) {
            this._forcePointsCloud !== i && (this._forcePointsCloud = i,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "animationPropertiesOverride", {
        get: function() {
            return this._animationPropertiesOverride
        },
        set: function(i) {
            this._animationPropertiesOverride = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onDispose", {
        set: function(i) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "beforeRender", {
        set: function(i) {
            this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),
            i && (this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "afterRender", {
        set: function(i) {
            this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver),
            i && (this._onAfterRenderObserver = this.onAfterRenderObservable.add(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "beforeCameraRender", {
        set: function(i) {
            this._onBeforeCameraRenderObserver && this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),
            this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "afterCameraRender", {
        set: function(i) {
            this._onAfterCameraRenderObserver && this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),
            this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(i)
        },
        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(i) {
            InputManager.DragMovementThreshold = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "LongPressDelay", {
        get: function() {
            return InputManager.LongPressDelay
        },
        set: function(i) {
            InputManager.LongPressDelay = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "DoubleClickDelay", {
        get: function() {
            return InputManager.DoubleClickDelay
        },
        set: function(i) {
            InputManager.DoubleClickDelay = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "ExclusiveDoubleClickMode", {
        get: function() {
            return InputManager.ExclusiveDoubleClickMode
        },
        set: function(i) {
            InputManager.ExclusiveDoubleClickMode = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.bindEyePosition = function(i, o, s) {
        var c;
        o === void 0 && (o = "vEyePosition"),
        s === void 0 && (s = !1);
        var d = this._forcedViewPosition ? this._forcedViewPosition : this._mirroredCameraPosition ? this._mirroredCameraPosition : (c = this.activeCamera.globalPosition) !== null && c !== void 0 ? c : this.activeCamera.devicePosition
          , _ = this.useRightHandedSystem === (this._mirroredCameraPosition != null);
        return TmpVectors.Vector4[0].set(d.x, d.y, d.z, _ ? -1 : 1),
        i && (s ? i.setFloat3(o, TmpVectors.Vector4[0].x, TmpVectors.Vector4[0].y, TmpVectors.Vector4[0].z) : i.setVector4(o, TmpVectors.Vector4[0])),
        TmpVectors.Vector4[0]
    }
    ,
    e.prototype.finalizeSceneUbo = function() {
        var i = this.getSceneUniformBuffer()
          , o = this.bindEyePosition(null);
        return i.updateFloat4("vEyePosition", o.x, o.y, o.z, o.w),
        i.update(),
        i
    }
    ,
    Object.defineProperty(e.prototype, "useRightHandedSystem", {
        get: function() {
            return this._useRightHandedSystem
        },
        set: function(i) {
            this._useRightHandedSystem !== i && (this._useRightHandedSystem = i,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setStepId = function(i) {
        this._currentStepId = i
    }
    ,
    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(i) {
            this._fogEnabled !== i && (this._fogEnabled = i,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fogMode", {
        get: function() {
            return this._fogMode
        },
        set: function(i) {
            this._fogMode !== i && (this._fogMode = i,
            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(i) {
            this._shadowsEnabled !== i && (this._shadowsEnabled = i,
            this.markAllMaterialsAsDirty(2))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lightsEnabled", {
        get: function() {
            return this._lightsEnabled
        },
        set: function(i) {
            this._lightsEnabled !== i && (this._lightsEnabled = i,
            this.markAllMaterialsAsDirty(2))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "activeCamera", {
        get: function() {
            return this._activeCamera
        },
        set: function(i) {
            i !== this._activeCamera && (this._activeCamera = i,
            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(i) {
            this._defaultMaterial = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "texturesEnabled", {
        get: function() {
            return this._texturesEnabled
        },
        set: function(i) {
            this._texturesEnabled !== i && (this._texturesEnabled = i,
            this.markAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "skeletonsEnabled", {
        get: function() {
            return this._skeletonsEnabled
        },
        set: function(i) {
            this._skeletonsEnabled !== i && (this._skeletonsEnabled = i,
            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 i = 0, o = this._transientComponents; i < o.length; i++) {
                var s = o[i];
                s.register()
            }
            this._transientComponents = []
        }
    }
    ,
    e.prototype._addComponent = function(i) {
        this._components.push(i),
        this._transientComponents.push(i);
        var o = i;
        o.addFromContainer && o.serialize && this._serializableComponents.push(o)
    }
    ,
    e.prototype._getComponent = function(i) {
        for (var o = 0, s = this._components; o < s.length; o++) {
            var c = s[o];
            if (c.name === i)
                return c
        }
        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(i) {
        return this._defaultSubMeshCandidates.data = i.subMeshes,
        this._defaultSubMeshCandidates.length = i.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(i) {
            this._inputManager.pointerX = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "pointerY", {
        get: function() {
            return this._inputManager.pointerY
        },
        set: function(i) {
            this._inputManager.pointerY = i
        },
        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(i, o, s) {
        return s === void 0 && (s = 1),
        this._cachedEffect !== o || this._cachedMaterial !== i || this._cachedVisibility !== s
    }
    ,
    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(i, o) {
        return this._inputManager.simulatePointerMove(i, o),
        this
    }
    ,
    e.prototype.simulatePointerDown = function(i, o) {
        return this._inputManager.simulatePointerDown(i, o),
        this
    }
    ,
    e.prototype.simulatePointerUp = function(i, o, s) {
        return this._inputManager.simulatePointerUp(i, o, s),
        this
    }
    ,
    e.prototype.isPointerCaptured = function(i) {
        return i === void 0 && (i = 0),
        this._inputManager.isPointerCaptured(i)
    }
    ,
    e.prototype.attachControl = function(i, o, s) {
        i === void 0 && (i = !0),
        o === void 0 && (o = !0),
        s === void 0 && (s = !0),
        this._inputManager.attachControl(i, o, s)
    }
    ,
    e.prototype.detachControl = function() {
        this._inputManager.detachControl()
    }
    ,
    e.prototype.isReady = function(i) {
        if (i === void 0 && (i = !0),
        this._isDisposed)
            return !1;
        var o, s = this.getEngine();
        if (!s.areAllEffectsReady() || this._pendingData.length > 0)
            return !1;
        for (i && (this._processedMaterials.reset(),
        this._renderTargets.reset()),
        o = 0; o < this.meshes.length; o++) {
            var c = this.meshes[o];
            if (!!c.isEnabled() && !(!c.subMeshes || c.subMeshes.length === 0)) {
                if (!c.isReady(!0))
                    return !1;
                for (var d = c.hasThinInstances || c.getClassName() === "InstancedMesh" || c.getClassName() === "InstancedLinesMesh" || s.getCaps().instancedArrays && c.instances.length > 0, _ = 0, b = this._isReadyForMeshStage; _ < b.length; _++) {
                    var k = b[_];
                    if (!k.action(c, d))
                        return !1
                }
                if (!!i) {
                    var j = c.material || this.defaultMaterial;
                    if (j)
                        if (j._storeEffectOnSubMeshes)
                            for (var $ = 0, _e = c.subMeshes; $ < _e.length; $++) {
                                var et = _e[$]
                                  , tt = et.getMaterial();
                                tt && tt.hasRenderTargetTextures && tt.getRenderTargetTextures != null && this._processedMaterials.indexOf(tt) === -1 && (this._processedMaterials.push(tt),
                                this._renderTargets.concatWithNoDuplicate(tt.getRenderTargetTextures()))
                            }
                        else
                            j.hasRenderTargetTextures && j.getRenderTargetTextures != null && this._processedMaterials.indexOf(j) === -1 && (this._processedMaterials.push(j),
                            this._renderTargets.concatWithNoDuplicate(j.getRenderTargetTextures()))
                }
            }
        }
        if (i)
            for (o = 0; o < this._renderTargets.length; ++o) {
                var rt = this._renderTargets.data[o];
                if (!rt.isReadyForRendering())
                    return !1
            }
        for (o = 0; o < this.geometries.length; o++) {
            var it = this.geometries[o];
            if (it.delayLoadState === 2)
                return !1
        }
        if (this.activeCameras && this.activeCameras.length > 0)
            for (var nt = 0, ot = this.activeCameras; nt < ot.length; nt++) {
                var at = ot[nt];
                if (!at.isReady(!0))
                    return !1
            }
        else if (this.activeCamera && !this.activeCamera.isReady(!0))
            return !1;
        for (var st = 0, ut = this.particleSystems; st < ut.length; st++) {
            var ct = ut[st];
            if (!ct.isReady())
                return !1
        }
        return !0
    }
    ,
    e.prototype.resetCachedMaterial = function() {
        this._cachedMaterial = null,
        this._cachedEffect = null,
        this._cachedVisibility = null
    }
    ,
    e.prototype.registerBeforeRender = function(i) {
        this.onBeforeRenderObservable.add(i)
    }
    ,
    e.prototype.unregisterBeforeRender = function(i) {
        this.onBeforeRenderObservable.removeCallback(i)
    }
    ,
    e.prototype.registerAfterRender = function(i) {
        this.onAfterRenderObservable.add(i)
    }
    ,
    e.prototype.unregisterAfterRender = function(i) {
        this.onAfterRenderObservable.removeCallback(i)
    }
    ,
    e.prototype._executeOnceBeforeRender = function(i) {
        var o = this
          , s = function() {
            i(),
            setTimeout(function() {
                o.unregisterBeforeRender(s)
            })
        };
        this.registerBeforeRender(s)
    }
    ,
    e.prototype.executeOnceBeforeRender = function(i, o) {
        var s = this;
        o !== void 0 ? setTimeout(function() {
            s._executeOnceBeforeRender(i)
        }, o) : this._executeOnceBeforeRender(i)
    }
    ,
    e.prototype._addPendingData = function(i) {
        this._pendingData.push(i)
    }
    ,
    e.prototype._removePendingData = function(i) {
        var o = this.isLoading
          , s = this._pendingData.indexOf(i);
        s !== -1 && this._pendingData.splice(s, 1),
        o && !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(i, o) {
        var s = this;
        o === void 0 && (o = !1),
        this.onReadyObservable.add(i),
        this._executeWhenReadyTimeoutId === -1 && (this._executeWhenReadyTimeoutId = setTimeout(function() {
            s._checkIsReady(o)
        }, 150))
    }
    ,
    e.prototype.whenReadyAsync = function(i) {
        var o = this;
        return i === void 0 && (i = !1),
        new Promise(function(s) {
            o.executeWhenReady(function() {
                s()
            }, i)
        }
        )
    }
    ,
    e.prototype._checkIsReady = function(i) {
        var o = this;
        if (i === void 0 && (i = !1),
        this._registerTransientComponents(),
        this.isReady(i)) {
            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() {
            o._checkIsReady(i)
        }, 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(i, o, s, c) {
        this._viewUpdateFlag === i.updateFlag && this._projectionUpdateFlag === o.updateFlag || (this._viewUpdateFlag = i.updateFlag,
        this._projectionUpdateFlag = o.updateFlag,
        this._viewMatrix = i,
        this._projectionMatrix = o,
        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(s, c) : 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(i) {
        var o = new UniformBuffer(this._engine,void 0,!1,i != null ? i : "scene");
        return o.addUniform("viewProjection", 16),
        o.addUniform("view", 16),
        o.addUniform("projection", 16),
        o.addUniform("vEyePosition", 4),
        o
    }
    ,
    e.prototype.setSceneUniformBuffer = function(i) {
        this._sceneUbo = i,
        this._viewUpdateFlag = -1,
        this._projectionUpdateFlag = -1
    }
    ,
    e.prototype.getUniqueId = function() {
        return UniqueIdGenerator.UniqueId
    }
    ,
    e.prototype.addMesh = function(i, o) {
        var s = this;
        o === void 0 && (o = !1),
        !this._blockEntityCollection && (this.meshes.push(i),
        i._resyncLightSources(),
        i.parent || i._addToSceneRootNodes(),
        this.onNewMeshAddedObservable.notifyObservers(i),
        o && i.getChildMeshes().forEach(function(c) {
            s.addMesh(c)
        }))
    }
    ,
    e.prototype.removeMesh = function(i, o) {
        var s = this;
        o === void 0 && (o = !1);
        var c = this.meshes.indexOf(i);
        return c !== -1 && (this.meshes[c] = this.meshes[this.meshes.length - 1],
        this.meshes.pop(),
        i.parent || i._removeFromSceneRootNodes()),
        this._inputManager._invalidateMesh(i),
        this.onMeshRemovedObservable.notifyObservers(i),
        o && i.getChildMeshes().forEach(function(d) {
            s.removeMesh(d)
        }),
        c
    }
    ,
    e.prototype.addTransformNode = function(i) {
        this._blockEntityCollection || (i._indexInSceneTransformNodesArray = this.transformNodes.length,
        this.transformNodes.push(i),
        i.parent || i._addToSceneRootNodes(),
        this.onNewTransformNodeAddedObservable.notifyObservers(i))
    }
    ,
    e.prototype.removeTransformNode = function(i) {
        var o = i._indexInSceneTransformNodesArray;
        if (o !== -1) {
            if (o !== this.transformNodes.length - 1) {
                var s = this.transformNodes[this.transformNodes.length - 1];
                this.transformNodes[o] = s,
                s._indexInSceneTransformNodesArray = o
            }
            i._indexInSceneTransformNodesArray = -1,
            this.transformNodes.pop(),
            i.parent || i._removeFromSceneRootNodes()
        }
        return this.onTransformNodeRemovedObservable.notifyObservers(i),
        o
    }
    ,
    e.prototype.removeSkeleton = function(i) {
        var o = this.skeletons.indexOf(i);
        return o !== -1 && (this.skeletons.splice(o, 1),
        this.onSkeletonRemovedObservable.notifyObservers(i)),
        o
    }
    ,
    e.prototype.removeMorphTargetManager = function(i) {
        var o = this.morphTargetManagers.indexOf(i);
        return o !== -1 && this.morphTargetManagers.splice(o, 1),
        o
    }
    ,
    e.prototype.removeLight = function(i) {
        var o = this.lights.indexOf(i);
        if (o !== -1) {
            for (var s = 0, c = this.meshes; s < c.length; s++) {
                var d = c[s];
                d._removeLightSource(i, !1)
            }
            this.lights.splice(o, 1),
            this.sortLightsByPriority(),
            i.parent || i._removeFromSceneRootNodes()
        }
        return this.onLightRemovedObservable.notifyObservers(i),
        o
    }
    ,
    e.prototype.removeCamera = function(i) {
        var o = this.cameras.indexOf(i);
        if (o !== -1 && (this.cameras.splice(o, 1),
        i.parent || i._removeFromSceneRootNodes()),
        this.activeCameras) {
            var s = this.activeCameras.indexOf(i);
            s !== -1 && this.activeCameras.splice(s, 1)
        }
        return this.activeCamera === i && (this.cameras.length > 0 ? this.activeCamera = this.cameras[0] : this.activeCamera = null),
        this.onCameraRemovedObservable.notifyObservers(i),
        o
    }
    ,
    e.prototype.removeParticleSystem = function(i) {
        var o = this.particleSystems.indexOf(i);
        return o !== -1 && this.particleSystems.splice(o, 1),
        o
    }
    ,
    e.prototype.removeAnimation = function(i) {
        var o = this.animations.indexOf(i);
        return o !== -1 && this.animations.splice(o, 1),
        o
    }
    ,
    e.prototype.stopAnimation = function(i, o, s) {}
    ,
    e.prototype.removeAnimationGroup = function(i) {
        var o = this.animationGroups.indexOf(i);
        return o !== -1 && this.animationGroups.splice(o, 1),
        o
    }
    ,
    e.prototype.removeMultiMaterial = function(i) {
        var o = this.multiMaterials.indexOf(i);
        return o !== -1 && this.multiMaterials.splice(o, 1),
        this.onMultiMaterialRemovedObservable.notifyObservers(i),
        o
    }
    ,
    e.prototype.removeMaterial = function(i) {
        var o = i._indexInSceneMaterialArray;
        if (o !== -1 && o < this.materials.length) {
            if (o !== this.materials.length - 1) {
                var s = this.materials[this.materials.length - 1];
                this.materials[o] = s,
                s._indexInSceneMaterialArray = o
            }
            i._indexInSceneMaterialArray = -1,
            this.materials.pop()
        }
        return this.onMaterialRemovedObservable.notifyObservers(i),
        o
    }
    ,
    e.prototype.removeActionManager = function(i) {
        var o = this.actionManagers.indexOf(i);
        return o !== -1 && this.actionManagers.splice(o, 1),
        o
    }
    ,
    e.prototype.removeTexture = function(i) {
        var o = this.textures.indexOf(i);
        return o !== -1 && this.textures.splice(o, 1),
        this.onTextureRemovedObservable.notifyObservers(i),
        o
    }
    ,
    e.prototype.addLight = function(i) {
        if (!this._blockEntityCollection) {
            this.lights.push(i),
            this.sortLightsByPriority(),
            i.parent || i._addToSceneRootNodes();
            for (var o = 0, s = this.meshes; o < s.length; o++) {
                var c = s[o];
                c.lightSources.indexOf(i) === -1 && (c.lightSources.push(i),
                c._resyncLightSources())
            }
            this.onNewLightAddedObservable.notifyObservers(i)
        }
    }
    ,
    e.prototype.sortLightsByPriority = function() {
        this.requireLightSorting && this.lights.sort(LightConstants.CompareLightsPriority)
    }
    ,
    e.prototype.addCamera = function(i) {
        this._blockEntityCollection || (this.cameras.push(i),
        this.onNewCameraAddedObservable.notifyObservers(i),
        i.parent || i._addToSceneRootNodes())
    }
    ,
    e.prototype.addSkeleton = function(i) {
        this._blockEntityCollection || (this.skeletons.push(i),
        this.onNewSkeletonAddedObservable.notifyObservers(i))
    }
    ,
    e.prototype.addParticleSystem = function(i) {
        this._blockEntityCollection || this.particleSystems.push(i)
    }
    ,
    e.prototype.addAnimation = function(i) {
        this._blockEntityCollection || this.animations.push(i)
    }
    ,
    e.prototype.addAnimationGroup = function(i) {
        this._blockEntityCollection || this.animationGroups.push(i)
    }
    ,
    e.prototype.addMultiMaterial = function(i) {
        this._blockEntityCollection || (this.multiMaterials.push(i),
        this.onNewMultiMaterialAddedObservable.notifyObservers(i))
    }
    ,
    e.prototype.addMaterial = function(i) {
        this._blockEntityCollection || (i._indexInSceneMaterialArray = this.materials.length,
        this.materials.push(i),
        this.onNewMaterialAddedObservable.notifyObservers(i))
    }
    ,
    e.prototype.addMorphTargetManager = function(i) {
        this._blockEntityCollection || this.morphTargetManagers.push(i)
    }
    ,
    e.prototype.addGeometry = function(i) {
        this._blockEntityCollection || (this.geometriesByUniqueId && (this.geometriesByUniqueId[i.uniqueId] = this.geometries.length),
        this.geometries.push(i))
    }
    ,
    e.prototype.addActionManager = function(i) {
        this.actionManagers.push(i)
    }
    ,
    e.prototype.addTexture = function(i) {
        this._blockEntityCollection || (this.textures.push(i),
        this.onNewTextureAddedObservable.notifyObservers(i))
    }
    ,
    e.prototype.switchActiveCamera = function(i, o) {
        o === void 0 && (o = !0);
        var s = this._engine.getInputElement();
        !s || (this.activeCamera && this.activeCamera.detachControl(),
        this.activeCamera = i,
        o && i.attachControl())
    }
    ,
    e.prototype.setActiveCameraById = function(i) {
        var o = this.getCameraById(i);
        return o ? (this.activeCamera = o,
        o) : null
    }
    ,
    e.prototype.setActiveCameraByName = function(i) {
        var o = this.getCameraByName(i);
        return o ? (this.activeCamera = o,
        o) : null
    }
    ,
    e.prototype.getAnimationGroupByName = function(i) {
        for (var o = 0; o < this.animationGroups.length; o++)
            if (this.animationGroups[o].name === i)
                return this.animationGroups[o];
        return null
    }
    ,
    e.prototype.getMaterialByUniqueID = function(i) {
        for (var o = 0; o < this.materials.length; o++)
            if (this.materials[o].uniqueId === i)
                return this.materials[o];
        return null
    }
    ,
    e.prototype.getMaterialById = function(i) {
        for (var o = 0; o < this.materials.length; o++)
            if (this.materials[o].id === i)
                return this.materials[o];
        return null
    }
    ,
    e.prototype.getLastMaterialById = function(i) {
        for (var o = this.materials.length - 1; o >= 0; o--)
            if (this.materials[o].id === i)
                return this.materials[o];
        return null
    }
    ,
    e.prototype.getMaterialByName = function(i) {
        for (var o = 0; o < this.materials.length; o++)
            if (this.materials[o].name === i)
                return this.materials[o];
        return null
    }
    ,
    e.prototype.getTextureByUniqueId = function(i) {
        for (var o = 0; o < this.textures.length; o++)
            if (this.textures[o].uniqueId === i)
                return this.textures[o];
        return null
    }
    ,
    e.prototype.getTextureByName = function(i) {
        for (var o = 0; o < this.textures.length; o++)
            if (this.textures[o].name === i)
                return this.textures[o];
        return null
    }
    ,
    e.prototype.getCameraById = function(i) {
        for (var o = 0; o < this.cameras.length; o++)
            if (this.cameras[o].id === i)
                return this.cameras[o];
        return null
    }
    ,
    e.prototype.getCameraByUniqueId = function(i) {
        for (var o = 0; o < this.cameras.length; o++)
            if (this.cameras[o].uniqueId === i)
                return this.cameras[o];
        return null
    }
    ,
    e.prototype.getCameraByName = function(i) {
        for (var o = 0; o < this.cameras.length; o++)
            if (this.cameras[o].name === i)
                return this.cameras[o];
        return null
    }
    ,
    e.prototype.getBoneById = function(i) {
        for (var o = 0; o < this.skeletons.length; o++)
            for (var s = this.skeletons[o], c = 0; c < s.bones.length; c++)
                if (s.bones[c].id === i)
                    return s.bones[c];
        return null
    }
    ,
    e.prototype.getBoneByName = function(i) {
        for (var o = 0; o < this.skeletons.length; o++)
            for (var s = this.skeletons[o], c = 0; c < s.bones.length; c++)
                if (s.bones[c].name === i)
                    return s.bones[c];
        return null
    }
    ,
    e.prototype.getLightByName = function(i) {
        for (var o = 0; o < this.lights.length; o++)
            if (this.lights[o].name === i)
                return this.lights[o];
        return null
    }
    ,
    e.prototype.getLightById = function(i) {
        for (var o = 0; o < this.lights.length; o++)
            if (this.lights[o].id === i)
                return this.lights[o];
        return null
    }
    ,
    e.prototype.getLightByUniqueId = function(i) {
        for (var o = 0; o < this.lights.length; o++)
            if (this.lights[o].uniqueId === i)
                return this.lights[o];
        return null
    }
    ,
    e.prototype.getParticleSystemById = function(i) {
        for (var o = 0; o < this.particleSystems.length; o++)
            if (this.particleSystems[o].id === i)
                return this.particleSystems[o];
        return null
    }
    ,
    e.prototype.getGeometryById = function(i) {
        for (var o = 0; o < this.geometries.length; o++)
            if (this.geometries[o].id === i)
                return this.geometries[o];
        return null
    }
    ,
    e.prototype._getGeometryByUniqueId = function(i) {
        if (this.geometriesByUniqueId) {
            var o = this.geometriesByUniqueId[i];
            if (o !== void 0)
                return this.geometries[o]
        } else
            for (var s = 0; s < this.geometries.length; s++)
                if (this.geometries[s].uniqueId === i)
                    return this.geometries[s];
        return null
    }
    ,
    e.prototype.pushGeometry = function(i, o) {
        return !o && this._getGeometryByUniqueId(i.uniqueId) ? !1 : (this.addGeometry(i),
        this.onNewGeometryAddedObservable.notifyObservers(i),
        !0)
    }
    ,
    e.prototype.removeGeometry = function(i) {
        var o;
        if (this.geometriesByUniqueId) {
            if (o = this.geometriesByUniqueId[i.uniqueId],
            o === void 0)
                return !1
        } else if (o = this.geometries.indexOf(i),
        o < 0)
            return !1;
        if (o !== this.geometries.length - 1) {
            var s = this.geometries[this.geometries.length - 1];
            s && (this.geometries[o] = s,
            this.geometriesByUniqueId && (this.geometriesByUniqueId[s.uniqueId] = o,
            this.geometriesByUniqueId[i.uniqueId] = void 0))
        }
        return this.geometries.pop(),
        this.onGeometryRemovedObservable.notifyObservers(i),
        !0
    }
    ,
    e.prototype.getGeometries = function() {
        return this.geometries
    }
    ,
    e.prototype.getMeshById = function(i) {
        for (var o = 0; o < this.meshes.length; o++)
            if (this.meshes[o].id === i)
                return this.meshes[o];
        return null
    }
    ,
    e.prototype.getMeshesById = function(i) {
        return this.meshes.filter(function(o) {
            return o.id === i
        })
    }
    ,
    e.prototype.getTransformNodeById = function(i) {
        for (var o = 0; o < this.transformNodes.length; o++)
            if (this.transformNodes[o].id === i)
                return this.transformNodes[o];
        return null
    }
    ,
    e.prototype.getTransformNodeByUniqueId = function(i) {
        for (var o = 0; o < this.transformNodes.length; o++)
            if (this.transformNodes[o].uniqueId === i)
                return this.transformNodes[o];
        return null
    }
    ,
    e.prototype.getTransformNodesById = function(i) {
        return this.transformNodes.filter(function(o) {
            return o.id === i
        })
    }
    ,
    e.prototype.getMeshByUniqueId = function(i) {
        for (var o = 0; o < this.meshes.length; o++)
            if (this.meshes[o].uniqueId === i)
                return this.meshes[o];
        return null
    }
    ,
    e.prototype.getLastMeshById = function(i) {
        for (var o = this.meshes.length - 1; o >= 0; o--)
            if (this.meshes[o].id === i)
                return this.meshes[o];
        return null
    }
    ,
    e.prototype.getLastEntryById = function(i) {
        var o;
        for (o = this.meshes.length - 1; o >= 0; o--)
            if (this.meshes[o].id === i)
                return this.meshes[o];
        for (o = this.transformNodes.length - 1; o >= 0; o--)
            if (this.transformNodes[o].id === i)
                return this.transformNodes[o];
        for (o = this.cameras.length - 1; o >= 0; o--)
            if (this.cameras[o].id === i)
                return this.cameras[o];
        for (o = this.lights.length - 1; o >= 0; o--)
            if (this.lights[o].id === i)
                return this.lights[o];
        return null
    }
    ,
    e.prototype.getNodeById = function(i) {
        var o = this.getMeshById(i);
        if (o)
            return o;
        var s = this.getTransformNodeById(i);
        if (s)
            return s;
        var c = this.getLightById(i);
        if (c)
            return c;
        var d = this.getCameraById(i);
        if (d)
            return d;
        var _ = this.getBoneById(i);
        return _ || null
    }
    ,
    e.prototype.getNodeByName = function(i) {
        var o = this.getMeshByName(i);
        if (o)
            return o;
        var s = this.getTransformNodeByName(i);
        if (s)
            return s;
        var c = this.getLightByName(i);
        if (c)
            return c;
        var d = this.getCameraByName(i);
        if (d)
            return d;
        var _ = this.getBoneByName(i);
        return _ || null
    }
    ,
    e.prototype.getMeshByName = function(i) {
        for (var o = 0; o < this.meshes.length; o++)
            if (this.meshes[o].name === i)
                return this.meshes[o];
        return null
    }
    ,
    e.prototype.getTransformNodeByName = function(i) {
        for (var o = 0; o < this.transformNodes.length; o++)
            if (this.transformNodes[o].name === i)
                return this.transformNodes[o];
        return null
    }
    ,
    e.prototype.getLastSkeletonById = function(i) {
        for (var o = this.skeletons.length - 1; o >= 0; o--)
            if (this.skeletons[o].id === i)
                return this.skeletons[o];
        return null
    }
    ,
    e.prototype.getSkeletonByUniqueId = function(i) {
        for (var o = 0; o < this.skeletons.length; o++)
            if (this.skeletons[o].uniqueId === i)
                return this.skeletons[o];
        return null
    }
    ,
    e.prototype.getSkeletonById = function(i) {
        for (var o = 0; o < this.skeletons.length; o++)
            if (this.skeletons[o].id === i)
                return this.skeletons[o];
        return null
    }
    ,
    e.prototype.getSkeletonByName = function(i) {
        for (var o = 0; o < this.skeletons.length; o++)
            if (this.skeletons[o].name === i)
                return this.skeletons[o];
        return null
    }
    ,
    e.prototype.getMorphTargetManagerById = function(i) {
        for (var o = 0; o < this.morphTargetManagers.length; o++)
            if (this.morphTargetManagers[o].uniqueId === i)
                return this.morphTargetManagers[o];
        return null
    }
    ,
    e.prototype.getMorphTargetById = function(i) {
        for (var o = 0; o < this.morphTargetManagers.length; ++o)
            for (var s = this.morphTargetManagers[o], c = 0; c < s.numTargets; ++c) {
                var d = s.getTarget(c);
                if (d.id === i)
                    return d
            }
        return null
    }
    ,
    e.prototype.getMorphTargetByName = function(i) {
        for (var o = 0; o < this.morphTargetManagers.length; ++o)
            for (var s = this.morphTargetManagers[o], c = 0; c < s.numTargets; ++c) {
                var d = s.getTarget(c);
                if (d.name === i)
                    return d
            }
        return null
    }
    ,
    e.prototype.getPostProcessByName = function(i) {
        for (var o = 0; o < this.postProcesses.length; ++o) {
            var s = this.postProcesses[o];
            if (s.name === i)
                return s
        }
        return null
    }
    ,
    e.prototype.isActiveMesh = function(i) {
        return this._activeMeshes.indexOf(i) !== -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(i, o) {
        return this._externalData || (this._externalData = new StringDictionary),
        this._externalData.add(i, o)
    }
    ,
    e.prototype.getExternalData = function(i) {
        return this._externalData ? this._externalData.get(i) : null
    }
    ,
    e.prototype.getOrAddExternalDataWithFactory = function(i, o) {
        return this._externalData || (this._externalData = new StringDictionary),
        this._externalData.getOrAddWithFactory(i, o)
    }
    ,
    e.prototype.removeExternalData = function(i) {
        return this._externalData.remove(i)
    }
    ,
    e.prototype._evaluateSubMesh = function(i, o, s) {
        if (s.hasInstances || s.isAnInstance || this.dispatchAllSubMeshesOfActiveMeshes || this._skipFrustumClipping || o.alwaysSelectAsActiveMesh || o.subMeshes.length === 1 || i.isInFrustum(this._frustumPlanes)) {
            for (var c = 0, d = this._evaluateSubMeshStage; c < d.length; c++) {
                var _ = d[c];
                _.action(o, i)
            }
            var b = i.getMaterial();
            b != null && (b.hasRenderTargetTextures && b.getRenderTargetTextures != null && this._processedMaterials.indexOf(b) === -1 && (this._processedMaterials.push(b),
            this._renderTargets.concatWithNoDuplicate(b.getRenderTargetTextures())),
            this._renderingManager.dispatch(i, o, b))
        }
    }
    ,
    e.prototype.freeProcessedMaterials = function() {
        this._processedMaterials.dispose()
    }
    ,
    Object.defineProperty(e.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
        get: function() {
            return this._preventFreeActiveMeshesAndRenderingGroups
        },
        set: function(i) {
            this._preventFreeActiveMeshesAndRenderingGroups !== i && (i && (this.freeActiveMeshes(),
            this.freeRenderingGroups()),
            this._preventFreeActiveMeshesAndRenderingGroups = i)
        },
        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 i = 0; i < this.activeCameras.length; i++) {
                var o = this.activeCameras[i];
                o && o._activeMeshes && o._activeMeshes.dispose()
            }
    }
    ,
    e.prototype.freeRenderingGroups = function() {
        if (!this.blockfreeActiveMeshesAndRenderingGroups && (this._renderingManager && this._renderingManager.freeRenderingGroups(),
        this.textures))
            for (var i = 0; i < this.textures.length; i++) {
                var o = this.textures[i];
                o && o.renderList && o.freeRenderingGroups()
            }
    }
    ,
    e.prototype._isInIntermediateRendering = function() {
        return this._intermediateRendering
    }
    ,
    e.prototype.freezeActiveMeshes = function(i, o, s, c) {
        var d = this;
        return i === void 0 && (i = !1),
        c === void 0 && (c = !0),
        this.executeWhenReady(function() {
            if (!d.activeCamera) {
                s && s("No active camera found");
                return
            }
            if (d._frustumPlanes || d.setTransformMatrix(d.activeCamera.getViewMatrix(), d.activeCamera.getProjectionMatrix()),
            d._evaluateActiveMeshes(),
            d._activeMeshesFrozen = !0,
            d._skipEvaluateActiveMeshesCompletely = i,
            c)
                for (var _ = 0; _ < d._activeMeshes.length; _++)
                    d._activeMeshes.data[_]._freeze();
            o && o()
        }),
        this
    }
    ,
    e.prototype.unfreezeActiveMeshes = function() {
        for (var i = 0; i < this.meshes.length; i++) {
            var o = this.meshes[i];
            o._internalAbstractMeshDataInfo && (o._internalAbstractMeshDataInfo._isActive = !1)
        }
        for (var i = 0; i < this._activeMeshes.length; i++)
            this._activeMeshes.data[i]._unFreeze();
        return this._activeMeshesFrozen = !1,
        this
    }
    ,
    e.prototype._evaluateActiveMeshes = function() {
        var i;
        if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) {
            this._activeMeshes.length > 0 && ((i = this.activeCamera) === null || i === void 0 || i._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 o = this._activeMeshes.length, s = 0; s < o; s++) {
                    var c = this._activeMeshes.data[s];
                    c.computeWorldMatrix()
                }
            if (this._activeParticleSystems)
                for (var d = this._activeParticleSystems.length, s = 0; s < d; s++)
                    this._activeParticleSystems.data[s].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 _ = 0, b = this._beforeEvaluateActiveMeshStage; _ < b.length; _++) {
                var k = b[_];
                k.action()
            }
            for (var j = this.getActiveMeshCandidates(), $ = j.length, s = 0; s < $; s++) {
                var c = j.data[s];
                if (c._internalAbstractMeshDataInfo._currentLODIsUpToDate = !1,
                !c.isBlocked && (this._totalVertices.addCount(c.getTotalVertices(), !1),
                !(!c.isReady() || !c.isEnabled() || c.scaling.lengthSquared() === 0))) {
                    c.computeWorldMatrix(),
                    c.actionManager && c.actionManager.hasSpecificTriggers2(12, 13) && this._meshesForIntersections.pushNoDuplicate(c);
                    var _e = this.customLODSelector ? this.customLODSelector(c, this.activeCamera) : c.getLOD(this.activeCamera);
                    if (c._internalAbstractMeshDataInfo._currentLOD = _e,
                    c._internalAbstractMeshDataInfo._currentLODIsUpToDate = !0,
                    _e != null && (_e !== c && _e.billboardMode !== 0 && _e.computeWorldMatrix(),
                    c._preActivate(),
                    c.isVisible && c.visibility > 0 && (c.layerMask & this.activeCamera.layerMask) !== 0 && (this._skipFrustumClipping || c.alwaysSelectAsActiveMesh || c.isInFrustum(this._frustumPlanes)))) {
                        this._activeMeshes.push(c),
                        this.activeCamera._activeMeshes.push(c),
                        _e !== c && _e._activate(this._renderId, !1);
                        for (var et = 0, tt = this._preActiveMeshStage; et < tt.length; et++) {
                            var k = tt[et];
                            k.action(c)
                        }
                        c._activate(this._renderId, !1) && (c.isAnInstance ? c._internalAbstractMeshDataInfo._actAsRegularMesh && (_e = c) : _e._internalAbstractMeshDataInfo._onlyForInstances = !1,
                        _e._internalAbstractMeshDataInfo._isActive = !0,
                        this._activeMesh(c, _e)),
                        c._postActivate()
                    }
                }
            }
            if (this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),
            this.particlesEnabled) {
                this.onBeforeParticlesRenderingObservable.notifyObservers(this);
                for (var rt = 0; rt < this.particleSystems.length; rt++) {
                    var it = this.particleSystems[rt];
                    if (!(!it.isStarted() || !it.emitter)) {
                        var nt = it.emitter;
                        (!nt.position || nt.isEnabled()) && (this._activeParticleSystems.push(it),
                        it.animate(),
                        this._renderingManager.dispatchParticles(it))
                    }
                }
                this.onAfterParticlesRenderingObservable.notifyObservers(this)
            }
        }
    }
    ,
    e.prototype._activeMesh = function(i, o) {
        if (this._skeletonsEnabled && o.skeleton !== null && o.skeleton !== void 0 && (this._activeSkeletons.pushNoDuplicate(o.skeleton) && o.skeleton.prepare(),
        o.computeBonesUsingShaders || this._softwareSkinnedMeshes.pushNoDuplicate(o)),
        o != null && o.subMeshes !== void 0 && o.subMeshes !== null && o.subMeshes.length > 0)
            for (var s = this.getActiveSubMeshCandidates(o), c = s.length, d = 0; d < c; d++) {
                var _ = s.data[d];
                this._evaluateSubMesh(_, o, i)
            }
    }
    ,
    e.prototype.updateTransformMatrix = function(i) {
        !this.activeCamera || this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(i))
    }
    ,
    e.prototype._bindFrameBuffer = function(i, o) {
        o === void 0 && (o = !0),
        i && i._multiviewTexture ? i._multiviewTexture._bindFrameBuffer() : i && i.outputRenderTarget ? i.outputRenderTarget._bindFrameBuffer() : this._engine._currentFrameBufferIsDefaultFrameBuffer() || this._engine.restoreDefaultFramebuffer(),
        o && this._clearFrameBuffer(i)
    }
    ,
    e.prototype._clearFrameBuffer = function(i) {
        if (!(i && i._multiviewTexture))
            if (i && i.outputRenderTarget) {
                var o = i.outputRenderTarget;
                o.onClearObservable.hasObservers() ? o.onClearObservable.notifyObservers(this._engine) : o.skipInitialClear || (this._engine.clear(o.clearColor || this.clearColor, !o._cleared, !0, !0),
                o._cleared = !0)
            } else
                this._defaultFrameBufferCleared ? this._engine.clear(null, !1, !0, !0) : (this._defaultFrameBufferCleared = !0,
                this._clear())
    }
    ,
    e.prototype._renderForCamera = function(i, o, s) {
        var c, d, _;
        if (s === void 0 && (s = !0),
        !(i && i._skipRendering)) {
            var b = this._engine;
            if (this._activeCamera = i,
            !this.activeCamera)
                throw new Error("Active camera not set");
            b.setViewport(this.activeCamera.viewport),
            this.resetCachedMaterial(),
            this._renderId++,
            !this.prePass && s && this._bindFrameBuffer(this._activeCamera);
            var k = this.getEngine().getCaps().multiview && i.outputRenderTarget && i.outputRenderTarget.getViewCount() > 1;
            k ? this.setTransformMatrix(i._rigCameras[0].getViewMatrix(), i._rigCameras[0].getProjectionMatrix(), i._rigCameras[1].getViewMatrix(), i._rigCameras[1].getProjectionMatrix()) : this.updateTransformMatrix(),
            this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),
            this._evaluateActiveMeshes();
            for (var j = 0; j < this._softwareSkinnedMeshes.length; j++) {
                var $ = this._softwareSkinnedMeshes.data[j];
                $.applySkeleton($.skeleton)
            }
            this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),
            i.customRenderTargets && i.customRenderTargets.length > 0 && this._renderTargets.concatWithNoDuplicate(i.customRenderTargets),
            o && o.customRenderTargets && o.customRenderTargets.length > 0 && this._renderTargets.concatWithNoDuplicate(o.customRenderTargets),
            this.environmentTexture && this.environmentTexture.isRenderTarget && this._renderTargets.pushNoDuplicate(this.environmentTexture);
            for (var _e = 0, et = this._gatherActiveCameraRenderTargetsStage; _e < et.length; _e++) {
                var tt = et[_e];
                tt.action(this._renderTargets)
            }
            var rt = !1;
            if (this.renderTargetsEnabled) {
                if (this._intermediateRendering = !0,
                this._renderTargets.length > 0) {
                    Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
                    for (var it = 0; it < this._renderTargets.length; it++) {
                        var nt = this._renderTargets.data[it];
                        if (nt._shouldRender()) {
                            this._renderId++;
                            var ot = nt.activeCamera && nt.activeCamera !== this.activeCamera;
                            nt.render(ot, this.dumpNextRenderTargets),
                            rt = !0
                        }
                    }
                    Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0),
                    this._renderId++
                }
                for (var at = 0, st = this._cameraDrawRenderTargetStage; at < st.length; at++) {
                    var tt = st[at];
                    rt = tt.action(this.activeCamera) || rt
                }
                this._intermediateRendering = !1
            }
            this._engine.currentRenderPassId = (_ = (d = (c = i.outputRenderTarget) === null || c === void 0 ? void 0 : c.renderPassId) !== null && d !== void 0 ? d : i.renderPassId) !== null && _ !== void 0 ? _ : 0,
            rt && !this.prePass && this._bindFrameBuffer(this._activeCamera, !1),
            this.onAfterRenderTargetsRenderObservable.notifyObservers(this),
            this.postProcessManager && !i._multiviewTexture && !this.prePass && this.postProcessManager._prepareFrame();
            for (var ut = 0, ct = this._beforeCameraDrawStage; ut < ct.length; ut++) {
                var tt = ct[ut];
                tt.action(this.activeCamera)
            }
            this.onBeforeDrawPhaseObservable.notifyObservers(this),
            b.snapshotRendering && b.snapshotRenderingMode === 1 && this.finalizeSceneUbo(),
            this._renderingManager.render(null, null, !0, !0),
            this.onAfterDrawPhaseObservable.notifyObservers(this);
            for (var lt = 0, ft = this._afterCameraDrawStage; lt < ft.length; lt++) {
                var tt = ft[lt];
                tt.action(this.activeCamera)
            }
            if (this.postProcessManager && !i._multiviewTexture) {
                var ht = i.outputRenderTarget ? i.outputRenderTarget.renderTarget : void 0;
                this.postProcessManager._finalizeFrame(i.isIntermediate, ht)
            }
            this._renderTargets.reset(),
            this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)
        }
    }
    ,
    e.prototype._processSubCameras = function(i, o) {
        if (o === void 0 && (o = !0),
        i.cameraRigMode === 0 || i.outputRenderTarget && i.outputRenderTarget.getViewCount() > 1 && this.getEngine().getCaps().multiview) {
            this._renderForCamera(i, void 0, o),
            this.onAfterRenderCameraObservable.notifyObservers(i);
            return
        }
        if (i._useMultiviewToSingleView)
            this._renderMultiviewToSingleView(i);
        else {
            this.onBeforeCameraRenderObservable.notifyObservers(i);
            for (var s = 0; s < i._rigCameras.length; s++)
                this._renderForCamera(i._rigCameras[s], i)
        }
        this._activeCamera = i,
        this.setTransformMatrix(this._activeCamera.getViewMatrix(), this._activeCamera.getProjectionMatrix()),
        this.onAfterRenderCameraObservable.notifyObservers(i)
    }
    ,
    e.prototype._checkIntersections = function() {
        for (var i = 0; i < this._meshesForIntersections.length; i++) {
            var o = this._meshesForIntersections.data[i];
            if (!!o.actionManager)
                for (var s = 0; o.actionManager && s < o.actionManager.actions.length; s++) {
                    var c = o.actionManager.actions[s];
                    if (c.trigger === 12 || c.trigger === 13) {
                        var d = c.getTriggerParameter()
                          , _ = d.mesh ? d.mesh : d
                          , b = _.intersectsMesh(o, d.usePreciseIntersection)
                          , k = o._intersectionsInProgress.indexOf(_);
                        b && k === -1 ? c.trigger === 12 ? (c._executeCurrent(ActionEvent.CreateNew(o, void 0, _)),
                        o._intersectionsInProgress.push(_)) : c.trigger === 13 && o._intersectionsInProgress.push(_) : !b && k > -1 && (c.trigger === 13 && c._executeCurrent(ActionEvent.CreateNew(o, void 0, _)),
                        (!o.actionManager.hasSpecificTrigger(13, function(j) {
                            var $ = j.mesh ? j.mesh : j;
                            return _ === $
                        }) || c.trigger === 13) && o._intersectionsInProgress.splice(k, 1))
                    }
                }
        }
    }
    ,
    e.prototype._advancePhysicsEngineStep = function(i) {}
    ,
    e.prototype._animate = function() {}
    ,
    e.prototype.animate = function() {
        if (this._engine.isDeterministicLockStep()) {
            var i = Math.max(e.MinDeltaTime, Math.min(this._engine.getDeltaTime(), e.MaxDeltaTime)) + this._timeAccumulator
              , o = this._engine.getTimeStep()
              , s = 1e3 / o / 1e3
              , c = 0
              , d = this._engine.getLockstepMaxSteps()
              , _ = Math.floor(i / o);
            for (_ = Math.min(_, d); i > 0 && c < _; )
                this.onBeforeStepObservable.notifyObservers(this),
                this._animationRatio = o * s,
                this._animate(),
                this.onAfterAnimationsObservable.notifyObservers(this),
                this.physicsEnabled && this._advancePhysicsEngineStep(o),
                this.onAfterStepObservable.notifyObservers(this),
                this._currentStepId++,
                c++,
                i -= o;
            this._timeAccumulator = i < 0 ? 0 : i
        } else {
            var i = this.useConstantAnimationDeltaTime ? 16 : Math.max(e.MinDeltaTime, Math.min(this._engine.getDeltaTime(), e.MaxDeltaTime));
            this._animationRatio = i * (60 / 1e3),
            this._animate(),
            this.onAfterAnimationsObservable.notifyObservers(this),
            this.physicsEnabled && this._advancePhysicsEngineStep(i)
        }
    }
    ,
    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(i) {
        var o;
        if ((i == null ? void 0 : i.outputRenderTarget) && !(i != null && i.isRigCamera) && (i.outputRenderTarget._cleared = !1),
        !((o = i == null ? void 0 : i.rigCameras) === null || o === void 0) && o.length)
            for (var s = 0; s < i.rigCameras.length; ++s) {
                var c = i.rigCameras[s].outputRenderTarget;
                c && (c._cleared = !1)
            }
    }
    ,
    e.prototype.resetDrawCache = function() {
        if (!!this.meshes)
            for (var i = 0, o = this.meshes; i < o.length; i++) {
                var s = o[i];
                s.resetDrawCache()
            }
    }
    ,
    e.prototype.render = function(i, o) {
        var s, c, d;
        if (i === void 0 && (i = !0),
        o === void 0 && (o = !1),
        !this.isDisposed) {
            this.onReadyObservable.hasObservers() && this._executeWhenReadyTimeoutId === -1 && this._checkIsReady(),
            this._frameId++,
            this._defaultFrameBufferCleared = !1,
            this.checkCameraRenderTarget(this.activeCamera),
            !((s = this.activeCameras) === null || s === void 0) && s.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),
            o || this.animate();
            for (var _ = 0, b = this._beforeCameraUpdateStage; _ < b.length; _++) {
                var k = b[_];
                k.action()
            }
            if (i) {
                if (this.activeCameras && this.activeCameras.length > 0)
                    for (var j = 0; j < this.activeCameras.length; j++) {
                        var $ = this.activeCameras[j];
                        if ($.update(),
                        $.cameraRigMode !== 0)
                            for (var _e = 0; _e < $._rigCameras.length; _e++)
                                $._rigCameras[_e].update()
                    }
                else if (this.activeCamera && (this.activeCamera.update(),
                this.activeCamera.cameraRigMode !== 0))
                    for (var _e = 0; _e < this.activeCamera._rigCameras.length; _e++)
                        this.activeCamera._rigCameras[_e].update()
            }
            this.onBeforeRunRegisterBeforeRenderObservable.notifyObservers(this),
            this.onBeforeRenderObservable.notifyObservers(this),
            this.onAfterRunRegisterBeforeRenderObservable.notifyObservers(this),
            this.onBeforeRTT1Observable.notifyObservers(this);
            var et = this.getEngine();
            this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
            var tt = !((c = this.activeCameras) === null || c === void 0) && c.length ? this.activeCameras[0] : this.activeCamera;
            if (this.renderTargetsEnabled) {
                Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0),
                this._intermediateRendering = !0;
                for (var rt = 0; rt < this.customRenderTargets.length; rt++) {
                    var it = this.customRenderTargets[rt];
                    if (it._shouldRender()) {
                        if (this._renderId++,
                        this.activeCamera = it.activeCamera || this.activeCamera,
                        !this.activeCamera)
                            throw new Error("Active camera not set");
                        et.setViewport(this.activeCamera.viewport),
                        this.updateTransformMatrix(),
                        it.render(tt !== this.activeCamera, this.dumpNextRenderTargets)
                    }
                }
                Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0),
                this._intermediateRendering = !1,
                this._renderId++
            }
            this._engine.currentRenderPassId = (d = tt == null ? void 0 : tt.renderPassId) !== null && d !== void 0 ? d : 0,
            this.activeCamera = tt,
            this._activeCamera && this._activeCamera.cameraRigMode !== 22 && !this.prePass && this._bindFrameBuffer(this._activeCamera, !1),
            this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
            for (var nt = 0, ot = this._beforeClearStage; nt < ot.length; nt++) {
                var k = ot[nt];
                k.action()
            }
            this._clearFrameBuffer(this.activeCamera);
            for (var at = 0, st = this._gatherRenderTargetsStage; at < st.length; at++) {
                var k = st[at];
                k.action(this._renderTargets)
            }
            if (this.onAfterRTT1Observable.notifyObservers(this),
            this.activeCameras && this.activeCameras.length > 0)
                for (var j = 0; j < this.activeCameras.length; j++)
                    this._processSubCameras(this.activeCameras[j], j > 0);
            else {
                if (!this.activeCamera)
                    throw new Error("No camera defined");
                this._processSubCameras(this.activeCamera, !1)
            }
            this.onBeforeRunRegisterAfterRenderObservable.notifyObservers(this),
            this._checkIntersections();
            for (var ut = 0, ct = this._afterRenderStage; ut < ct.length; ut++) {
                var k = ct[ut];
                k.action()
            }
            if (this.afterRender && this.afterRender(),
            this.onAfterRenderObservable.notifyObservers(this),
            this.onAfterRunRegisterAfterRenderObservable.notifyObservers(this),
            this._toBeDisposed.length) {
                for (var _e = 0; _e < this._toBeDisposed.length; _e++) {
                    var lt = this._toBeDisposed[_e];
                    lt && lt.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 i = 0; i < this.materials.length; i++)
            this.materials[i].freeze()
    }
    ,
    e.prototype.unfreezeMaterials = function() {
        for (var i = 0; i < this.materials.length; i++)
            this.materials[i].unfreeze()
    }
    ,
    e.prototype.dispose = function() {
        var i;
        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 o = 0, s = this._components; o < s.length; o++) {
                var c = s[o];
                c.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 d = 0, _ = this._activeRequests; d < _.length; d++) {
                var b = _[d];
                b.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(),
            (i = this._computePressureObserver) === null || i === void 0 || i.unobserve(),
            this._computePressureObserver = void 0,
            this.detachControl();
            var k = this._engine.getInputElement();
            if (k) {
                var j;
                for (j = 0; j < this.cameras.length; j++)
                    this.cameras[j].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(),
            j = this._engine.scenes.indexOf(this),
            j > -1 && this._engine.scenes.splice(j, 1),
            EngineStore._LastCreatedScene === this && (this._engine.scenes.length > 0 ? EngineStore._LastCreatedScene = this._engine.scenes[this._engine.scenes.length - 1] : EngineStore._LastCreatedScene = null),
            j = this._engine._virtualScenes.indexOf(this),
            j > -1 && this._engine._virtualScenes.splice(j, 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 i = 0; i < this.meshes.length; i++) {
            var o = this.meshes[i]
              , s = o.geometry;
            s && s.clearCachedData()
        }
    }
    ,
    e.prototype.cleanCachedTextureBuffer = function() {
        for (var i = 0, o = this.textures; i < o.length; i++) {
            var s = o[i]
              , c = s._buffer;
            c && (s._buffer = null)
        }
    }
    ,
    e.prototype.getWorldExtends = function(i) {
        var o = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)
          , s = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);
        return i = i || function() {
            return !0
        }
        ,
        this.meshes.filter(i).forEach(function(c) {
            if (c.computeWorldMatrix(!0),
            !(!c.subMeshes || c.subMeshes.length === 0 || c.infiniteDistance)) {
                var d = c.getBoundingInfo()
                  , _ = d.boundingBox.minimumWorld
                  , b = d.boundingBox.maximumWorld;
                Vector3.CheckExtends(_, o, s),
                Vector3.CheckExtends(b, o, s)
            }
        }),
        {
            min: o,
            max: s
        }
    }
    ,
    e.prototype.createPickingRay = function(i, o, s, c, d) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.createPickingRayToRef = function(i, o, s, c, d, _) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.createPickingRayInCameraSpace = function(i, o, s) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.createPickingRayInCameraSpaceToRef = function(i, o, s, c) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.pick = function(i, o, s, c, d, _) {
        var b = new PickingInfo;
        return b._pickingUnavailable = !0,
        b
    }
    ,
    e.prototype.pickWithBoundingInfo = function(i, o, s, c, d) {
        var _ = new PickingInfo;
        return _._pickingUnavailable = !0,
        _
    }
    ,
    e.prototype.pickWithRay = function(i, o, s, c) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.multiPick = function(i, o, s, c, d) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.multiPickWithRay = function(i, o, s) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.setPointerOverMesh = function(i, o, s) {
        this._inputManager.setPointerOverMesh(i, o, s)
    }
    ,
    e.prototype.getPointerOverMesh = function() {
        return this._inputManager.getPointerOverMesh()
    }
    ,
    e.prototype._rebuildGeometries = function() {
        for (var i = 0, o = this.geometries; i < o.length; i++) {
            var s = o[i];
            s._rebuild()
        }
        for (var c = 0, d = this.meshes; c < d.length; c++) {
            var _ = d[c];
            _._rebuild()
        }
        this.postProcessManager && this.postProcessManager._rebuild();
        for (var b = 0, k = this._components; b < k.length; b++) {
            var j = k[b];
            j.rebuild()
        }
        for (var $ = 0, _e = this.particleSystems; $ < _e.length; $++) {
            var et = _e[$];
            et.rebuild()
        }
        if (this.spriteManagers)
            for (var tt = 0, rt = this.spriteManagers; tt < rt.length; tt++) {
                var it = rt[tt];
                it.rebuild()
            }
    }
    ,
    e.prototype._rebuildTextures = function() {
        for (var i = 0, o = this.textures; i < o.length; i++) {
            var s = o[i];
            s._rebuild()
        }
        this.markAllMaterialsAsDirty(1)
    }
    ,
    e.prototype._getByTags = function(i, o, s) {
        if (o === void 0)
            return i;
        var c = [];
        s = s || function(b) {}
        ;
        for (var d in i) {
            var _ = i[d];
            Tags && Tags.MatchesQuery(_, o) && (c.push(_),
            s(_))
        }
        return c
    }
    ,
    e.prototype.getMeshesByTags = function(i, o) {
        return this._getByTags(this.meshes, i, o)
    }
    ,
    e.prototype.getCamerasByTags = function(i, o) {
        return this._getByTags(this.cameras, i, o)
    }
    ,
    e.prototype.getLightsByTags = function(i, o) {
        return this._getByTags(this.lights, i, o)
    }
    ,
    e.prototype.getMaterialByTags = function(i, o) {
        return this._getByTags(this.materials, i, o).concat(this._getByTags(this.multiMaterials, i, o))
    }
    ,
    e.prototype.getTransformNodesByTags = function(i, o) {
        return this._getByTags(this.transformNodes, i, o)
    }
    ,
    e.prototype.setRenderingOrder = function(i, o, s, c) {
        o === void 0 && (o = null),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        this._renderingManager.setRenderingOrder(i, o, s, c)
    }
    ,
    e.prototype.setRenderingAutoClearDepthStencil = function(i, o, s, c) {
        s === void 0 && (s = !0),
        c === void 0 && (c = !0),
        this._renderingManager.setRenderingAutoClearDepthStencil(i, o, s, c)
    }
    ,
    e.prototype.getAutoClearDepthStencilSetup = function(i) {
        return this._renderingManager.getAutoClearDepthStencilSetup(i)
    }
    ,
    Object.defineProperty(e.prototype, "blockMaterialDirtyMechanism", {
        get: function() {
            return this._blockMaterialDirtyMechanism
        },
        set: function(i) {
            this._blockMaterialDirtyMechanism !== i && (this._blockMaterialDirtyMechanism = i,
            i || this.markAllMaterialsAsDirty(63))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.markAllMaterialsAsDirty = function(i, o) {
        if (!this._blockMaterialDirtyMechanism)
            for (var s = 0, c = this.materials; s < c.length; s++) {
                var d = c[s];
                o && !o(d) || d.markAsDirty(i)
            }
    }
    ,
    e.prototype._loadFile = function(i, o, s, c, d, _, b) {
        var k = this
          , j = LoadFile(i, o, s, c ? this.offlineProvider : void 0, d, _, b);
        return this._activeRequests.push(j),
        j.onCompleteObservable.add(function($) {
            k._activeRequests.splice(k._activeRequests.indexOf($), 1)
        }),
        j
    }
    ,
    e.prototype._loadFileAsync = function(i, o, s, c, d) {
        var _ = this;
        return new Promise(function(b, k) {
            _._loadFile(i, function(j) {
                b(j)
            }, o, s, c, function(j, $) {
                k($)
            }, d)
        }
        )
    }
    ,
    e.prototype._requestFile = function(i, o, s, c, d, _, b) {
        var k = this
          , j = RequestFile(i, o, s, c ? this.offlineProvider : void 0, d, _, b);
        return this._activeRequests.push(j),
        j.onCompleteObservable.add(function($) {
            k._activeRequests.splice(k._activeRequests.indexOf($), 1)
        }),
        j
    }
    ,
    e.prototype._requestFileAsync = function(i, o, s, c, d) {
        var _ = this;
        return new Promise(function(b, k) {
            _._requestFile(i, function(j) {
                b(j)
            }, o, s, c, function(j) {
                k(j)
            }, d)
        }
        )
    }
    ,
    e.prototype._readFile = function(i, o, s, c, d) {
        var _ = this
          , b = ReadFile(i, o, s, c, d);
        return this._activeRequests.push(b),
        b.onCompleteObservable.add(function(k) {
            _._activeRequests.splice(_._activeRequests.indexOf(k), 1)
        }),
        b
    }
    ,
    e.prototype._readFileAsync = function(i, o, s) {
        var c = this;
        return new Promise(function(d, _) {
            c._readFile(i, function(b) {
                d(b)
            }, o, s, function(b) {
                _(b)
            })
        }
        )
    }
    ,
    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 Size = function() {
    function a(e, i) {
        this.width = e,
        this.height = i
    }
    return a.prototype.toString = function() {
        return "{W: " + this.width + ", H: " + this.height + "}"
    }
    ,
    a.prototype.getClassName = function() {
        return "Size"
    }
    ,
    a.prototype.getHashCode = function() {
        var e = this.width | 0;
        return e = e * 397 ^ (this.height | 0),
        e
    }
    ,
    a.prototype.copyFrom = function(e) {
        this.width = e.width,
        this.height = e.height
    }
    ,
    a.prototype.copyFromFloats = function(e, i) {
        return this.width = e,
        this.height = i,
        this
    }
    ,
    a.prototype.set = function(e, i) {
        return this.copyFromFloats(e, i)
    }
    ,
    a.prototype.multiplyByFloats = function(e, i) {
        return new a(this.width * e,this.height * i)
    }
    ,
    a.prototype.clone = function() {
        return new a(this.width,this.height)
    }
    ,
    a.prototype.equals = function(e) {
        return e ? this.width === e.width && this.height === e.height : !1
    }
    ,
    Object.defineProperty(a.prototype, "surface", {
        get: function() {
            return this.width * this.height
        },
        enumerable: !1,
        configurable: !0
    }),
    a.Zero = function() {
        return new a(0,0)
    }
    ,
    a.prototype.add = function(e) {
        var i = new a(this.width + e.width,this.height + e.height);
        return i
    }
    ,
    a.prototype.subtract = function(e) {
        var i = new a(this.width - e.width,this.height - e.height);
        return i
    }
    ,
    a.Lerp = function(e, i, o) {
        var s = e.width + (i.width - e.width) * o
          , c = e.height + (i.height - e.height) * o;
        return new a(s,c)
    }
    ,
    a
}()
  , ThinTexture = function() {
    function a(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(a.prototype, "wrapU", {
        get: function() {
            return this._wrapU
        },
        set: function(e) {
            this._wrapU = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "wrapV", {
        get: function() {
            return this._wrapV
        },
        set: function(e) {
            this._wrapV = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "coordinatesMode", {
        get: function() {
            return 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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(a.prototype, "is2DArray", {
        get: function() {
            return this._texture ? this._texture.is2DArray : !1
        },
        set: function(e) {
            !this._texture || (this._texture.is2DArray = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getClassName = function() {
        return "ThinTexture"
    }
    ,
    a.prototype.isReady = function() {
        return this.delayLoadState === 4 ? (this.delayLoad(),
        !1) : this._texture ? this._texture.isReady : !1
    }
    ,
    a.prototype.delayLoad = function() {}
    ,
    a.prototype.getInternalTexture = function() {
        return this._texture
    }
    ,
    a.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
    }
    ,
    a.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(a.prototype, "samplingMode", {
        get: function() {
            return this._texture ? this._texture.samplingMode : this._initialSamplingMode
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.updateSamplingMode = function(e) {
        this._texture && this._engine && this._engine.updateTextureSamplingMode(e, this._texture)
    }
    ,
    a.prototype.releaseInternalTexture = function() {
        this._texture && (this._texture.dispose(),
        this._texture = null)
    }
    ,
    a.prototype.dispose = function() {
        this._texture && (this.releaseInternalTexture(),
        this._engine = null)
    }
    ,
    a
}()
  , BaseTexture = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, null) || this;
        return o.metadata = null,
        o.reservedDataStore = null,
        o._hasAlpha = !1,
        o.getAlphaFromRGB = !1,
        o.level = 1,
        o.coordinatesIndex = 0,
        o._coordinatesMode = 0,
        o.wrapR = 1,
        o.anisotropicFilteringLevel = e.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,
        o._isCube = !1,
        o._gammaSpace = !0,
        o.invertZ = !1,
        o.lodLevelInAlpha = !1,
        o.isRenderTarget = !1,
        o._prefiltered = !1,
        o._forceSerialize = !1,
        o.animations = new Array,
        o.onDisposeObservable = new Observable,
        o._onDisposeObserver = null,
        o._scene = null,
        o._uid = null,
        o._parentContainer = null,
        o._loadingError = !1,
        i ? e._isScene(i) ? o._scene = i : o._engine = i : o._scene = EngineStore.LastCreatedScene,
        o._scene && (o.uniqueId = o._scene.getUniqueId(),
        o._scene.addTexture(o),
        o._engine = o._scene.getEngine()),
        o._uid = null,
        o
    }
    return Object.defineProperty(e.prototype, "hasAlpha", {
        get: function() {
            return this._hasAlpha
        },
        set: function(i) {
            this._hasAlpha !== i && (this._hasAlpha = i,
            this._scene && this._scene.markAllMaterialsAsDirty(17))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "coordinatesMode", {
        get: function() {
            return this._coordinatesMode
        },
        set: function(i) {
            this._coordinatesMode !== i && (this._coordinatesMode = i,
            this._scene && this._scene.markAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wrapU", {
        get: function() {
            return this._wrapU
        },
        set: function(i) {
            this._wrapU = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wrapV", {
        get: function() {
            return this._wrapV
        },
        set: function(i) {
            this._wrapV = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isCube", {
        get: function() {
            return this._texture ? this._texture.isCube : this._isCube
        },
        set: function(i) {
            this._texture ? this._texture.isCube = i : this._isCube = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "is3D", {
        get: function() {
            return this._texture ? this._texture.is3D : !1
        },
        set: function(i) {
            !this._texture || (this._texture.is3D = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "is2DArray", {
        get: function() {
            return this._texture ? this._texture.is2DArray : !1
        },
        set: function(i) {
            !this._texture || (this._texture.is2DArray = i)
        },
        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(i) {
            if (this._texture) {
                if (this._texture._gammaSpace === i)
                    return;
                this._texture._gammaSpace = i
            } else {
                if (this._gammaSpace === i)
                    return;
                this._gammaSpace = i
            }
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isRGBD", {
        get: function() {
            return this._texture != null && this._texture._isRGBD
        },
        set: function(i) {
            this._texture && (this._texture._isRGBD = i)
        },
        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(i) {
            this._texture && (this._texture._lodGenerationOffset = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lodGenerationScale", {
        get: function() {
            return this._texture ? this._texture._lodGenerationScale : 0
        },
        set: function(i) {
            this._texture && (this._texture._lodGenerationScale = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "linearSpecularLOD", {
        get: function() {
            return this._texture ? this._texture._linearSpecularLOD : !1
        },
        set: function(i) {
            this._texture && (this._texture._linearSpecularLOD = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "irradianceTexture", {
        get: function() {
            return this._texture ? this._texture._irradianceTexture : null
        },
        set: function(i) {
            this._texture && (this._texture._irradianceTexture = i)
        },
        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(i) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(i)
        },
        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(i) {
        return i !== 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(i) {}
    ,
    Object.defineProperty(e.prototype, "canRescale", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._getFromCache = function(i, o, s, c, d) {
        var _ = this._getEngine();
        if (!_)
            return null;
        for (var b = _._getUseSRGBBuffer(!!d, o), k = _.getLoadedTexturesCache(), j = 0; j < k.length; j++) {
            var $ = k[j];
            if ((d === void 0 || b === $._useSRGBBuffer) && (c === void 0 || c === $.invertY) && $.url === i && $.generateMipMaps === !o && (!s || s === $.samplingMode))
                return $.incrementReferences(),
                $
        }
        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 i = this.getScene();
        !i || i.markAllMaterialsAsDirty(1)
    }
    ,
    e.prototype.readPixels = function(i, o, s, c, d) {
        if (i === void 0 && (i = 0),
        o === void 0 && (o = 0),
        s === void 0 && (s = null),
        c === void 0 && (c = !0),
        d === void 0 && (d = !1),
        !this._texture)
            return null;
        var _ = this.getSize()
          , b = _.width
          , k = _.height
          , j = this._getEngine();
        if (!j)
            return null;
        o != 0 && (b = b / Math.pow(2, o),
        k = k / Math.pow(2, o),
        b = Math.round(b),
        k = Math.round(k));
        try {
            return this._texture.isCube ? j._readTexturePixels(this._texture, b, k, i, o, s, c, d) : j._readTexturePixels(this._texture, b, k, -1, o, s, c, d)
        } catch {
            return null
        }
    }
    ,
    e.prototype._readPixelsSync = function(i, o, s, c, d) {
        if (i === void 0 && (i = 0),
        o === void 0 && (o = 0),
        s === void 0 && (s = null),
        c === void 0 && (c = !0),
        d === void 0 && (d = !1),
        !this._texture)
            return null;
        var _ = this.getSize()
          , b = _.width
          , k = _.height
          , j = this._getEngine();
        if (!j)
            return null;
        o != 0 && (b = b / Math.pow(2, o),
        k = k / Math.pow(2, o),
        b = Math.round(b),
        k = Math.round(k));
        try {
            return this._texture.isCube ? j._readTexturePixelsSync(this._texture, b, k, i, o, s, c, d) : j._readTexturePixelsSync(this._texture, b, k, -1, o, s, c, d)
        } 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 i = this._scene.textures.indexOf(this);
            if (i >= 0 && this._scene.textures.splice(i, 1),
            this._scene.onTextureRemovedObservable.notifyObservers(this),
            this._scene = null,
            this._parentContainer) {
                var o = this._parentContainer.textures.indexOf(this);
                o > -1 && this._parentContainer.textures.splice(o, 1),
                this._parentContainer = null
            }
        }
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.metadata = null,
        a.prototype.dispose.call(this)
    }
    ,
    e.prototype.serialize = function() {
        if (!this.name)
            return null;
        var i = SerializationHelper.Serialize(this);
        return SerializationHelper.AppendSerializedAnimations(this, i),
        i
    }
    ,
    e.WhenAllReady = function(i, o) {
        var s = i.length;
        if (s === 0) {
            o();
            return
        }
        for (var c = 0; c < i.length; c++) {
            var d = i[c];
            if (d.isReady())
                --s === 0 && o();
            else {
                var _ = d.onLoadObservable;
                _ && _.addOnce(function() {
                    --s === 0 && o()
                })
            }
        }
    }
    ,
    e._isScene = function(i) {
        return i.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(a, e, i) {
    i === void 0 && (i = !1);
    var o = e.width
      , s = e.height;
    if (a instanceof Float32Array) {
        for (var c = a.byteLength / a.BYTES_PER_ELEMENT, d = new Uint8Array(c); --c >= 0; ) {
            var _ = a[c];
            _ < 0 ? _ = 0 : _ > 1 && (_ = 1),
            d[c] = _ * 255
        }
        a = d
    }
    var b = document.createElement("canvas");
    b.width = o,
    b.height = s;
    var k = b.getContext("2d");
    if (!k)
        return null;
    var j = k.createImageData(o, s)
      , $ = j.data;
    if ($.set(a),
    k.putImageData(j, 0, 0),
    i) {
        var _e = document.createElement("canvas");
        _e.width = o,
        _e.height = s;
        var et = _e.getContext("2d");
        return et ? (et.translate(0, s),
        et.scale(1, -1),
        et.drawImage(b, 0, 0),
        _e.toDataURL("image/png")) : null
    }
    return b.toDataURL("image/png")
}
function GenerateBase64StringFromTexture(a, e, i) {
    e === void 0 && (e = 0),
    i === void 0 && (i = 0);
    var o = a.getInternalTexture();
    if (!o)
        return null;
    var s = a._readPixelsSync(e, i);
    return s ? GenerateBase64StringFromPixelData(s, a.getSize(), o.invertY) : null
}
function GenerateBase64StringFromTextureAsync(a, e, i) {
    return e === void 0 && (e = 0),
    i === void 0 && (i = 0),
    __awaiter(this, void 0, void 0, function() {
        var o, s;
        return __generator(this, function(c) {
            switch (c.label) {
            case 0:
                return o = a.getInternalTexture(),
                o ? [4, a.readPixels(e, i)] : [2, null];
            case 1:
                return s = c.sent(),
                s ? [2, GenerateBase64StringFromPixelData(s, a.getSize(), o.invertY)] : [2, null]
            }
        })
    })
}
var Texture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $, _e, et, tt) {
        c === void 0 && (c = !0),
        d === void 0 && (d = e.TRILINEAR_SAMPLINGMODE),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null),
        k === void 0 && (k = null),
        j === void 0 && (j = !1);
        var rt, it, nt, ot, at, st, ut, ct, lt = a.call(this, o) || this;
        lt.url = null,
        lt.uOffset = 0,
        lt.vOffset = 0,
        lt.uScale = 1,
        lt.vScale = 1,
        lt.uAng = 0,
        lt.vAng = 0,
        lt.wAng = 0,
        lt.uRotationCenter = .5,
        lt.vRotationCenter = .5,
        lt.wRotationCenter = .5,
        lt.homogeneousRotationInUVTransform = !1,
        lt.inspectableCustomProperties = null,
        lt._noMipmap = !1,
        lt._invertY = !1,
        lt._rowGenerationMatrix = null,
        lt._cachedTextureMatrix = null,
        lt._projectionModeMatrix = null,
        lt._t0 = null,
        lt._t1 = null,
        lt._t2 = null,
        lt._cachedUOffset = -1,
        lt._cachedVOffset = -1,
        lt._cachedUScale = 0,
        lt._cachedVScale = 0,
        lt._cachedUAng = -1,
        lt._cachedVAng = -1,
        lt._cachedWAng = -1,
        lt._cachedProjectionMatrixId = -1,
        lt._cachedURotationCenter = -1,
        lt._cachedVRotationCenter = -1,
        lt._cachedWRotationCenter = -1,
        lt._cachedHomogeneousRotationInUVTransform = !1,
        lt._cachedCoordinatesMode = -1,
        lt._buffer = null,
        lt._deleteBuffer = !1,
        lt._format = null,
        lt._delayedOnLoad = null,
        lt._delayedOnError = null,
        lt.onLoadObservable = new Observable,
        lt._isBlocking = !0,
        lt.name = i || "",
        lt.url = i;
        var ft, ht = !1;
        typeof s == "object" && s !== null ? (ft = (rt = s.noMipmap) !== null && rt !== void 0 ? rt : !1,
        c = (it = s.invertY) !== null && it !== void 0 ? it : !0,
        d = (nt = s.samplingMode) !== null && nt !== void 0 ? nt : e.TRILINEAR_SAMPLINGMODE,
        _ = (ot = s.onLoad) !== null && ot !== void 0 ? ot : null,
        b = (at = s.onError) !== null && at !== void 0 ? at : null,
        k = (st = s.buffer) !== null && st !== void 0 ? st : null,
        j = (ut = s.deleteBuffer) !== null && ut !== void 0 ? ut : !1,
        $ = s.format,
        _e = s.mimeType,
        et = s.loaderOptions,
        tt = s.creationFlags,
        ht = (ct = s.useSRGBBuffer) !== null && ct !== void 0 ? ct : !1) : ft = !!s,
        lt._noMipmap = ft,
        lt._invertY = c,
        lt._initialSamplingMode = d,
        lt._buffer = k,
        lt._deleteBuffer = j,
        lt._mimeType = _e,
        lt._loaderOptions = et,
        lt._creationFlags = tt,
        lt._useSRGBBuffer = ht,
        $ && (lt._format = $);
        var pt = lt.getScene()
          , dt = lt._getEngine();
        if (!dt)
            return lt;
        dt.onBeforeTextureInitObservable.notifyObservers(lt);
        var _t = function() {
            lt._texture && (lt._texture._invertVScale && (lt.vScale *= -1,
            lt.vOffset += 1),
            lt._texture._cachedWrapU !== null && (lt.wrapU = lt._texture._cachedWrapU,
            lt._texture._cachedWrapU = null),
            lt._texture._cachedWrapV !== null && (lt.wrapV = lt._texture._cachedWrapV,
            lt._texture._cachedWrapV = null),
            lt._texture._cachedWrapR !== null && (lt.wrapR = lt._texture._cachedWrapR,
            lt._texture._cachedWrapR = null)),
            lt.onLoadObservable.hasObservers() && lt.onLoadObservable.notifyObservers(lt),
            _ && _(),
            !lt.isBlocking && pt && pt.resetCachedMaterial()
        }
          , mt = function(yt, Et) {
            lt._loadingError = !0,
            lt._errorObject = {
                message: yt,
                exception: Et
            },
            b && b(yt, Et),
            e.OnTextureLoadErrorObservable.notifyObservers(lt)
        };
        if (!lt.url)
            return lt._delayedOnLoad = _t,
            lt._delayedOnError = mt,
            lt;
        if (lt._texture = lt._getFromCache(lt.url, ft, d, c, ht),
        lt._texture)
            if (lt._texture.isReady)
                TimingTools.SetImmediate(function() {
                    return _t()
                });
            else {
                var vt = lt._texture.onLoadedObservable.add(_t);
                lt._texture.onErrorObservable.add(function(yt) {
                    var Et;
                    mt(yt.message, yt.exception),
                    (Et = lt._texture) === null || Et === void 0 || Et.onLoadedObservable.remove(vt)
                })
            }
        else if (!pt || !pt.useDelayedTextureLoading) {
            try {
                lt._texture = dt.createTexture(lt.url, ft, c, pt, d, _t, mt, lt._buffer, void 0, lt._format, null, _e, et, tt, ht)
            } catch (yt) {
                throw mt("error loading", yt),
                yt
            }
            j && (lt._buffer = null)
        } else
            lt.delayLoadState = 4,
            lt._delayedOnLoad = _t,
            lt._delayedOnError = mt;
        return lt
    }
    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(i) {
            this._isBlocking = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "invertY", {
        get: function() {
            return this._invertY
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.updateURL = function(i, o, s) {
        o === void 0 && (o = null),
        this.url && (this.releaseInternalTexture(),
        this.getScene().markAllMaterialsAsDirty(1)),
        (!this.name || StartsWith(this.name, "data:")) && (this.name = i),
        this.url = i,
        this._buffer = o,
        this.delayLoadState = 4,
        s && (this._delayedOnLoad = s),
        this.delayLoad()
    }
    ,
    e.prototype.delayLoad = function() {
        if (this.delayLoadState === 4) {
            var i = this.getScene();
            !i || (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 = i.getEngine().createTexture(this.url, this._noMipmap, this._invertY, i, 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(i, o, s, c) {
        i *= this._cachedUScale,
        o *= this._cachedVScale,
        i -= this.uRotationCenter * this._cachedUScale,
        o -= this.vRotationCenter * this._cachedVScale,
        s -= this.wRotationCenter,
        Vector3.TransformCoordinatesFromFloatsToRef(i, o, s, this._rowGenerationMatrix, c),
        c.x += this.uRotationCenter * this._cachedUScale + this._cachedUOffset,
        c.y += this.vRotationCenter * this._cachedVScale + this._cachedVOffset,
        c.z += this.wRotationCenter
    }
    ,
    e.prototype.checkTransformsAreIdentical = function(i) {
        return i !== null && this.uOffset === i.uOffset && this.vOffset === i.vOffset && this.uScale === i.uScale && this.vScale === i.vScale && this.uAng === i.uAng && this.vAng === i.vAng && this.wAng === i.wAng
    }
    ,
    e.prototype.getTextureMatrix = function(i) {
        var o = this;
        if (i === void 0 && (i = 1),
        this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale * i === 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 * i,
        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 s = this.getScene();
        return s ? (s.markAllMaterialsAsDirty(1, function(c) {
            return c.hasTexture(o)
        }),
        this._cachedTextureMatrix) : this._cachedTextureMatrix
    }
    ,
    e.prototype.getReflectionTextureMatrix = function() {
        var i = this
          , o = this.getScene();
        if (!o)
            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 === o.getProjectionMatrix().updateFlag)
                    return this._cachedTextureMatrix
            } else
                return this._cachedTextureMatrix;
        this._cachedTextureMatrix || (this._cachedTextureMatrix = Matrix.Zero()),
        this._projectionModeMatrix || (this._projectionModeMatrix = Matrix.Zero());
        var s = 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 c = o.getProjectionMatrix();
            this._cachedProjectionMatrixId = c.updateFlag,
            c.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
            break;
        default:
            Matrix.IdentityToRef(this._cachedTextureMatrix);
            break
        }
        return s && o.markAllMaterialsAsDirty(1, function(d) {
            return d.getActiveTextures().indexOf(i) !== -1
        }),
        this._cachedTextureMatrix
    }
    ,
    e.prototype.clone = function() {
        var i = this
          , o = {
            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(i._texture ? i._texture.url : null,i.getScene(),o)
        }, this)
    }
    ,
    e.prototype.serialize = function() {
        var i = this.name;
        e.SerializeBuffers || StartsWith(this.name, "data:") && (this.name = ""),
        StartsWith(this.name, "data:") && this.url === this.name && (this.url = "");
        var o = a.prototype.serialize.call(this);
        return o ? ((e.SerializeBuffers || e.ForceSerializeBuffers) && (typeof this._buffer == "string" && this._buffer.substr(0, 5) === "data:" ? (o.base64String = this._buffer,
        o.name = o.name.replace("data:", "")) : this.url && StartsWith(this.url, "data:") && this._buffer instanceof Uint8Array ? o.base64String = "data:image/png;base64," + EncodeArrayBufferToBase64(this._buffer) : (e.ForceSerializeBuffers || this.url && StartsWith(this.url, "blob:") || this._forceSerialize) && (o.base64String = !this._engine || this._engine._features.supportSyncTextureRead ? GenerateBase64StringFromTexture(this) : GenerateBase64StringFromTextureAsync(this))),
        o.invertY = this._invertY,
        o.samplingMode = this.samplingMode,
        o._creationFlags = this._creationFlags,
        o._useSRGBBuffer = this._useSRGBBuffer,
        this.name = i,
        o) : null
    }
    ,
    e.prototype.getClassName = function() {
        return "Texture"
    }
    ,
    e.prototype.dispose = function() {
        a.prototype.dispose.call(this),
        this.onLoadObservable.clear(),
        this._delayedOnLoad = null,
        this._delayedOnError = null
    }
    ,
    e.Parse = function(i, o, s) {
        if (i.customType) {
            var c = InstantiationTools.Instantiate(i.customType)
              , d = c.Parse(i, o, s);
            return i.samplingMode && d.updateSamplingMode && d._samplingMode && d._samplingMode !== i.samplingMode && d.updateSamplingMode(i.samplingMode),
            d
        }
        if (i.isCube && !i.isRenderTarget)
            return e._CubeTextureParser(i, o, s);
        if (!i.name && !i.isRenderTarget)
            return null;
        var _ = function() {
            if (b && b._texture && (b._texture._cachedWrapU = null,
            b._texture._cachedWrapV = null,
            b._texture._cachedWrapR = null),
            i.samplingMode) {
                var k = i.samplingMode;
                b && b.samplingMode !== k && b.updateSamplingMode(k)
            }
            if (b && i.animations)
                for (var j = 0; j < i.animations.length; j++) {
                    var $ = i.animations[j]
                      , _e = GetClass("BABYLON.Animation");
                    _e && b.animations.push(_e.Parse($))
                }
        }
          , b = SerializationHelper.Parse(function() {
            var k, j, $, _e = !0;
            if (i.noMipmap && (_e = !1),
            i.mirrorPlane) {
                var et = e._CreateMirror(i.name, i.renderTargetSize, o, _e);
                return et._waitingRenderList = i.renderList,
                et.mirrorPlane = Plane.FromArray(i.mirrorPlane),
                _(),
                et
            } else if (i.isRenderTarget) {
                var tt = null;
                if (i.isCube) {
                    if (o.reflectionProbes)
                        for (var rt = 0; rt < o.reflectionProbes.length; rt++) {
                            var it = o.reflectionProbes[rt];
                            if (it.name === i.name)
                                return it.cubeTexture
                        }
                } else
                    tt = e._CreateRenderTargetTexture(i.name, i.renderTargetSize, o, _e, (k = i._creationFlags) !== null && k !== void 0 ? k : 0),
                    tt._waitingRenderList = i.renderList;
                return _(),
                tt
            } else {
                var nt;
                if (i.base64String)
                    nt = e.CreateFromBase64String(i.base64String, i.name, o, !_e, i.invertY, i.samplingMode, _, (j = i._creationFlags) !== null && j !== void 0 ? j : 0, ($ = i._useSRGBBuffer) !== null && $ !== void 0 ? $ : !1);
                else {
                    var ot = void 0;
                    i.name && i.name.indexOf("://") > 0 ? ot = i.name : ot = s + i.name,
                    (StartsWith(i.url, "data:") || e.UseSerializedUrlIfAny && i.url) && (ot = i.url),
                    nt = new e(ot,o,!_e,i.invertY,i.samplingMode,_)
                }
                return nt
            }
        }, i, o);
        return b
    }
    ,
    e.CreateFromBase64String = function(i, o, s, c, d, _, b, k, j, $) {
        return _ === void 0 && (_ = e.TRILINEAR_SAMPLINGMODE),
        b === void 0 && (b = null),
        k === void 0 && (k = null),
        j === void 0 && (j = 5),
        new e("data:" + o,s,c,d,_,b,k,i,!1,j,void 0,void 0,$)
    }
    ,
    e.LoadFromDataString = function(i, o, s, c, d, _, b, k, j, $, _e) {
        return c === void 0 && (c = !1),
        _ === void 0 && (_ = !0),
        b === void 0 && (b = e.TRILINEAR_SAMPLINGMODE),
        k === void 0 && (k = null),
        j === void 0 && (j = null),
        $ === void 0 && ($ = 5),
        i.substr(0, 5) !== "data:" && (i = "data:" + i),
        new e(i,s,d,_,b,k,j,o,c,$,void 0,void 0,_e)
    }
    ,
    e.SerializeBuffers = !0,
    e.ForceSerializeBuffers = !1,
    e.OnTextureLoadErrorObservable = new Observable,
    e._CubeTextureParser = function(i, o, s) {
        throw _WarnImport("CubeTexture")
    }
    ,
    e._CreateMirror = function(i, o, s, c) {
        throw _WarnImport("MirrorTexture")
    }
    ,
    e._CreateRenderTargetTexture = function(i, o, s, c, d) {
        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;
var WebGLRenderTargetWrapper = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        var _ = a.call(this, i, o, s, c) || this;
        return _._framebuffer = null,
        _._depthStencilBuffer = null,
        _._MSAAFramebuffer = null,
        _._colorTextureArray = null,
        _._depthStencilTextureArray = null,
        _._context = d,
        _
    }
    return e.prototype._cloneRenderTargetWrapper = function() {
        var i = null;
        return this._colorTextureArray && this._depthStencilTextureArray ? (i = this._engine.createMultiviewRenderTargetTexture(this.width, this.height),
        i.texture.isReady = !0) : i = a.prototype._cloneRenderTargetWrapper.call(this),
        i
    }
    ,
    e.prototype._swapRenderTargetWrapper = function(i) {
        a.prototype._swapRenderTargetWrapper.call(this, i),
        i._framebuffer = this._framebuffer,
        i._depthStencilBuffer = this._depthStencilBuffer,
        i._MSAAFramebuffer = this._MSAAFramebuffer,
        i._colorTextureArray = this._colorTextureArray,
        i._depthStencilTextureArray = this._depthStencilTextureArray,
        this._framebuffer = this._depthStencilBuffer = this._MSAAFramebuffer = this._colorTextureArray = this._depthStencilTextureArray = null
    }
    ,
    e.prototype._shareDepth = function(i) {
        a.prototype._shareDepth.call(this, i);
        var o = this._context
          , s = this._depthStencilBuffer
          , c = i._framebuffer;
        i._depthStencilBuffer && o.deleteRenderbuffer(i._depthStencilBuffer),
        i._depthStencilBuffer = this._depthStencilBuffer,
        this._engine._bindUnboundFramebuffer(c),
        o.framebufferRenderbuffer(o.FRAMEBUFFER, o.DEPTH_ATTACHMENT, o.RENDERBUFFER, s),
        this._engine._bindUnboundFramebuffer(null)
    }
    ,
    e.prototype._bindTextureRenderTarget = function(i, o, s, c) {
        if (o === void 0 && (o = 0),
        s === void 0 && (s = -1),
        c === void 0 && (c = 0),
        !!i._hardwareTexture) {
            var d = this._context
              , _ = this._framebuffer
              , b = this._engine._currentFramebuffer;
            this._engine._bindUnboundFramebuffer(_);
            var k = d[this._engine.webGLVersion > 1 ? "COLOR_ATTACHMENT" + o : "COLOR_ATTACHMENT" + o + "_WEBGL"]
              , j = s !== -1 ? d.TEXTURE_CUBE_MAP_POSITIVE_X + s : d.TEXTURE_2D;
            d.framebufferTexture2D(d.FRAMEBUFFER, k, j, i._hardwareTexture.underlyingResource, c),
            this._engine._bindUnboundFramebuffer(b)
        }
    }
    ,
    e.prototype.setTexture = function(i, o, s) {
        o === void 0 && (o = 0),
        s === void 0 && (s = !0),
        a.prototype.setTexture.call(this, i, o, s),
        this._bindTextureRenderTarget(i, o)
    }
    ,
    e.prototype.dispose = function(i) {
        i === void 0 && (i = !1);
        var o = this._context;
        i || (this._colorTextureArray && (this._context.deleteTexture(this._colorTextureArray),
        this._colorTextureArray = null),
        this._depthStencilTextureArray && (this._context.deleteTexture(this._depthStencilTextureArray),
        this._depthStencilTextureArray = null)),
        this._framebuffer && (o.deleteFramebuffer(this._framebuffer),
        this._framebuffer = null),
        this._depthStencilBuffer && (o.deleteRenderbuffer(this._depthStencilBuffer),
        this._depthStencilBuffer = null),
        this._MSAAFramebuffer && (o.deleteFramebuffer(this._MSAAFramebuffer),
        this._MSAAFramebuffer = null),
        a.prototype.dispose.call(this, i)
    }
    ,
    e
}(RenderTargetWrapper);
ThinEngine.prototype._createHardwareRenderTargetWrapper = function(a, e, i) {
    var o = new WebGLRenderTargetWrapper(a,e,i,this,this._gl);
    return this._renderTargetWrapperCache.push(o),
    o
}
;
ThinEngine.prototype.createRenderTargetTexture = function(a, e) {
    var i = this._createHardwareRenderTargetWrapper(!1, !1, a)
      , o = {};
    e !== void 0 && typeof e == "object" ? (o.generateDepthBuffer = !!e.generateDepthBuffer,
    o.generateStencilBuffer = !!e.generateStencilBuffer) : (o.generateDepthBuffer = !0,
    o.generateStencilBuffer = !1);
    var s = this._createInternalTexture(a, e, !0, InternalTextureSource.RenderTarget)
      , c = a.width || a
      , d = a.height || a
      , _ = this._currentFramebuffer
      , b = this._gl
      , k = b.createFramebuffer();
    return this._bindUnboundFramebuffer(k),
    i._depthStencilBuffer = this._setupFramebufferDepthAttachments(!!o.generateStencilBuffer, o.generateDepthBuffer, c, d),
    s.is2DArray || b.framebufferTexture2D(b.FRAMEBUFFER, b.COLOR_ATTACHMENT0, b.TEXTURE_2D, s._hardwareTexture.underlyingResource, 0),
    this._bindUnboundFramebuffer(_),
    i._framebuffer = k,
    i._generateDepthBuffer = o.generateDepthBuffer,
    i._generateStencilBuffer = !!o.generateStencilBuffer,
    i.setTextures(s),
    i
}
;
ThinEngine.prototype.createDepthStencilTexture = function(a, e, i) {
    if (e.isCube) {
        var o = a.width || a;
        return this._createDepthStencilCubeTexture(o, e, i)
    } else
        return this._createDepthStencilTexture(a, e, i)
}
;
ThinEngine.prototype._createDepthStencilTexture = function(a, e, i) {
    var o = this._gl
      , s = a.layers || 0
      , c = s !== 0 ? o.TEXTURE_2D_ARRAY : o.TEXTURE_2D
      , d = new InternalTexture(this,InternalTextureSource.DepthStencil);
    if (!this._caps.depthTextureExtension)
        return Logger$2.Error("Depth texture is not supported by your browser or hardware."),
        d;
    var _ = __assign({
        bilinearFiltering: !1,
        comparisonFunction: 0,
        generateStencil: !1
    }, e);
    this._bindTextureDirectly(c, d, !0),
    this._setupDepthStencilTexture(d, a, _.generateStencil, _.comparisonFunction === 0 ? !1 : _.bilinearFiltering, _.comparisonFunction),
    i._depthStencilTexture = d,
    i._depthStencilTextureWithStencil = _.generateStencil;
    var b = _.generateStencil ? o.UNSIGNED_INT_24_8 : o.UNSIGNED_INT
      , k = _.generateStencil ? o.DEPTH_STENCIL : o.DEPTH_COMPONENT
      , j = k;
    return this.webGLVersion > 1 && (j = _.generateStencil ? o.DEPTH24_STENCIL8 : o.DEPTH_COMPONENT24),
    d.is2DArray ? o.texImage3D(c, 0, j, d.width, d.height, s, 0, k, b, null) : o.texImage2D(c, 0, j, d.width, d.height, 0, k, b, null),
    this._bindTextureDirectly(c, null),
    this._internalTexturesCache.push(d),
    d
}
;
ThinEngine.prototype.updateRenderTargetTextureSampleCount = function(a, e) {
    if (this.webGLVersion < 2 || !a || !a.texture)
        return 1;
    if (a.samples === e)
        return e;
    var i = this._gl;
    e = Math.min(e, this.getCaps().maxMSAASamples),
    a._depthStencilBuffer && (i.deleteRenderbuffer(a._depthStencilBuffer),
    a._depthStencilBuffer = null),
    a._MSAAFramebuffer && (i.deleteFramebuffer(a._MSAAFramebuffer),
    a._MSAAFramebuffer = null);
    var o = a.texture._hardwareTexture;
    if (o._MSAARenderBuffer && (i.deleteRenderbuffer(o._MSAARenderBuffer),
    o._MSAARenderBuffer = null),
    e > 1 && i.renderbufferStorageMultisample) {
        var s = i.createFramebuffer();
        if (!s)
            throw new Error("Unable to create multi sampled framebuffer");
        a._MSAAFramebuffer = s,
        this._bindUnboundFramebuffer(a._MSAAFramebuffer);
        var c = this._createRenderBuffer(a.texture.width, a.texture.height, e, -1, this._getRGBAMultiSampleBufferFormat(a.texture.type), i.COLOR_ATTACHMENT0, !1);
        if (!c)
            throw new Error("Unable to create multi sampled framebuffer");
        o._MSAARenderBuffer = c
    } else
        this._bindUnboundFramebuffer(a._framebuffer);
    return a.texture.samples = e,
    a._depthStencilBuffer = this._setupFramebufferDepthAttachments(a._generateStencilBuffer, a._generateDepthBuffer, a.texture.width, a.texture.height, e),
    this._bindUnboundFramebuffer(null),
    e
}
;
ThinEngine.prototype.createRenderTargetCubeTexture = function(a, e) {
    var i = this._createHardwareRenderTargetWrapper(!1, !0, a)
      , o = __assign({
        generateMipMaps: !0,
        generateDepthBuffer: !0,
        generateStencilBuffer: !1,
        type: 0,
        samplingMode: 3,
        format: 5
    }, e);
    o.generateStencilBuffer = o.generateDepthBuffer && o.generateStencilBuffer,
    (o.type === 1 && !this._caps.textureFloatLinearFiltering || o.type === 2 && !this._caps.textureHalfFloatLinearFiltering) && (o.samplingMode = 1);
    var s = this._gl
      , c = new InternalTexture(this,InternalTextureSource.RenderTarget);
    this._bindTextureDirectly(s.TEXTURE_CUBE_MAP, c, !0);
    var d = this._getSamplingParameters(o.samplingMode, o.generateMipMaps);
    o.type === 1 && !this._caps.textureFloat && (o.type = 0,
    Logger$2.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),
    s.texParameteri(s.TEXTURE_CUBE_MAP, s.TEXTURE_MAG_FILTER, d.mag),
    s.texParameteri(s.TEXTURE_CUBE_MAP, s.TEXTURE_MIN_FILTER, d.min),
    s.texParameteri(s.TEXTURE_CUBE_MAP, s.TEXTURE_WRAP_S, s.CLAMP_TO_EDGE),
    s.texParameteri(s.TEXTURE_CUBE_MAP, s.TEXTURE_WRAP_T, s.CLAMP_TO_EDGE);
    for (var _ = 0; _ < 6; _++)
        s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X + _, 0, this._getRGBABufferInternalSizedFormat(o.type, o.format), a, a, 0, this._getInternalFormat(o.format), this._getWebGLTextureType(o.type), null);
    var b = s.createFramebuffer();
    return this._bindUnboundFramebuffer(b),
    i._depthStencilBuffer = this._setupFramebufferDepthAttachments(o.generateStencilBuffer, o.generateDepthBuffer, a, a),
    o.generateMipMaps && s.generateMipmap(s.TEXTURE_CUBE_MAP),
    this._bindTextureDirectly(s.TEXTURE_CUBE_MAP, null),
    this._bindUnboundFramebuffer(null),
    i._framebuffer = b,
    i._generateDepthBuffer = o.generateDepthBuffer,
    i._generateStencilBuffer = o.generateStencilBuffer,
    c.width = a,
    c.height = a,
    c.isReady = !0,
    c.isCube = !0,
    c.samples = 1,
    c.generateMipMaps = o.generateMipMaps,
    c.samplingMode = o.samplingMode,
    c.type = o.type,
    c.format = o.format,
    this._internalTexturesCache.push(c),
    i.setTextures(c),
    i
}
;
var RenderTargetTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it) {
        d === void 0 && (d = !0),
        _ === void 0 && (_ = 0),
        b === void 0 && (b = !1),
        k === void 0 && (k = Texture.TRILINEAR_SAMPLINGMODE),
        j === void 0 && (j = !0),
        $ === void 0 && ($ = !1),
        _e === void 0 && (_e = !1),
        et === void 0 && (et = 5),
        tt === void 0 && (tt = !1);
        var nt, ot = a.call(this, null, s, !c, void 0, k, void 0, void 0, void 0, void 0, et) || this;
        if (ot.renderParticles = !0,
        ot.renderSprites = !1,
        ot.ignoreCameraViewport = !1,
        ot.onBeforeBindObservable = new Observable,
        ot.onAfterUnbindObservable = new Observable,
        ot.onBeforeRenderObservable = new Observable,
        ot.onAfterRenderObservable = new Observable,
        ot.onClearObservable = new Observable,
        ot.onResizeObservable = new Observable,
        ot._cleared = !1,
        ot.skipInitialClear = !1,
        ot._currentRefreshId = -1,
        ot._refreshRate = 1,
        ot._samples = 1,
        ot._canRescale = !0,
        ot._renderTarget = null,
        ot.boundingBoxPosition = Vector3.Zero(),
        s = ot.getScene(),
        !s)
            return ot;
        var at = ot.getScene().getEngine();
        return ot._coordinatesMode = Texture.PROJECTION_MODE,
        ot.renderList = new Array,
        ot.name = i,
        ot.isRenderTarget = !0,
        ot._initialSizeParameter = o,
        ot._renderPassIds = [],
        ot.__isCube = b,
        ot._processSizeParameter(o),
        ot.renderPassId = ot._renderPassIds[0],
        ot._resizeObserver = at.onResizeObservable.add(function() {}),
        ot._generateMipMaps = !!c,
        ot._doNotChangeAspectRatio = d,
        ot._renderingManager = new RenderingManager(s),
        ot._renderingManager._useSceneAutoClearSetup = !0,
        _e || (ot._renderTargetOptions = {
            generateMipMaps: c,
            type: _,
            format: (nt = ot._format) !== null && nt !== void 0 ? nt : void 0,
            samplingMode: ot.samplingMode,
            generateDepthBuffer: j,
            generateStencilBuffer: $,
            samples: rt,
            creationFlags: it
        },
        ot.samplingMode === Texture.NEAREST_SAMPLINGMODE && (ot.wrapU = Texture.CLAMP_ADDRESSMODE,
        ot.wrapV = Texture.CLAMP_ADDRESSMODE),
        tt || (b ? (ot._renderTarget = s.getEngine().createRenderTargetCubeTexture(ot.getRenderSize(), ot._renderTargetOptions),
        ot.coordinatesMode = Texture.INVCUBIC_MODE,
        ot._textureMatrix = Matrix.Identity()) : ot._renderTarget = s.getEngine().createRenderTargetTexture(ot._size, ot._renderTargetOptions),
        ot._texture = ot._renderTarget.texture,
        rt !== void 0 && (ot.samples = rt))),
        ot
    }
    return Object.defineProperty(e.prototype, "renderList", {
        get: function() {
            return this._renderList
        },
        set: function(i) {
            this._renderList = i,
            this._renderList && this._hookArray(this._renderList)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._hookArray = function(i) {
        var o = this
          , s = i.push;
        i.push = function() {
            for (var d, _ = [], b = 0; b < arguments.length; b++)
                _[b] = arguments[b];
            var k = i.length === 0
              , j = s.apply(i, _);
            return k && ((d = o.getScene()) === null || d === void 0 || d.meshes.forEach(function($) {
                $._markSubMeshesAsLightDirty()
            })),
            j
        }
        ;
        var c = i.splice;
        i.splice = function(d, _) {
            var b, k = c.apply(i, [d, _]);
            return i.length === 0 && ((b = o.getScene()) === null || b === void 0 || b.meshes.forEach(function(j) {
                j._markSubMeshesAsLightDirty()
            })),
            k
        }
    }
    ,
    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(i) {
            this._onAfterUnbindObserver && this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),
            this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onBeforeRender", {
        set: function(i) {
            this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),
            this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onAfterRender", {
        set: function(i) {
            this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver),
            this._onAfterRenderObserver = this.onAfterRenderObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onClear", {
        set: function(i) {
            this._onClearObserver && this.onClearObservable.remove(this._onClearObserver),
            this._onClearObserver = this.onClearObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "renderPassIds", {
        get: function() {
            return this._renderPassIds
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setMaterialForRendering = function(i, o) {
        var s;
        Array.isArray(i) ? s = i : s = [i];
        for (var c = 0; c < s.length; ++c)
            for (var d = 0; d < this._renderPassIds.length; ++d)
                s[c].setMaterialForRenderPass(this._renderPassIds[d], o !== void 0 ? Array.isArray(o) ? o[d] : o : 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(i) {
            if (!(this._boundingBoxSize && this._boundingBoxSize.equals(i))) {
                this._boundingBoxSize = i;
                var o = this.getScene();
                o && o.markAllMaterialsAsDirty(1)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthStencilTexture", {
        get: function() {
            var i, o;
            return (o = (i = this._renderTarget) === null || i === void 0 ? void 0 : i._depthStencilTexture) !== null && o !== void 0 ? o : null
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.createDepthStencilTexture = function(i, o, s, c) {
        var d;
        i === void 0 && (i = 0),
        o === void 0 && (o = !0),
        s === void 0 && (s = !1),
        c === void 0 && (c = 1),
        (d = this._renderTarget) === null || d === void 0 || d.createDepthStencilTexture(i, o, s, c)
    }
    ,
    e.prototype._releaseRenderPassId = function() {
        if (this._scene)
            for (var i = this._scene.getEngine(), o = 0; o < this._renderPassIds.length; ++o)
                i.releaseRenderPassId(this._renderPassIds[o]);
        this._renderPassIds = []
    }
    ,
    e.prototype._createRenderPassId = function() {
        this._releaseRenderPassId();
        for (var i = this._scene.getEngine(), o = this.__isCube ? 6 : this.getRenderLayers() || 1, s = 0; s < o; ++s)
            this._renderPassIds[s] = i.createRenderPassId("RenderTargetTexture - " + this.name + "#" + s)
    }
    ,
    e.prototype._processSizeParameter = function(i) {
        if (i.ratio) {
            this._sizeRatio = i.ratio;
            var o = this._getEngine();
            this._size = {
                width: this._bestReflectionRenderTargetDimension(o.getRenderWidth(), this._sizeRatio),
                height: this._bestReflectionRenderTargetDimension(o.getRenderHeight(), this._sizeRatio)
            }
        } else
            this._size = i;
        this._createRenderPassId()
    }
    ,
    Object.defineProperty(e.prototype, "samples", {
        get: function() {
            var i, o;
            return (o = (i = this._renderTarget) === null || i === void 0 ? void 0 : i.samples) !== null && o !== void 0 ? o : this._samples
        },
        set: function(i) {
            this._renderTarget && (this._samples = this._renderTarget.setSamples(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.resetRefreshCounter = function() {
        this._currentRefreshId = -1
    }
    ,
    Object.defineProperty(e.prototype, "refreshRate", {
        get: function() {
            return this._refreshRate
        },
        set: function(i) {
            this._refreshRate = i,
            this.resetRefreshCounter()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addPostProcess = function(i) {
        if (!this._postProcessManager) {
            var o = this.getScene();
            if (!o)
                return;
            this._postProcessManager = new PostProcessManager(o),
            this._postProcesses = new Array
        }
        this._postProcesses.push(i),
        this._postProcesses[0].autoClear = !1
    }
    ,
    e.prototype.clearPostProcesses = function(i) {
        if (i === void 0 && (i = !1),
        !!this._postProcesses) {
            if (i)
                for (var o = 0, s = this._postProcesses; o < s.length; o++) {
                    var c = s[o];
                    c.dispose()
                }
            this._postProcesses = []
        }
    }
    ,
    e.prototype.removePostProcess = function(i) {
        if (!!this._postProcesses) {
            var o = this._postProcesses.indexOf(i);
            o !== -1 && (this._postProcesses.splice(o, 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 i = this._size.layers;
        return i || 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(i) {
        var o = Math.max(1, this.getRenderSize() * i);
        this.resize(o)
    }
    ,
    e.prototype.getReflectionTextureMatrix = function() {
        return this.isCube ? this._textureMatrix : a.prototype.getReflectionTextureMatrix.call(this)
    }
    ,
    e.prototype.resize = function(i) {
        var o, s = this.isCube;
        (o = this._renderTarget) === null || o === void 0 || o.dispose(),
        this._renderTarget = null;
        var c = this.getScene();
        !c || (this._processSizeParameter(i),
        s ? this._renderTarget = c.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions) : this._renderTarget = c.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(i, o) {
        i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        this._render(i, o)
    }
    ,
    e.prototype.isReadyForRendering = function() {
        return this._render(!1, !1, !0)
    }
    ,
    e.prototype._render = function(i, o, s) {
        var c;
        i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        s === void 0 && (s = !1);
        var d = this.getScene();
        if (!d)
            return s;
        var _ = d.getEngine();
        if (this.useCameraPostProcesses !== void 0 && (i = this.useCameraPostProcesses),
        this._waitingRenderList) {
            this.renderList = [];
            for (var b = 0; b < this._waitingRenderList.length; b++) {
                var k = this._waitingRenderList[b]
                  , j = d.getMeshById(k);
                j && this.renderList.push(j)
            }
            this._waitingRenderList = void 0
        }
        if (this.renderListPredicate) {
            this.renderList ? this.renderList.length = 0 : this.renderList = [];
            var d = this.getScene();
            if (!d)
                return s;
            for (var $ = d.meshes, b = 0; b < $.length; b++) {
                var _e = $[b];
                this.renderListPredicate(_e) && this.renderList.push(_e)
            }
        }
        var et = _.currentRenderPassId;
        this.onBeforeBindObservable.notifyObservers(this);
        var tt = (c = this.activeCamera) !== null && c !== void 0 ? c : d.activeCamera;
        tt && (tt !== d.activeCamera && d.setTransformMatrix(tt.getViewMatrix(), tt.getProjectionMatrix(!0)),
        _.setViewport(tt.viewport, this.getRenderWidth(), this.getRenderHeight())),
        this._defaultRenderListPrepared = !1;
        var rt = s;
        if (s) {
            d.getViewMatrix() || d.updateTransformMatrix();
            for (var ot = this.is2DArray ? this.getRenderLayers() : this.isCube ? 6 : 1, it = 0; it < ot && rt; it++) {
                var at = null
                  , st = this.renderList ? this.renderList : d.getActiveMeshes().data
                  , ut = this.renderList ? this.renderList.length : d.getActiveMeshes().length;
                _.currentRenderPassId = this._renderPassIds[it],
                this.onBeforeRenderObservable.notifyObservers(it),
                this.getCustomRenderList && (at = this.getCustomRenderList(it, st, ut)),
                at || (at = st),
                this._doNotChangeAspectRatio || d.updateTransformMatrix(!0);
                for (var ct = 0; ct < at.length && rt; ++ct) {
                    var lt = at[ct];
                    if (!(!lt.isEnabled() || lt.isBlocked || !lt.isVisible || !lt.subMeshes)) {
                        if (this.customIsReadyFunction) {
                            if (!this.customIsReadyFunction(lt, this.refreshRate)) {
                                rt = !1;
                                break
                            }
                        } else if (!lt.isReady(!0)) {
                            rt = !1;
                            break
                        }
                    }
                }
                this.onAfterRenderObservable.notifyObservers(it)
            }
        } else if (this.is2DArray)
            for (var it = 0; it < this.getRenderLayers(); it++)
                this.renderToTarget(0, i, o, it, tt),
                d.incrementRenderId(),
                d.resetCachedMaterial();
        else if (this.isCube)
            for (var nt = 0; nt < 6; nt++)
                this.renderToTarget(nt, i, o, void 0, tt),
                d.incrementRenderId(),
                d.resetCachedMaterial();
        else
            this.renderToTarget(0, i, o, void 0, tt);
        return this.onAfterUnbindObservable.notifyObservers(this),
        _.currentRenderPassId = et,
        d.activeCamera && ((d.getEngine().scenes.length > 1 || this.activeCamera && this.activeCamera !== d.activeCamera) && d.setTransformMatrix(d.activeCamera.getViewMatrix(), d.activeCamera.getProjectionMatrix(!0)),
        _.setViewport(d.activeCamera.viewport)),
        d.resetCachedMaterial(),
        rt
    }
    ,
    e.prototype._bestReflectionRenderTargetDimension = function(i, o) {
        var s = 128
          , c = i * o
          , d = Engine.NearestPOT(c + s * s / (s + c));
        return Math.min(Engine.FloorPOT(i), d)
    }
    ,
    e.prototype._prepareRenderingManager = function(i, o, s, c) {
        var d = this.getScene();
        if (!!d) {
            this._renderingManager.reset();
            for (var _ = d.getRenderId(), b = 0; b < o; b++) {
                var k = i[b];
                if (k && !k.isBlocked) {
                    if (this.customIsReadyFunction) {
                        if (!this.customIsReadyFunction(k, this.refreshRate)) {
                            this.resetRefreshCounter();
                            continue
                        }
                    } else if (!k.isReady(this.refreshRate === 0)) {
                        this.resetRefreshCounter();
                        continue
                    }
                    if (!k._internalAbstractMeshDataInfo._currentLODIsUpToDate && d.activeCamera && (k._internalAbstractMeshDataInfo._currentLOD = d.customLODSelector ? d.customLODSelector(k, this.activeCamera || d.activeCamera) : k.getLOD(this.activeCamera || d.activeCamera),
                    k._internalAbstractMeshDataInfo._currentLODIsUpToDate = !0),
                    !k._internalAbstractMeshDataInfo._currentLOD)
                        continue;
                    var j = k._internalAbstractMeshDataInfo._currentLOD;
                    j._preActivateForIntermediateRendering(_);
                    var $ = void 0;
                    if (c && s ? $ = (k.layerMask & s.layerMask) === 0 : $ = !1,
                    k.isEnabled() && k.isVisible && k.subMeshes && !$ && (j !== k && j._activate(_, !0),
                    k._activate(_, !0) && k.subMeshes.length)) {
                        k.isAnInstance ? k._internalAbstractMeshDataInfo._actAsRegularMesh && (j = k) : j._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = !1,
                        j._internalAbstractMeshDataInfo._isActiveIntermediate = !0;
                        for (var _e = 0; _e < j.subMeshes.length; _e++) {
                            var et = j.subMeshes[_e];
                            this._renderingManager.dispatch(et, j)
                        }
                    }
                }
            }
            for (var tt = 0; tt < d.particleSystems.length; tt++) {
                var rt = d.particleSystems[tt]
                  , it = rt.emitter;
                !rt.isStarted() || !it || !it.position || !it.isEnabled() || i.indexOf(it) >= 0 && this._renderingManager.dispatchParticles(rt)
            }
        }
    }
    ,
    e.prototype._bindFrameBuffer = function(i, o) {
        i === void 0 && (i = 0),
        o === void 0 && (o = 0);
        var s = this.getScene();
        if (!!s) {
            var c = s.getEngine();
            this._renderTarget && c.bindFramebuffer(this._renderTarget, this.isCube ? i : void 0, void 0, void 0, this.ignoreCameraViewport, 0, o)
        }
    }
    ,
    e.prototype.unbindFrameBuffer = function(i, o) {
        var s = this;
        !this._renderTarget || i.unBindFramebuffer(this._renderTarget, this.isCube, function() {
            s.onAfterRenderObservable.notifyObservers(o)
        })
    }
    ,
    e.prototype._prepareFrame = function(i, o, s, c) {
        this._postProcessManager ? this._prePassEnabled || this._postProcessManager._prepareFrame(this._texture, this._postProcesses) : (!c || !i.postProcessManager._prepareFrame(this._texture)) && this._bindFrameBuffer(o, s)
    }
    ,
    e.prototype.renderToTarget = function(i, o, s, c, d) {
        var _, b, k, j;
        c === void 0 && (c = 0),
        d === void 0 && (d = null);
        var $ = this.getScene();
        if (!!$) {
            var _e = $.getEngine();
            if (!!this._texture) {
                (_ = _e._debugPushGroup) === null || _ === void 0 || _.call(_e, "render to face #" + i + " layer #" + c, 1),
                this._prepareFrame($, i, c, o),
                this.is2DArray ? (_e.currentRenderPassId = this._renderPassIds[c],
                this.onBeforeRenderObservable.notifyObservers(c)) : (_e.currentRenderPassId = this._renderPassIds[i],
                this.onBeforeRenderObservable.notifyObservers(i));
                var et = _e.snapshotRendering && _e.snapshotRenderingMode === 1;
                if (et)
                    this.onClearObservable.hasObservers() ? this.onClearObservable.notifyObservers(_e) : this.skipInitialClear || _e.clear(this.clearColor || $.clearColor, !0, !0, !0);
                else {
                    var tt = null
                      , rt = this.renderList ? this.renderList : $.getActiveMeshes().data
                      , it = this.renderList ? this.renderList.length : $.getActiveMeshes().length;
                    this.getCustomRenderList && (tt = this.getCustomRenderList(this.is2DArray ? c : i, rt, it)),
                    tt ? this._prepareRenderingManager(tt, tt.length, d, !1) : (this._defaultRenderListPrepared || (this._prepareRenderingManager(rt, it, d, !this.renderList),
                    this._defaultRenderListPrepared = !0),
                    tt = rt);
                    for (var nt = 0, ot = $._beforeRenderTargetClearStage; nt < ot.length; nt++) {
                        var at = ot[nt];
                        at.action(this, i, c)
                    }
                    this.onClearObservable.hasObservers() ? this.onClearObservable.notifyObservers(_e) : this.skipInitialClear || _e.clear(this.clearColor || $.clearColor, !0, !0, !0),
                    this._doNotChangeAspectRatio || $.updateTransformMatrix(!0);
                    for (var st = 0, ut = $._beforeRenderTargetDrawStage; st < ut.length; st++) {
                        var at = ut[st];
                        at.action(this, i, c)
                    }
                    this._renderingManager.render(this.customRenderFunction, tt, this.renderParticles, this.renderSprites);
                    for (var ct = 0, lt = $._afterRenderTargetDrawStage; ct < lt.length; ct++) {
                        var at = lt[ct];
                        at.action(this, i, c)
                    }
                    var ft = this._texture.generateMipMaps;
                    this._texture.generateMipMaps = !1,
                    this._postProcessManager ? this._postProcessManager._finalizeFrame(!1, (b = this._renderTarget) !== null && b !== void 0 ? b : void 0, i, this._postProcesses, this.ignoreCameraViewport) : o && $.postProcessManager._finalizeFrame(!1, (k = this._renderTarget) !== null && k !== void 0 ? k : void 0, i),
                    this._texture.generateMipMaps = ft,
                    this._doNotChangeAspectRatio || $.updateTransformMatrix(!0),
                    s && Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), _e)
                }
                this.unbindFrameBuffer(_e, i),
                this.isCube && i === 5 && _e.generateMipMapsForCubemap(this._texture),
                (j = _e._debugPopGroup) === null || j === void 0 || j.call(_e, 1)
            }
        }
    }
    ,
    e.prototype.setRenderingOrder = function(i, o, s, c) {
        o === void 0 && (o = null),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        this._renderingManager.setRenderingOrder(i, o, s, c)
    }
    ,
    e.prototype.setRenderingAutoClearDepthStencil = function(i, o) {
        this._renderingManager.setRenderingAutoClearDepthStencil(i, o),
        this._renderingManager._useSceneAutoClearSetup = !1
    }
    ,
    e.prototype.clone = function() {
        var i = this.getSize()
          , o = new e(this.name,i,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 o.hasAlpha = this.hasAlpha,
        o.level = this.level,
        o.coordinatesMode = this.coordinatesMode,
        this.renderList && (o.renderList = this.renderList.slice(0)),
        o
    }
    ,
    e.prototype.serialize = function() {
        if (!this.name)
            return null;
        var i = a.prototype.serialize.call(this);
        if (i.renderTargetSize = this.getRenderSize(),
        i.renderList = [],
        this.renderList)
            for (var o = 0; o < this.renderList.length; o++)
                i.renderList.push(this.renderList[o].id);
        return i
    }
    ,
    e.prototype.disposeFramebufferObjects = function() {
        var i;
        (i = this._renderTarget) === null || i === void 0 || i.dispose(!0)
    }
    ,
    e.prototype.releaseInternalTexture = function() {
        var i;
        (i = this._renderTarget) === null || i === void 0 || i.releaseTextures(),
        this._texture = null
    }
    ,
    e.prototype.dispose = function() {
        var i;
        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 o = this.getScene();
        if (!!o) {
            var s = o.customRenderTargets.indexOf(this);
            s >= 0 && o.customRenderTargets.splice(s, 1);
            for (var c = 0, d = o.cameras; c < d.length; c++) {
                var _ = d[c];
                s = _.customRenderTargets.indexOf(this),
                s >= 0 && _.customRenderTargets.splice(s, 1)
            }
            (i = this._renderTarget) === null || i === void 0 || i.dispose(),
            this._renderTarget = null,
            this._texture = null,
            a.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(a, e, i, o, s) {
    return new RenderTargetTexture(a,e,i,o)
}
;
var MultiviewRenderTarget = function(a) {
    __extends(e, a);
    function e(i, o) {
        o === void 0 && (o = 512);
        var s = a.call(this, "multiview rtt", o, i, !1, !0, 0, !1, void 0, !1, !1, !0, void 0, !0) || this
          , c = i.getEngine().createMultiviewRenderTargetTexture(s.getRenderWidth(), s.getRenderHeight());
        return s._texture = c.texture,
        s._texture.isMultiview = !0,
        s._texture.format = 5,
        s.samples = s._getEngine().getCaps().maxSamples || s.samples,
        s
    }
    return e.prototype._bindFrameBuffer = function(i) {
        !this._renderTarget || this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)
    }
    ,
    e.prototype.getViewCount = function() {
        return 2
    }
    ,
    e
}(RenderTargetTexture);
Engine.prototype.createMultiviewRenderTargetTexture = function(a, e) {
    var i = this._gl;
    if (!this.getCaps().multiview)
        throw "Multiview is not supported";
    var o = this._createHardwareRenderTargetWrapper(!1, !1, {
        width: a,
        height: e
    });
    o._framebuffer = i.createFramebuffer();
    var s = new InternalTexture(this,InternalTextureSource.Unknown,!0);
    return s.width = a,
    s.height = e,
    o._colorTextureArray = i.createTexture(),
    i.bindTexture(i.TEXTURE_2D_ARRAY, o._colorTextureArray),
    i.texStorage3D(i.TEXTURE_2D_ARRAY, 1, i.RGBA8, a, e, 2),
    o._depthStencilTextureArray = i.createTexture(),
    i.bindTexture(i.TEXTURE_2D_ARRAY, o._depthStencilTextureArray),
    i.texStorage3D(i.TEXTURE_2D_ARRAY, 1, i.DEPTH32F_STENCIL8, a, e, 2),
    s.isReady = !0,
    o.setTextures(s),
    o
}
;
Engine.prototype.bindMultiviewFramebuffer = function(a) {
    var e = a
      , i = this._gl
      , o = this.getCaps().oculusMultiview || this.getCaps().multiview;
    if (this.bindFramebuffer(e, void 0, void 0, void 0, !0),
    i.bindFramebuffer(i.DRAW_FRAMEBUFFER, e._framebuffer),
    e._colorTextureArray && e._depthStencilTextureArray)
        this.getCaps().oculusMultiview ? (o.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER, i.COLOR_ATTACHMENT0, e._colorTextureArray, 0, e.samples, 0, 2),
        o.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER, i.DEPTH_STENCIL_ATTACHMENT, e._depthStencilTextureArray, 0, e.samples, 0, 2)) : (o.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER, i.COLOR_ATTACHMENT0, e._colorTextureArray, 0, 0, 2),
        o.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER, i.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(a, e) {
    this._multiviewTexture ? (this._multiviewTexture.getRenderWidth() != a || this._multiviewTexture.getRenderHeight() != e) && (this._multiviewTexture.dispose(),
    this._multiviewTexture = new MultiviewRenderTarget(this.getScene(),{
        width: a,
        height: e
    })) : this._multiviewTexture = new MultiviewRenderTarget(this.getScene(),{
        width: a,
        height: e
    })
}
;
function createMultiviewUbo(a, e) {
    var i = new UniformBuffer(a,void 0,!0,e);
    return i.addUniform("viewProjection", 16),
    i.addUniform("viewProjectionR", 16),
    i.addUniform("view", 16),
    i.addUniform("projection", 16),
    i.addUniform("viewPosition", 4),
    i
}
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(a) {
    return this._multiviewSceneUbo ? createMultiviewUbo(this.getEngine(), a) : currentCreateSceneUniformBuffer.bind(this)(a)
}
;
Scene.prototype._updateMultiviewUbo = function(a, e) {
    a && e && a.multiplyToRef(e, this._transformMatrixR),
    a && e && (a.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(a) {
    a._resizeOrCreateMultiviewTexture(a._rigPostProcess && a._rigPostProcess && a._rigPostProcess.width > 0 ? a._rigPostProcess.width : this.getEngine().getRenderWidth(!0), a._rigPostProcess && a._rigPostProcess && a._rigPostProcess.height > 0 ? a._rigPostProcess.height : this.getEngine().getRenderHeight(!0)),
    this._multiviewSceneUbo || this._createMultiviewUbo(),
    a.outputRenderTarget = a._multiviewTexture,
    this._renderForCamera(a),
    a.outputRenderTarget = null;
    for (var e = 0; e < a._rigCameras.length; e++) {
        var i = this.getEngine();
        this._activeCamera = a._rigCameras[e],
        i.setViewport(this._activeCamera.viewport),
        this.postProcessManager && (this.postProcessManager._prepareFrame(),
        this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))
    }
}
;
ThinEngine.prototype.updateRawTexture = function(a, e, i, o, s, c) {
    if (s === void 0 && (s = null),
    c === void 0 && (c = 0),
    !!a) {
        var d = this._getRGBABufferInternalSizedFormat(c, i)
          , _ = this._getInternalFormat(i)
          , b = this._getWebGLTextureType(c);
        this._bindTextureDirectly(this._gl.TEXTURE_2D, a, !0),
        this._unpackFlipY(o === void 0 ? !0 : !!o),
        this._doNotHandleContextLost || (a._bufferView = e,
        a.format = i,
        a.type = c,
        a.invertY = o,
        a._compression = s),
        a.width % 4 !== 0 && this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1),
        s && e ? this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[s], a.width, a.height, 0, e) : this._gl.texImage2D(this._gl.TEXTURE_2D, 0, d, a.width, a.height, 0, _, b, e),
        a.generateMipMaps && this._gl.generateMipmap(this._gl.TEXTURE_2D),
        this._bindTextureDirectly(this._gl.TEXTURE_2D, null),
        a.isReady = !0
    }
}
;
ThinEngine.prototype.createRawTexture = function(a, e, i, o, s, c, d, _, b, k) {
    _ === void 0 && (_ = null),
    b === void 0 && (b = 0);
    var j = new InternalTexture(this,InternalTextureSource.Raw);
    j.baseWidth = e,
    j.baseHeight = i,
    j.width = e,
    j.height = i,
    j.format = o,
    j.generateMipMaps = s,
    j.samplingMode = d,
    j.invertY = c,
    j._compression = _,
    j.type = b,
    this._doNotHandleContextLost || (j._bufferView = a),
    this.updateRawTexture(j, a, o, c, _, b),
    this._bindTextureDirectly(this._gl.TEXTURE_2D, j, !0);
    var $ = this._getSamplingParameters(d, s);
    return this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, $.mag),
    this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, $.min),
    s && this._gl.generateMipmap(this._gl.TEXTURE_2D),
    this._bindTextureDirectly(this._gl.TEXTURE_2D, null),
    this._internalTexturesCache.push(j),
    j
}
;
ThinEngine.prototype.createRawCubeTexture = function(a, e, i, o, s, c, d, _) {
    _ === void 0 && (_ = null);
    var b = this._gl
      , k = new InternalTexture(this,InternalTextureSource.CubeRaw);
    k.isCube = !0,
    k.format = i,
    k.type = o,
    this._doNotHandleContextLost || (k._bufferViewArray = a);
    var j = this._getWebGLTextureType(o)
      , $ = this._getInternalFormat(i);
    $ === b.RGB && ($ = b.RGBA),
    j === b.FLOAT && !this._caps.textureFloatLinearFiltering ? (s = !1,
    d = 1,
    Logger$2.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")) : j === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering ? (s = !1,
    d = 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.")) : j === b.FLOAT && !this._caps.textureFloatRender ? (s = !1,
    Logger$2.Warn("Render to float textures is not supported. Mipmap generation forced to false.")) : j === b.HALF_FLOAT && !this._caps.colorBufferFloat && (s = !1,
    Logger$2.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));
    var _e = e
      , et = _e;
    k.width = _e,
    k.height = et;
    var tt = !this.needPOTTextures || Tools.IsExponentOfTwo(k.width) && Tools.IsExponentOfTwo(k.height);
    tt || (s = !1),
    a && this.updateRawCubeTexture(k, a, i, o, c, _),
    this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, k, !0),
    a && s && this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
    var rt = this._getSamplingParameters(d, s);
    return b.texParameteri(b.TEXTURE_CUBE_MAP, b.TEXTURE_MAG_FILTER, rt.mag),
    b.texParameteri(b.TEXTURE_CUBE_MAP, b.TEXTURE_MIN_FILTER, rt.min),
    b.texParameteri(b.TEXTURE_CUBE_MAP, b.TEXTURE_WRAP_S, b.CLAMP_TO_EDGE),
    b.texParameteri(b.TEXTURE_CUBE_MAP, b.TEXTURE_WRAP_T, b.CLAMP_TO_EDGE),
    this._bindTextureDirectly(b.TEXTURE_CUBE_MAP, null),
    k.generateMipMaps = s,
    k.samplingMode = d,
    k
}
;
ThinEngine.prototype.updateRawCubeTexture = function(a, e, i, o, s, c, d) {
    c === void 0 && (c = null),
    d === void 0 && (d = 0),
    a._bufferViewArray = e,
    a.format = i,
    a.type = o,
    a.invertY = s,
    a._compression = c;
    var _ = this._gl
      , b = this._getWebGLTextureType(o)
      , k = this._getInternalFormat(i)
      , j = this._getRGBABufferInternalSizedFormat(o)
      , $ = !1;
    k === _.RGB && (k = _.RGBA,
    $ = !0),
    this._bindTextureDirectly(_.TEXTURE_CUBE_MAP, a, !0),
    this._unpackFlipY(s === void 0 ? !0 : !!s),
    a.width % 4 !== 0 && _.pixelStorei(_.UNPACK_ALIGNMENT, 1);
    for (var _e = 0; _e < 6; _e++) {
        var et = e[_e];
        c ? _.compressedTexImage2D(_.TEXTURE_CUBE_MAP_POSITIVE_X + _e, d, this.getCaps().s3tc[c], a.width, a.height, 0, et) : ($ && (et = _convertRGBtoRGBATextureData$1(et, a.width, a.height, o)),
        _.texImage2D(_.TEXTURE_CUBE_MAP_POSITIVE_X + _e, d, j, a.width, a.height, 0, k, b, et))
    }
    var tt = !this.needPOTTextures || Tools.IsExponentOfTwo(a.width) && Tools.IsExponentOfTwo(a.height);
    tt && a.generateMipMaps && d === 0 && this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),
    this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null),
    a.isReady = !0
}
;
ThinEngine.prototype.createRawCubeTextureFromUrl = function(a, e, i, o, s, c, d, _, b, k, j, $) {
    var _e = this;
    b === void 0 && (b = null),
    k === void 0 && (k = null),
    j === void 0 && (j = 3),
    $ === void 0 && ($ = !1);
    var et = this._gl
      , tt = this.createRawCubeTexture(null, i, o, s, !c, $, j, null);
    e == null || e._addPendingData(tt),
    tt.url = a,
    this._internalTexturesCache.push(tt);
    var rt = function(nt, ot) {
        e == null || e._removePendingData(tt),
        k && nt && k(nt.status + " " + nt.statusText, ot)
    }
      , it = function(nt) {
        var ot = tt.width
          , at = d(nt);
        if (!!at) {
            if (_) {
                var st = _e._getWebGLTextureType(s)
                  , ut = _e._getInternalFormat(o)
                  , ct = _e._getRGBABufferInternalSizedFormat(s)
                  , lt = !1;
                ut === et.RGB && (ut = et.RGBA,
                lt = !0),
                _e._bindTextureDirectly(et.TEXTURE_CUBE_MAP, tt, !0),
                _e._unpackFlipY(!1);
                for (var ft = _(at), ht = 0; ht < ft.length; ht++)
                    for (var pt = ot >> ht, dt = 0; dt < 6; dt++) {
                        var _t = ft[ht][dt];
                        lt && (_t = _convertRGBtoRGBATextureData$1(_t, pt, pt, s)),
                        et.texImage2D(dt, ht, ct, pt, pt, 0, ut, st, _t)
                    }
                _e._bindTextureDirectly(et.TEXTURE_CUBE_MAP, null)
            } else
                _e.updateRawCubeTexture(tt, at, o, s, $);
            tt.isReady = !0,
            e == null || e._removePendingData(tt),
            b && b()
        }
    };
    return this._loadFile(a, function(nt) {
        it(nt)
    }, void 0, e == null ? void 0 : e.offlineProvider, !0, rt),
    tt
}
;
function _convertRGBtoRGBATextureData$1(a, e, i, o) {
    var s, c = 1;
    o === 1 ? s = new Float32Array(e * i * 4) : o === 2 ? (s = new Uint16Array(e * i * 4),
    c = 15360) : o === 7 ? s = new Uint32Array(e * i * 4) : s = new Uint8Array(e * i * 4);
    for (var d = 0; d < e; d++)
        for (var _ = 0; _ < i; _++) {
            var b = (_ * e + d) * 3
              , k = (_ * e + d) * 4;
            s[k + 0] = a[b + 0],
            s[k + 1] = a[b + 1],
            s[k + 2] = a[b + 2],
            s[k + 3] = c
        }
    return s
}
function _makeCreateRawTextureFunction(a) {
    return function(e, i, o, s, c, d, _, b, k, j) {
        k === void 0 && (k = null),
        j === void 0 && (j = 0);
        var $ = a ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY
          , _e = a ? InternalTextureSource.Raw3D : InternalTextureSource.Raw2DArray
          , et = new InternalTexture(this,_e);
        et.baseWidth = i,
        et.baseHeight = o,
        et.baseDepth = s,
        et.width = i,
        et.height = o,
        et.depth = s,
        et.format = c,
        et.type = j,
        et.generateMipMaps = d,
        et.samplingMode = b,
        a ? et.is3D = !0 : et.is2DArray = !0,
        this._doNotHandleContextLost || (et._bufferView = e),
        a ? this.updateRawTexture3D(et, e, c, _, k, j) : this.updateRawTexture2DArray(et, e, c, _, k, j),
        this._bindTextureDirectly($, et, !0);
        var tt = this._getSamplingParameters(b, d);
        return this._gl.texParameteri($, this._gl.TEXTURE_MAG_FILTER, tt.mag),
        this._gl.texParameteri($, this._gl.TEXTURE_MIN_FILTER, tt.min),
        d && this._gl.generateMipmap($),
        this._bindTextureDirectly($, null),
        this._internalTexturesCache.push(et),
        et
    }
}
ThinEngine.prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(!1);
ThinEngine.prototype.createRawTexture3D = _makeCreateRawTextureFunction(!0);
function _makeUpdateRawTextureFunction(a) {
    return function(e, i, o, s, c, d) {
        c === void 0 && (c = null),
        d === void 0 && (d = 0);
        var _ = a ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY
          , b = this._getWebGLTextureType(d)
          , k = this._getInternalFormat(o)
          , j = this._getRGBABufferInternalSizedFormat(d, o);
        this._bindTextureDirectly(_, e, !0),
        this._unpackFlipY(s === void 0 ? !0 : !!s),
        this._doNotHandleContextLost || (e._bufferView = i,
        e.format = o,
        e.invertY = s,
        e._compression = c),
        e.width % 4 !== 0 && this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1),
        c && i ? this._gl.compressedTexImage3D(_, 0, this.getCaps().s3tc[c], e.width, e.height, e.depth, 0, i) : this._gl.texImage3D(_, 0, j, e.width, e.height, e.depth, 0, k, b, i),
        e.generateMipMaps && this._gl.generateMipmap(_),
        this._bindTextureDirectly(_, null),
        e.isReady = !0
    }
}
ThinEngine.prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(!1);
ThinEngine.prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(!0);
ThinEngine.prototype.createDynamicTexture = function(a, e, i, o) {
    var s = new InternalTexture(this,InternalTextureSource.Dynamic);
    return s.baseWidth = a,
    s.baseHeight = e,
    i && (a = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(a, this._caps.maxTextureSize) : a,
    e = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(e, this._caps.maxTextureSize) : e),
    s.width = a,
    s.height = e,
    s.isReady = !1,
    s.generateMipMaps = i,
    s.samplingMode = o,
    this.updateTextureSamplingMode(o, s),
    this._internalTexturesCache.push(s),
    s
}
;
ThinEngine.prototype.updateDynamicTexture = function(a, e, i, o, s, c, d) {
    if (o === void 0 && (o = !1),
    c === void 0 && (c = !1),
    !!a) {
        var _ = this._gl
          , b = _.TEXTURE_2D
          , k = this._bindTextureDirectly(b, a, !0, c);
        this._unpackFlipY(i === void 0 ? a.invertY : i),
        o && _.pixelStorei(_.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
        var j = this._getWebGLTextureType(a.type)
          , $ = this._getInternalFormat(s || a.format)
          , _e = this._getRGBABufferInternalSizedFormat(a.type, $);
        _.texImage2D(b, 0, _e, $, j, e),
        a.generateMipMaps && _.generateMipmap(b),
        k || this._bindTextureDirectly(b, null),
        o && _.pixelStorei(_.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0),
        a.isReady = !0
    }
}
;
ThinEngine.prototype.createExternalTexture = function(a) {
    return null
}
;
ThinEngine.prototype.setExternalTexture = function(a, e) {
    throw new Error("setExternalTexture: This engine does not support external textures!")
}
;
ThinEngine.prototype.updateVideoTexture = function(a, e, i) {
    if (!(!a || a._isDisabled)) {
        var o = this._bindTextureDirectly(this._gl.TEXTURE_2D, a, !0);
        this._unpackFlipY(!i);
        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 (!a._workingCanvas) {
                    a._workingCanvas = this.createCanvas(a.width, a.height);
                    var s = a._workingCanvas.getContext("2d");
                    if (!s)
                        throw new Error("Unable to get 2d context");
                    a._workingContext = s,
                    a._workingCanvas.width = a.width,
                    a._workingCanvas.height = a.height
                }
                a._workingContext.clearRect(0, 0, a.width, a.height),
                a._workingContext.drawImage(e, 0, 0, e.videoWidth, e.videoHeight, 0, 0, a.width, a.height),
                this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, a._workingCanvas)
            }
            a.generateMipMaps && this._gl.generateMipmap(this._gl.TEXTURE_2D),
            o || this._bindTextureDirectly(this._gl.TEXTURE_2D, null),
            a.isReady = !0
        } catch {
            a._isDisabled = !0
        }
    }
}
;
ThinEngine.prototype.restoreSingleAttachment = function() {
    var a = this._gl;
    this.bindAttachments([a.BACK])
}
;
ThinEngine.prototype.restoreSingleAttachmentForRenderTarget = function() {
    var a = this._gl;
    this.bindAttachments([a.COLOR_ATTACHMENT0])
}
;
ThinEngine.prototype.buildTextureLayout = function(a) {
    for (var e = this._gl, i = [], o = 0; o < a.length; o++)
        a[o] ? i.push(e["COLOR_ATTACHMENT" + o]) : i.push(e.NONE);
    return i
}
;
ThinEngine.prototype.bindAttachments = function(a) {
    var e = this._gl;
    e.drawBuffers(a)
}
;
ThinEngine.prototype.unBindMultiColorAttachmentFramebuffer = function(a, e, i) {
    e === void 0 && (e = !1),
    this._currentRenderTarget = null;
    var o = this._gl
      , s = a._attachments
      , c = s.length;
    if (a._MSAAFramebuffer) {
        o.bindFramebuffer(o.READ_FRAMEBUFFER, a._MSAAFramebuffer),
        o.bindFramebuffer(o.DRAW_FRAMEBUFFER, a._framebuffer);
        for (var d = 0; d < c; d++) {
            for (var _ = a.textures[d], b = 0; b < c; b++)
                s[b] = o.NONE;
            s[d] = o[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + d : "COLOR_ATTACHMENT" + d + "_WEBGL"],
            o.readBuffer(s[d]),
            o.drawBuffers(s),
            o.blitFramebuffer(0, 0, _.width, _.height, 0, 0, _.width, _.height, o.COLOR_BUFFER_BIT, o.NEAREST)
        }
        for (var d = 0; d < c; d++)
            s[d] = o[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + d : "COLOR_ATTACHMENT" + d + "_WEBGL"];
        o.drawBuffers(s)
    }
    for (var d = 0; d < c; d++) {
        var _ = a.textures[d];
        _.generateMipMaps && !e && !_.isCube && (this._bindTextureDirectly(o.TEXTURE_2D, _, !0),
        o.generateMipmap(o.TEXTURE_2D),
        this._bindTextureDirectly(o.TEXTURE_2D, null))
    }
    i && (a._MSAAFramebuffer && this._bindUnboundFramebuffer(a._framebuffer),
    i()),
    this._bindUnboundFramebuffer(null)
}
;
ThinEngine.prototype.createMultipleRenderTarget = function(a, e, i) {
    i === void 0 && (i = !0);
    var o = !1
      , s = !0
      , c = !1
      , d = !1
      , _ = 15
      , b = 1
      , k = 0
      , j = 3
      , $ = new Array
      , _e = new Array
      , et = this._createHardwareRenderTargetWrapper(!0, !1, a);
    e !== void 0 && (o = e.generateMipMaps === void 0 ? !1 : e.generateMipMaps,
    s = e.generateDepthBuffer === void 0 ? !0 : e.generateDepthBuffer,
    c = e.generateStencilBuffer === void 0 ? !1 : e.generateStencilBuffer,
    d = e.generateDepthTexture === void 0 ? !1 : e.generateDepthTexture,
    b = e.textureCount || 1,
    e.types && ($ = e.types),
    e.samplingModes && (_e = e.samplingModes),
    this.webGLVersion > 1 && (e.depthTextureFormat === 13 || e.depthTextureFormat === 16 || e.depthTextureFormat === 14) && (_ = e.depthTextureFormat));
    var tt = this._gl
      , rt = tt.createFramebuffer();
    this._bindUnboundFramebuffer(rt);
    var it = a.width || a
      , nt = a.height || a
      , ot = []
      , at = []
      , st = this.webGLVersion > 1 && d && e.depthTextureFormat === 13
      , ut = this._setupFramebufferDepthAttachments(!st && c, !d && s, it, nt);
    et._framebuffer = rt,
    et._depthStencilBuffer = ut,
    et._generateDepthBuffer = !d && s,
    et._generateStencilBuffer = !st && c,
    et._attachments = at;
    for (var ct = 0; ct < b; ct++) {
        var lt = _e[ct] || j
          , ft = $[ct] || k;
        (ft === 1 && !this._caps.textureFloatLinearFiltering || ft === 2 && !this._caps.textureHalfFloatLinearFiltering) && (lt = 1);
        var ht = this._getSamplingParameters(lt, o);
        ft === 1 && !this._caps.textureFloat && (ft = 0,
        Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));
        var pt = new InternalTexture(this,InternalTextureSource.MultiRenderTarget)
          , dt = tt[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + ct : "COLOR_ATTACHMENT" + ct + "_WEBGL"];
        ot.push(pt),
        at.push(dt),
        tt.activeTexture(tt["TEXTURE" + ct]),
        tt.bindTexture(tt.TEXTURE_2D, pt._hardwareTexture.underlyingResource),
        tt.texParameteri(tt.TEXTURE_2D, tt.TEXTURE_MAG_FILTER, ht.mag),
        tt.texParameteri(tt.TEXTURE_2D, tt.TEXTURE_MIN_FILTER, ht.min),
        tt.texParameteri(tt.TEXTURE_2D, tt.TEXTURE_WRAP_S, tt.CLAMP_TO_EDGE),
        tt.texParameteri(tt.TEXTURE_2D, tt.TEXTURE_WRAP_T, tt.CLAMP_TO_EDGE),
        tt.texImage2D(tt.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(ft), it, nt, 0, tt.RGBA, this._getWebGLTextureType(ft), null),
        tt.framebufferTexture2D(tt.DRAW_FRAMEBUFFER, dt, tt.TEXTURE_2D, pt._hardwareTexture.underlyingResource, 0),
        o && this._gl.generateMipmap(this._gl.TEXTURE_2D),
        this._bindTextureDirectly(tt.TEXTURE_2D, null),
        pt.baseWidth = it,
        pt.baseHeight = nt,
        pt.width = it,
        pt.height = nt,
        pt.isReady = !0,
        pt.samples = 1,
        pt.generateMipMaps = o,
        pt.samplingMode = lt,
        pt.type = ft,
        this._internalTexturesCache.push(pt)
    }
    if (d && this._caps.depthTextureExtension) {
        var _t = new InternalTexture(this,InternalTextureSource.Depth)
          , mt = 5
          , vt = tt.DEPTH_COMPONENT16
          , yt = tt.DEPTH_COMPONENT
          , Et = tt.UNSIGNED_SHORT
          , At = tt.DEPTH_ATTACHMENT;
        this.webGLVersion < 2 ? vt = tt.DEPTH_COMPONENT : _ === 14 ? (mt = 1,
        Et = tt.FLOAT,
        vt = tt.DEPTH_COMPONENT32F) : _ === 16 ? (mt = 0,
        Et = tt.UNSIGNED_INT,
        vt = tt.DEPTH_COMPONENT24,
        At = tt.DEPTH_ATTACHMENT) : _ === 13 && (mt = 12,
        Et = tt.UNSIGNED_INT_24_8,
        vt = tt.DEPTH24_STENCIL8,
        yt = tt.DEPTH_STENCIL,
        At = tt.DEPTH_STENCIL_ATTACHMENT),
        tt.activeTexture(tt.TEXTURE0),
        tt.bindTexture(tt.TEXTURE_2D, _t._hardwareTexture.underlyingResource),
        tt.texParameteri(tt.TEXTURE_2D, tt.TEXTURE_MAG_FILTER, tt.NEAREST),
        tt.texParameteri(tt.TEXTURE_2D, tt.TEXTURE_MIN_FILTER, tt.NEAREST),
        tt.texParameteri(tt.TEXTURE_2D, tt.TEXTURE_WRAP_S, tt.CLAMP_TO_EDGE),
        tt.texParameteri(tt.TEXTURE_2D, tt.TEXTURE_WRAP_T, tt.CLAMP_TO_EDGE),
        tt.texImage2D(tt.TEXTURE_2D, 0, vt, it, nt, 0, yt, Et, null),
        tt.framebufferTexture2D(tt.FRAMEBUFFER, At, tt.TEXTURE_2D, _t._hardwareTexture.underlyingResource, 0),
        _t.baseWidth = it,
        _t.baseHeight = nt,
        _t.width = it,
        _t.height = nt,
        _t.isReady = !0,
        _t.samples = 1,
        _t.generateMipMaps = o,
        _t.samplingMode = 1,
        _t.format = _,
        _t.type = mt,
        ot.push(_t),
        this._internalTexturesCache.push(_t)
    }
    return et.setTextures(ot),
    i && tt.drawBuffers(at),
    this._bindUnboundFramebuffer(null),
    this.resetTextureCache(),
    et
}
;
ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function(a, e, i) {
    if (i === void 0 && (i = !0),
    this.webGLVersion < 2 || !a || !a.texture)
        return 1;
    if (a.samples === e)
        return e;
    var o = a._attachments.length;
    if (o === 0)
        return 1;
    var s = this._gl;
    e = Math.min(e, this.getCaps().maxMSAASamples),
    a._depthStencilBuffer && (s.deleteRenderbuffer(a._depthStencilBuffer),
    a._depthStencilBuffer = null),
    a._MSAAFramebuffer && (s.deleteFramebuffer(a._MSAAFramebuffer),
    a._MSAAFramebuffer = null);
    for (var c = 0; c < o; c++) {
        var d = a.textures[c]._hardwareTexture;
        d != null && d._MSAARenderBuffer && (s.deleteRenderbuffer(d._MSAARenderBuffer),
        d._MSAARenderBuffer = null)
    }
    if (e > 1 && s.renderbufferStorageMultisample) {
        var _ = s.createFramebuffer();
        if (!_)
            throw new Error("Unable to create multi sampled framebuffer");
        a._MSAAFramebuffer = _,
        this._bindUnboundFramebuffer(_);
        for (var b = [], c = 0; c < o; c++) {
            var k = a.textures[c]
              , d = k._hardwareTexture
              , j = s[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + c : "COLOR_ATTACHMENT" + c + "_WEBGL"]
              , $ = this._createRenderBuffer(k.width, k.height, e, -1, this._getRGBAMultiSampleBufferFormat(k.type), j);
            if (!$)
                throw new Error("Unable to create multi sampled framebuffer");
            d._MSAARenderBuffer = $,
            k.samples = e,
            b.push(j)
        }
        i && s.drawBuffers(b)
    } else
        this._bindUnboundFramebuffer(a._framebuffer);
    return a._depthStencilBuffer = this._setupFramebufferDepthAttachments(a._generateStencilBuffer, a._generateDepthBuffer, a.texture.width, a.texture.height, e),
    this._bindUnboundFramebuffer(null),
    e
}
;
ThinEngine.prototype._createDepthStencilCubeTexture = function(a, e, i) {
    var o = new InternalTexture(this,InternalTextureSource.DepthStencil);
    if (o.isCube = !0,
    this.webGLVersion === 1)
        return Logger$2.Error("Depth cube texture is not supported by WebGL 1."),
        o;
    var s = __assign({
        bilinearFiltering: !1,
        comparisonFunction: 0,
        generateStencil: !1
    }, e)
      , c = this._gl;
    this._bindTextureDirectly(c.TEXTURE_CUBE_MAP, o, !0),
    this._setupDepthStencilTexture(o, a, s.generateStencil, s.bilinearFiltering, s.comparisonFunction),
    i._depthStencilTexture = o,
    i._depthStencilTextureWithStencil = s.generateStencil;
    for (var d = 0; d < 6; d++)
        s.generateStencil ? c.texImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X + d, 0, c.DEPTH24_STENCIL8, a, a, 0, c.DEPTH_STENCIL, c.UNSIGNED_INT_24_8, null) : c.texImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X + d, 0, c.DEPTH_COMPONENT24, a, a, 0, c.DEPTH_COMPONENT, c.UNSIGNED_INT, null);
    return this._bindTextureDirectly(c.TEXTURE_CUBE_MAP, null),
    this._internalTexturesCache.push(o),
    o
}
;
ThinEngine.prototype._partialLoadFile = function(a, e, i, o, s) {
    s === void 0 && (s = null);
    var c = function(_) {
        i[e] = _,
        i._internalCount++,
        i._internalCount === 6 && o(i)
    }
      , d = function(_, b) {
        s && _ && s(_.status + " " + _.statusText, b)
    };
    this._loadFile(a, c, void 0, void 0, !0, d)
}
;
ThinEngine.prototype._cascadeLoadFiles = function(a, e, i, o) {
    o === void 0 && (o = null);
    var s = [];
    s._internalCount = 0;
    for (var c = 0; c < 6; c++)
        this._partialLoadFile(i[c], c, s, e, o)
}
;
ThinEngine.prototype._cascadeLoadImgs = function(a, e, i, o, s, c) {
    s === void 0 && (s = null);
    var d = [];
    d._internalCount = 0;
    for (var _ = 0; _ < 6; _++)
        this._partialLoadImg(o[_], _, d, a, e, i, s, c)
}
;
ThinEngine.prototype._partialLoadImg = function(a, e, i, o, s, c, d, _) {
    d === void 0 && (d = null);
    var b = RandomGUID()
      , k = function($) {
        i[e] = $,
        i._internalCount++,
        o && o._removePendingData(b),
        i._internalCount === 6 && c && c(s, i)
    }
      , j = function($, _e) {
        o && o._removePendingData(b),
        d && d($, _e)
    };
    LoadImage(a, k, j, o ? o.offlineProvider : null, _),
    o && o._addPendingData(b)
}
;
ThinEngine.prototype._setCubeMapTextureParams = function(a, e) {
    var i = this._gl;
    i.texParameteri(i.TEXTURE_CUBE_MAP, i.TEXTURE_MAG_FILTER, i.LINEAR),
    i.texParameteri(i.TEXTURE_CUBE_MAP, i.TEXTURE_MIN_FILTER, e ? i.LINEAR_MIPMAP_LINEAR : i.LINEAR),
    i.texParameteri(i.TEXTURE_CUBE_MAP, i.TEXTURE_WRAP_S, i.CLAMP_TO_EDGE),
    i.texParameteri(i.TEXTURE_CUBE_MAP, i.TEXTURE_WRAP_T, i.CLAMP_TO_EDGE),
    a.samplingMode = e ? 3 : 2,
    this._bindTextureDirectly(i.TEXTURE_CUBE_MAP, null)
}
;
ThinEngine.prototype.createCubeTextureBase = function(a, e, i, o, s, c, d, _, b, k, j, $, _e, et, tt) {
    var rt = this;
    s === void 0 && (s = null),
    c === void 0 && (c = null),
    _ === void 0 && (_ = null),
    b === void 0 && (b = !1),
    k === void 0 && (k = 0),
    j === void 0 && (j = 0),
    $ === void 0 && ($ = null),
    _e === void 0 && (_e = null),
    et === void 0 && (et = null),
    tt === void 0 && (tt = !1);
    var it = $ || new InternalTexture(this,InternalTextureSource.Cube);
    it.isCube = !0,
    it.url = a,
    it.generateMipMaps = !o,
    it._lodGenerationScale = k,
    it._lodGenerationOffset = j,
    it._useSRGBBuffer = !!tt && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || !!o),
    this._doNotHandleContextLost || (it._extension = _,
    it._files = i);
    var nt = a;
    this._transformTextureUrl && !$ && (a = this._transformTextureUrl(a));
    for (var ot = a.lastIndexOf("."), at = _ || (ot > -1 ? a.substring(ot).toLowerCase() : ""), st = null, ut = 0, ct = ThinEngine._TextureLoaders; ut < ct.length; ut++) {
        var lt = ct[ut];
        if (lt.canLoad(at)) {
            st = lt;
            break
        }
    }
    var ft = function(pt, dt) {
        a === nt ? c && pt && c(pt.status + " " + pt.statusText, dt) : (Logger$2.Warn("Failed to load " + a + ", falling back to the " + nt),
        rt.createCubeTextureBase(nt, e, i, !!o, s, c, d, _, b, k, j, it, _e, et, tt))
    };
    if (st) {
        var ht = function(pt) {
            _e && _e(it, pt),
            st.loadCubeData(pt, it, b, s, c)
        };
        i && i.length === 6 ? st.supportCascades ? this._cascadeLoadFiles(e, function(pt) {
            return ht(pt.map(function(dt) {
                return new Uint8Array(dt)
            }))
        }, i, c) : c ? c("Textures type does not support cascades.") : Logger$2.Warn("Texture loader does not support cascades.") : this._loadFile(a, function(pt) {
            return ht(new Uint8Array(pt))
        }, void 0, void 0, !0, ft)
    } else {
        if (!i)
            throw new Error("Cannot load cubemap because files were not defined");
        this._cascadeLoadImgs(e, it, function(pt, dt) {
            et && et(pt, dt)
        }, i, c)
    }
    return this._internalTexturesCache.push(it),
    it
}
;
ThinEngine.prototype.createCubeTexture = function(a, e, i, o, s, c, d, _, b, k, j, $, _e, et) {
    var tt = this;
    s === void 0 && (s = null),
    c === void 0 && (c = null),
    _ === void 0 && (_ = null),
    b === void 0 && (b = !1),
    k === void 0 && (k = 0),
    j === void 0 && (j = 0),
    $ === void 0 && ($ = null),
    et === void 0 && (et = !1);
    var rt = this._gl;
    return this.createCubeTextureBase(a, e, i, !!o, s, c, d, _, b, k, j, $, function(it, nt) {
        return tt._bindTextureDirectly(rt.TEXTURE_CUBE_MAP, it, !0)
    }, function(it, nt) {
        var ot = tt.needPOTTextures ? ThinEngine.GetExponentOfTwo(nt[0].width, tt._caps.maxCubemapTextureSize) : nt[0].width
          , at = ot
          , st = [rt.TEXTURE_CUBE_MAP_POSITIVE_X, rt.TEXTURE_CUBE_MAP_POSITIVE_Y, rt.TEXTURE_CUBE_MAP_POSITIVE_Z, rt.TEXTURE_CUBE_MAP_NEGATIVE_X, rt.TEXTURE_CUBE_MAP_NEGATIVE_Y, rt.TEXTURE_CUBE_MAP_NEGATIVE_Z];
        tt._bindTextureDirectly(rt.TEXTURE_CUBE_MAP, it, !0),
        tt._unpackFlipY(!1);
        var ut = d ? tt._getInternalFormat(d, it._useSRGBBuffer) : it._useSRGBBuffer ? rt.SRGB8_ALPHA8 : rt.RGBA
          , ct = d ? tt._getInternalFormat(d) : rt.RGBA;
        it._useSRGBBuffer && tt.webGLVersion === 1 && (ct = ut);
        for (var lt = 0; lt < st.length; lt++)
            if (nt[lt].width !== ot || nt[lt].height !== at) {
                if (tt._prepareWorkingCanvas(),
                !tt._workingCanvas || !tt._workingContext) {
                    Logger$2.Warn("Cannot create canvas to resize texture.");
                    return
                }
                tt._workingCanvas.width = ot,
                tt._workingCanvas.height = at,
                tt._workingContext.drawImage(nt[lt], 0, 0, nt[lt].width, nt[lt].height, 0, 0, ot, at),
                rt.texImage2D(st[lt], 0, ut, ct, rt.UNSIGNED_BYTE, tt._workingCanvas)
            } else
                rt.texImage2D(st[lt], 0, ut, ct, rt.UNSIGNED_BYTE, nt[lt]);
        o || rt.generateMipmap(rt.TEXTURE_CUBE_MAP),
        tt._setCubeMapTextureParams(it, !o),
        it.width = ot,
        it.height = at,
        it.isReady = !0,
        d && (it.format = d),
        it.onLoadedObservable.notifyObservers(it),
        it.onLoadedObservable.clear(),
        s && s()
    }, !!et)
}
;
ThinEngine.prototype.setTextureSampler = function(a, e) {
    throw new Error("setTextureSampler: This engine does not support separate texture sampler objects!")
}
;
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 a = this
      , e = function() {
        var o = {
            vrDisplay: a._vrDisplay,
            vrSupported: a._vrSupported
        };
        a.onVRDisplayChangedObservable.notifyObservers(o),
        a._webVRInitPromise = new Promise(function(s) {
            s(o)
        }
        )
    };
    if (!this._onVrDisplayConnect) {
        this._onVrDisplayConnect = function(o) {
            a._vrDisplay = o.display,
            e()
        }
        ,
        this._onVrDisplayDisconnect = function() {
            a._vrDisplay.cancelAnimationFrame(a._frameHandler),
            a._vrDisplay = void 0,
            a._frameHandler = Engine.QueueNewFrame(a._boundRenderFunction),
            e()
        }
        ,
        this._onVrDisplayPresentChange = function() {
            a._vrExclusivePointerMode = a._vrDisplay && a._vrDisplay.isPresenting
        }
        ;
        var i = this.getHostWindow();
        i && (i.addEventListener("vrdisplayconnect", this._onVrDisplayConnect),
        i.addEventListener("vrdisplaydisconnect", this._onVrDisplayDisconnect),
        i.addEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange))
    }
    return this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync(),
    this._webVRInitPromise.then(e),
    this._webVRInitPromise
}
;
Engine.prototype._getVRDisplaysAsync = function() {
    var a = this;
    return new Promise(function(e) {
        navigator.getVRDisplays ? navigator.getVRDisplays().then(function(i) {
            a._vrSupported = !0,
            a._vrDisplay = i[0],
            e({
                vrDisplay: a._vrDisplay,
                vrSupported: a._vrSupported
            })
        }) : (a._vrDisplay = void 0,
        a._vrSupported = !1,
        e({
            vrDisplay: a._vrDisplay,
            vrSupported: a._vrSupported
        }))
    }
    )
}
;
Engine.prototype.enableVR = function(a) {
    var e = this;
    if (this._vrDisplay && !this._vrDisplay.isPresenting) {
        var i = function() {
            e.onVRRequestPresentComplete.notifyObservers(!0),
            e._onVRFullScreenTriggered()
        }
          , o = function() {
            e.onVRRequestPresentComplete.notifyObservers(!1)
        };
        this.onVRRequestPresentStart.notifyObservers(this);
        var s = {
            highRefreshRate: this.vrPresentationAttributes ? this.vrPresentationAttributes.highRefreshRate : !1,
            foveationLevel: this.vrPresentationAttributes ? this.vrPresentationAttributes.foveationLevel : 1,
            multiview: (this.getCaps().multiview || this.getCaps().oculusMultiview) && a.useMultiview
        };
        this._vrDisplay.requestPresent([__assign({
            source: this.getRenderingCanvas(),
            attributes: s
        }, s)]).then(i).catch(o)
    }
}
;
Engine.prototype._onVRFullScreenTriggered = function() {
    if (this._vrDisplay && this._vrDisplay.isPresenting) {
        this._oldSize = new Size(this.getRenderWidth(),this.getRenderHeight()),
        this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
        var a = this._vrDisplay.getEyeParameters("left");
        this.setHardwareScalingLevel(1),
        this.setSize(a.renderWidth * 2, a.renderHeight)
    } else
        this.setHardwareScalingLevel(this._oldHardwareScaleFactor),
        this.setSize(this._oldSize.width, this._oldSize.height)
}
;
Engine.prototype.disableVR = function() {
    var a = this;
    this._vrDisplay && this._vrDisplay.isPresenting && this._vrDisplay.exitPresent().then(function() {
        return a._onVRFullScreenTriggered()
    }).catch(function() {
        return a._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(a, e) {
    var i = this;
    if (this._onVRDisplayPointerRestricted = function() {
        a && a.requestPointerLock()
    }
    ,
    this._onVRDisplayPointerUnrestricted = function() {
        if (!e) {
            var s = i.getHostWindow();
            s.document && s.document.exitPointerLock && s.document.exitPointerLock();
            return
        }
        !e.exitPointerLock || e.exitPointerLock()
    }
    ,
    IsWindowObjectExist()) {
        var o = this.getHostWindow();
        o.addEventListener("vrdisplaypointerrestricted", this._onVRDisplayPointerRestricted, !1),
        o.addEventListener("vrdisplaypointerunrestricted", this._onVRDisplayPointerUnrestricted, !1)
    }
}
;
Engine.prototype._submitVRFrame = function() {
    if (this._vrDisplay && this._vrDisplay.isPresenting)
        try {
            this._vrDisplay.submitFrame()
        } catch (a) {
            Tools.Warn("webVR submitFrame has had an unexpected failure: " + a)
        }
}
;
Engine.prototype.isVRPresenting = function() {
    return this._vrDisplay && this._vrDisplay.isPresenting
}
;
Engine.prototype._requestVRFrame = function() {
    this._frameHandler = Engine.QueueNewFrame(this._boundRenderFunction, this._vrDisplay)
}
;
Engine.prototype.getInputElement = function() {
    return this.inputElement || this.getRenderingCanvas()
}
;
Engine.prototype.registerView = function(a, e, i) {
    var o = this;
    this.views || (this.views = []);
    for (var s = 0, c = this.views; s < c.length; s++) {
        var d = c[s];
        if (d.target === a)
            return d
    }
    var _ = this.getRenderingCanvas();
    _ && (a.width = _.width,
    a.height = _.height);
    var b = {
        target: a,
        camera: e,
        clearBeforeCopy: i,
        enabled: !0
    };
    return this.views.push(b),
    e && e.onDisposeObservable.add(function() {
        o.unRegisterView(a)
    }),
    b
}
;
Engine.prototype.unRegisterView = function(a) {
    if (!this.views)
        return this;
    for (var e = 0, i = this.views; e < i.length; e++) {
        var o = i[e];
        if (o.target === a) {
            var s = this.views.indexOf(o);
            s !== -1 && this.views.splice(s, 1);
            break
        }
    }
    return this
}
;
Engine.prototype._renderViews = function() {
    if (!this.views)
        return !1;
    var a = this.getRenderingCanvas();
    if (!a)
        return !1;
    for (var e = 0, i = this.views; e < i.length; e++) {
        var o = i[e];
        if (!!o.enabled) {
            var s = o.target
              , c = s.getContext("2d");
            if (!!c) {
                var d = o.camera
                  , _ = null
                  , b = null;
                if (d) {
                    if (b = d.getScene(),
                    b.activeCameras && b.activeCameras.length)
                        continue;
                    this.activeView = o,
                    _ = b.activeCamera,
                    b.activeCamera = d
                }
                if (o.customResize)
                    o.customResize(s);
                else {
                    var k = Math.floor(s.clientWidth / this._hardwareScalingLevel)
                      , j = Math.floor(s.clientHeight / this._hardwareScalingLevel)
                      , $ = k !== s.width || a.width !== s.width || j !== s.height || a.height !== s.height;
                    s.clientWidth && s.clientHeight && $ && (s.width = k,
                    s.height = j,
                    this.setSize(k, j))
                }
                if (!a.width || !a.height)
                    return !1;
                this._renderFrame(),
                this.flushFramebuffer(),
                o.clearBeforeCopy && c.clearRect(0, 0, a.width, a.height),
                c.drawImage(a, 0, 0),
                _ && b && (b.activeCamera = _)
            }
        }
    }
    return this.activeView = null,
    !0
}
;
var ComputeBindingType;
(function(a) {
    a[a.Texture = 0] = "Texture",
    a[a.StorageTexture = 1] = "StorageTexture",
    a[a.UniformBuffer = 2] = "UniformBuffer",
    a[a.StorageBuffer = 3] = "StorageBuffer",
    a[a.TextureWithoutSampler = 4] = "TextureWithoutSampler",
    a[a.Sampler = 5] = "Sampler"
}
)(ComputeBindingType || (ComputeBindingType = {}));
ThinEngine.prototype.createComputeEffect = function(a, 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(a, e, i, o, s, c, d) {
    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(a, e, i, o, s) {}
;
ThinEngine.prototype._rebuildComputeEffects = function() {}
;
ThinEngine.prototype._executeWhenComputeStateIsCompiled = function(a, e) {
    e()
}
;
ThinEngine.prototype._releaseComputeEffect = function(a) {}
;
ThinEngine.prototype._deleteComputePipelineContext = function(a) {}
;
ThinEngine.prototype.createStorageBuffer = function(a, e) {
    throw new Error("createStorageBuffer: Unsupported method in this engine!")
}
;
ThinEngine.prototype.updateStorageBuffer = function(a, e, i, o) {}
;
ThinEngine.prototype.readFromStorageBuffer = function(a, e, i, o) {
    throw new Error("readFromStorageBuffer: Unsupported method in this engine!")
}
;
ThinEngine.prototype.setStorageBuffer = function(a, e) {
    throw new Error("setStorageBuffer: Unsupported method in this engine!")
}
;
function transformTextureUrl(a) {
    var e = function(c) {
        var d = "\\b" + c + "\\b";
        return a && (a === c || a.match(new RegExp(d,"g")))
    };
    if (this._excludedCompressedTextures && this._excludedCompressedTextures.some(e))
        return a;
    var i = a.lastIndexOf(".")
      , o = a.lastIndexOf("?")
      , s = o > -1 ? a.substring(o, a.length) : "";
    return (i > -1 ? a.substring(0, i) : a) + this._textureFormatInUse + s
}
Object.defineProperty(Engine.prototype, "texturesSupported", {
    get: function() {
        var a = new Array;
        return this._caps.astc && a.push("-astc.ktx"),
        this._caps.s3tc && a.push("-dxt.ktx"),
        this._caps.pvrtc && a.push("-pvrtc.ktx"),
        this._caps.etc2 && a.push("-etc2.ktx"),
        this._caps.etc1 && a.push("-etc1.ktx"),
        a
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(Engine.prototype, "textureFormatInUse", {
    get: function() {
        return this._textureFormatInUse || null
    },
    enumerable: !0,
    configurable: !0
});
Engine.prototype.setCompressedTextureExclusions = function(a) {
    this._excludedCompressedTextures = a
}
;
Engine.prototype.setTextureFormatToUse = function(a) {
    for (var e = this.texturesSupported, i = 0, o = e.length; i < o; i++)
        for (var s = 0, c = a.length; s < c; s++)
            if (e[i] === a[s].toLowerCase())
                return this._transformTextureUrl = transformTextureUrl.bind(this),
                this._textureFormatInUse = e[i];
    return this._textureFormatInUse = "",
    this._transformTextureUrl = null,
    null
}
;
var NativeDataStream = function() {
    function a() {
        var e = this
          , i = new ArrayBuffer(a.DEFAULT_BUFFER_SIZE);
        this._uint32s = new Uint32Array(i),
        this._int32s = new Int32Array(i),
        this._float32s = new Float32Array(i),
        this._length = a.DEFAULT_BUFFER_SIZE / 4,
        this._position = 0,
        this._nativeDataStream = new _native.NativeDataStream(function() {
            e._flush()
        }
        )
    }
    return a.prototype.writeUint32 = function(e) {
        this._flushIfNecessary(1),
        this._uint32s[this._position++] = e
    }
    ,
    a.prototype.writeInt32 = function(e) {
        this._flushIfNecessary(1),
        this._int32s[this._position++] = e
    }
    ,
    a.prototype.writeFloat32 = function(e) {
        this._flushIfNecessary(1),
        this._float32s[this._position++] = e
    }
    ,
    a.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
    }
    ,
    a.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
    }
    ,
    a.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
    }
    ,
    a.prototype.writeNativeData = function(e) {
        this._flushIfNecessary(e.length),
        this._uint32s.set(e, this._position),
        this._position += e.length
    }
    ,
    a.prototype.writeBoolean = function(e) {
        this.writeUint32(e ? 1 : 0)
    }
    ,
    a.prototype._flushIfNecessary = function(e) {
        this._position + e > this._length && this._flush()
    }
    ,
    a.prototype._flush = function() {
        this._nativeDataStream.writeBuffer(this._uint32s.buffer, this._position),
        this._position = 0
    }
    ,
    a.DEFAULT_BUFFER_SIZE = 65536,
    a
}(), Orientation;
(function(a) {
    a[a.CW = 0] = "CW",
    a[a.CCW = 1] = "CCW"
}
)(Orientation || (Orientation = {}));
var BezierCurve = function() {
    function a() {}
    return a.Interpolate = function(e, i, o, s, c) {
        for (var d = 1 - 3 * s + 3 * i, _ = 3 * s - 6 * i, b = 3 * i, k = e, j = 0; j < 5; j++) {
            var $ = k * k
              , _e = $ * k
              , et = d * _e + _ * $ + b * k
              , tt = 1 / (3 * d * $ + 2 * _ * k + b);
            k -= (et - e) * tt,
            k = Math.min(1, Math.max(0, k))
        }
        return 3 * Math.pow(1 - k, 2) * k * o + 3 * (1 - k) * Math.pow(k, 2) * c + Math.pow(k, 3)
    }
    ,
    a
}()
  , Angle = function() {
    function a(e) {
        this._radians = e,
        this._radians < 0 && (this._radians += 2 * Math.PI)
    }
    return a.prototype.degrees = function() {
        return this._radians * 180 / Math.PI
    }
    ,
    a.prototype.radians = function() {
        return this._radians
    }
    ,
    a.BetweenTwoPoints = function(e, i) {
        var o = i.subtract(e)
          , s = Math.atan2(o.y, o.x);
        return new a(s)
    }
    ,
    a.FromRadians = function(e) {
        return new a(e)
    }
    ,
    a.FromDegrees = function(e) {
        return new a(e * Math.PI / 180)
    }
    ,
    a
}()
  , Arc2 = function() {
    function a(e, i, o) {
        this.startPoint = e,
        this.midPoint = i,
        this.endPoint = o;
        var s = Math.pow(i.x, 2) + Math.pow(i.y, 2)
          , c = (Math.pow(e.x, 2) + Math.pow(e.y, 2) - s) / 2
          , d = (s - Math.pow(o.x, 2) - Math.pow(o.y, 2)) / 2
          , _ = (e.x - i.x) * (i.y - o.y) - (i.x - o.x) * (e.y - i.y);
        this.centerPoint = new Vector2((c * (i.y - o.y) - d * (e.y - i.y)) / _,((e.x - i.x) * d - (i.x - o.x) * c) / _),
        this.radius = this.centerPoint.subtract(this.startPoint).length(),
        this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
        var b = this.startAngle.degrees()
          , k = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees()
          , j = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
        k - b > 180 && (k -= 360),
        k - b < -180 && (k += 360),
        j - k > 180 && (j -= 360),
        j - k < -180 && (j += 360),
        this.orientation = k - b < 0 ? Orientation.CW : Orientation.CCW,
        this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? b - j : j - b)
    }
    return a
}()
  , Path2 = function() {
    function a(e, i) {
        this._points = new Array,
        this._length = 0,
        this.closed = !1,
        this._points.push(new Vector2(e,i))
    }
    return a.prototype.addLineTo = function(e, i) {
        if (this.closed)
            return this;
        var o = new Vector2(e,i)
          , s = this._points[this._points.length - 1];
        return this._points.push(o),
        this._length += o.subtract(s).length(),
        this
    }
    ,
    a.prototype.addArcTo = function(e, i, o, s, c) {
        if (c === void 0 && (c = 36),
        this.closed)
            return this;
        var d = this._points[this._points.length - 1]
          , _ = new Vector2(e,i)
          , b = new Vector2(o,s)
          , k = new Arc2(d,_,b)
          , j = k.angle.radians() / c;
        k.orientation === Orientation.CW && (j *= -1);
        for (var $ = k.startAngle.radians() + j, _e = 0; _e < c; _e++) {
            var et = Math.cos($) * k.radius + k.centerPoint.x
              , tt = Math.sin($) * k.radius + k.centerPoint.y;
            this.addLineTo(et, tt),
            $ += j
        }
        return this
    }
    ,
    a.prototype.close = function() {
        return this.closed = !0,
        this
    }
    ,
    a.prototype.length = function() {
        var e = this._length;
        if (this.closed) {
            var i = this._points[this._points.length - 1]
              , o = this._points[0];
            e += o.subtract(i).length()
        }
        return e
    }
    ,
    a.prototype.getPoints = function() {
        return this._points
    }
    ,
    a.prototype.getPointAtLengthPosition = function(e) {
        if (e < 0 || e > 1)
            return Vector2.Zero();
        for (var i = e * this.length(), o = 0, s = 0; s < this._points.length; s++) {
            var c = (s + 1) % this._points.length
              , d = this._points[s]
              , _ = this._points[c]
              , b = _.subtract(d)
              , k = b.length() + o;
            if (i >= o && i <= k) {
                var j = b.normalize()
                  , $ = i - o;
                return new Vector2(d.x + j.x * $,d.y + j.y * $)
            }
            o = k
        }
        return Vector2.Zero()
    }
    ,
    a.StartingAt = function(e, i) {
        return new a(e,i)
    }
    ,
    a
}()
  , Path3D = function() {
    function a(e, i, o, s) {
        i === void 0 && (i = null),
        s === void 0 && (s = !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 c = 0; c < e.length; c++)
            this._curve[c] = e[c].clone();
        this._raw = o || !1,
        this._alignTangentsWithPath = s,
        this._compute(i, s)
    }
    return a.prototype.getCurve = function() {
        return this._curve
    }
    ,
    a.prototype.getPoints = function() {
        return this._curve
    }
    ,
    a.prototype.length = function() {
        return this._distances[this._distances.length - 1]
    }
    ,
    a.prototype.getTangents = function() {
        return this._tangents
    }
    ,
    a.prototype.getNormals = function() {
        return this._normals
    }
    ,
    a.prototype.getBinormals = function() {
        return this._binormals
    }
    ,
    a.prototype.getDistances = function() {
        return this._distances
    }
    ,
    a.prototype.getPointAt = function(e) {
        return this._updatePointAtData(e).point
    }
    ,
    a.prototype.getTangentAt = function(e, i) {
        return i === void 0 && (i = !1),
        this._updatePointAtData(e, i),
        i ? Vector3.TransformCoordinates(Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex]
    }
    ,
    a.prototype.getNormalAt = function(e, i) {
        return i === void 0 && (i = !1),
        this._updatePointAtData(e, i),
        i ? Vector3.TransformCoordinates(Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex]
    }
    ,
    a.prototype.getBinormalAt = function(e, i) {
        return i === void 0 && (i = !1),
        this._updatePointAtData(e, i),
        i ? Vector3.TransformCoordinates(Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex]
    }
    ,
    a.prototype.getDistanceAt = function(e) {
        return this.length() * e
    }
    ,
    a.prototype.getPreviousPointIndexAt = function(e) {
        return this._updatePointAtData(e),
        this._pointAtData.previousPointArrayIndex
    }
    ,
    a.prototype.getSubPositionAt = function(e) {
        return this._updatePointAtData(e),
        this._pointAtData.subPosition
    }
    ,
    a.prototype.getClosestPositionTo = function(e) {
        for (var i = Number.MAX_VALUE, o = 0, s = 0; s < this._curve.length - 1; s++) {
            var c = this._curve[s + 0]
              , d = this._curve[s + 1].subtract(c).normalize()
              , _ = this._distances[s + 1] - this._distances[s + 0]
              , b = Math.min(Math.max(Vector3.Dot(d, e.subtract(c).normalize()), 0) * Vector3.Distance(c, e) / _, 1)
              , k = Vector3.Distance(c.add(d.scale(b * _)), e);
            k < i && (i = k,
            o = (this._distances[s + 0] + _ * b) / this.length())
        }
        return o
    }
    ,
    a.prototype.slice = function(e, i) {
        if (e === void 0 && (e = 0),
        i === void 0 && (i = 1),
        e < 0 && (e = 1 - e * -1 % 1),
        i < 0 && (i = 1 - i * -1 % 1),
        e > i) {
            var o = e;
            e = i,
            i = o
        }
        var s = this.getCurve()
          , c = this.getPointAt(e)
          , d = this.getPreviousPointIndexAt(e)
          , _ = this.getPointAt(i)
          , b = this.getPreviousPointIndexAt(i) + 1
          , k = [];
        return e !== 0 && (d++,
        k.push(c)),
        k.push.apply(k, s.slice(d, b)),
        (i !== 1 || e === 1) && k.push(_),
        new a(k,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)
    }
    ,
    a.prototype.update = function(e, i, o) {
        i === void 0 && (i = null),
        o === void 0 && (o = !1);
        for (var s = 0; s < e.length; s++)
            this._curve[s].x = e[s].x,
            this._curve[s].y = e[s].y,
            this._curve[s].z = e[s].z;
        return this._compute(i, o),
        this
    }
    ,
    a.prototype._compute = function(e, i) {
        i === void 0 && (i = !1);
        var o = this._curve.length;
        if (!(o < 2)) {
            this._tangents[0] = this._getFirstNonNullVector(0),
            this._raw || this._tangents[0].normalize(),
            this._tangents[o - 1] = this._curve[o - 1].subtract(this._curve[o - 2]),
            this._raw || this._tangents[o - 1].normalize();
            var s = this._tangents[0]
              , c = this._normalVector(s, e);
            this._normals[0] = c,
            this._raw || this._normals[0].normalize(),
            this._binormals[0] = Vector3.Cross(s, this._normals[0]),
            this._raw || this._binormals[0].normalize(),
            this._distances[0] = 0;
            for (var d, _, b, k, j, $ = 1; $ < o; $++)
                d = this._getLastNonNullVector($),
                $ < o - 1 && (_ = this._getFirstNonNullVector($),
                this._tangents[$] = i ? _ : d.add(_),
                this._tangents[$].normalize()),
                this._distances[$] = this._distances[$ - 1] + this._curve[$].subtract(this._curve[$ - 1]).length(),
                b = this._tangents[$],
                j = this._binormals[$ - 1],
                this._normals[$] = Vector3.Cross(j, b),
                this._raw || (this._normals[$].length() === 0 ? (k = this._normals[$ - 1],
                this._normals[$] = k.clone()) : this._normals[$].normalize()),
                this._binormals[$] = Vector3.Cross(b, this._normals[$]),
                this._raw || this._binormals[$].normalize();
            this._pointAtData.id = NaN
        }
    }
    ,
    a.prototype._getFirstNonNullVector = function(e) {
        for (var i = 1, o = this._curve[e + i].subtract(this._curve[e]); o.length() === 0 && e + i + 1 < this._curve.length; )
            i++,
            o = this._curve[e + i].subtract(this._curve[e]);
        return o
    }
    ,
    a.prototype._getLastNonNullVector = function(e) {
        for (var i = 1, o = this._curve[e].subtract(this._curve[e - i]); o.length() === 0 && e > i + 1; )
            i++,
            o = this._curve[e].subtract(this._curve[e - i]);
        return o
    }
    ,
    a.prototype._normalVector = function(e, i) {
        var o, s = e.length();
        if (s === 0 && (s = 1),
        i == null) {
            var c;
            Scalar.WithinEpsilon(Math.abs(e.y) / s, 1, Epsilon) ? Scalar.WithinEpsilon(Math.abs(e.x) / s, 1, Epsilon) ? Scalar.WithinEpsilon(Math.abs(e.z) / s, 1, Epsilon) ? c = Vector3.Zero() : c = new Vector3(0,0,1) : c = new Vector3(1,0,0) : c = new Vector3(0,-1,0),
            o = Vector3.Cross(e, c)
        } else
            o = Vector3.Cross(e, i),
            Vector3.CrossToRef(o, e, o);
        return o.normalize(),
        o
    }
    ,
    a.prototype._updatePointAtData = function(e, i) {
        if (i === void 0 && (i = !1),
        this._pointAtData.id === e)
            return this._pointAtData.interpolateReady || this._updateInterpolationMatrix(),
            this._pointAtData;
        this._pointAtData.id = e;
        var o = this.getPoints();
        if (e <= 0)
            return this._setPointAtData(0, 0, o[0], 0, i);
        if (e >= 1)
            return this._setPointAtData(1, 1, o[o.length - 1], o.length - 1, i);
        for (var s = o[0], c, d = 0, _ = e * this.length(), b = 1; b < o.length; b++) {
            c = o[b];
            var k = Vector3.Distance(s, c);
            if (d += k,
            d === _)
                return this._setPointAtData(e, 1, c, b, i);
            if (d > _) {
                var j = d - _
                  , $ = j / k
                  , _e = s.subtract(c)
                  , et = c.add(_e.scaleInPlace($));
                return this._setPointAtData(e, 1 - $, et, b - 1, i)
            }
            s = c
        }
        return this._pointAtData
    }
    ,
    a.prototype._setPointAtData = function(e, i, o, s, c) {
        return this._pointAtData.point = o,
        this._pointAtData.position = e,
        this._pointAtData.subPosition = i,
        this._pointAtData.previousPointArrayIndex = s,
        this._pointAtData.interpolateReady = c,
        c && this._updateInterpolationMatrix(),
        this._pointAtData
    }
    ,
    a.prototype._updateInterpolationMatrix = function() {
        this._pointAtData.interpolationMatrix = Matrix.Identity();
        var e = this._pointAtData.previousPointArrayIndex;
        if (e !== this._tangents.length - 1) {
            var i = e + 1
              , o = this._tangents[e].clone()
              , s = this._normals[e].clone()
              , c = this._binormals[e].clone()
              , d = this._tangents[i].clone()
              , _ = this._normals[i].clone()
              , b = this._binormals[i].clone()
              , k = Quaternion.RotationQuaternionFromAxis(s, c, o)
              , j = Quaternion.RotationQuaternionFromAxis(_, b, d)
              , $ = Quaternion.Slerp(k, j, this._pointAtData.subPosition);
            $.toRotationMatrix(this._pointAtData.interpolationMatrix)
        }
    }
    ,
    a
}()
  , Curve3 = function() {
    function a(e) {
        this._length = 0,
        this._points = e,
        this._length = this._computeLength(e)
    }
    return a.CreateQuadraticBezier = function(e, i, o, s) {
        s = s > 2 ? s : 3;
        for (var c = new Array, d = function(b, k, j, $) {
            var _e = (1 - b) * (1 - b) * k + 2 * b * (1 - b) * j + b * b * $;
            return _e
        }, _ = 0; _ <= s; _++)
            c.push(new Vector3(d(_ / s, e.x, i.x, o.x),d(_ / s, e.y, i.y, o.y),d(_ / s, e.z, i.z, o.z)));
        return new a(c)
    }
    ,
    a.CreateCubicBezier = function(e, i, o, s, c) {
        c = c > 3 ? c : 4;
        for (var d = new Array, _ = function(k, j, $, _e, et) {
            var tt = (1 - k) * (1 - k) * (1 - k) * j + 3 * k * (1 - k) * (1 - k) * $ + 3 * k * k * (1 - k) * _e + k * k * k * et;
            return tt
        }, b = 0; b <= c; b++)
            d.push(new Vector3(_(b / c, e.x, i.x, o.x, s.x),_(b / c, e.y, i.y, o.y, s.y),_(b / c, e.z, i.z, o.z, s.z)));
        return new a(d)
    }
    ,
    a.CreateHermiteSpline = function(e, i, o, s, c) {
        for (var d = new Array, _ = 1 / c, b = 0; b <= c; b++)
            d.push(Vector3.Hermite(e, i, o, s, b * _));
        return new a(d)
    }
    ,
    a.CreateCatmullRomSpline = function(e, i, o) {
        var s = new Array
          , c = 1 / i
          , d = 0;
        if (o) {
            for (var _ = e.length, b = 0; b < _; b++) {
                d = 0;
                for (var k = 0; k < i; k++)
                    s.push(Vector3.CatmullRom(e[b % _], e[(b + 1) % _], e[(b + 2) % _], e[(b + 3) % _], d)),
                    d += c
            }
            s.push(s[0])
        } else {
            var j = new Array;
            j.push(e[0].clone()),
            Array.prototype.push.apply(j, e),
            j.push(e[e.length - 1].clone());
            for (var b = 0; b < j.length - 3; b++) {
                d = 0;
                for (var k = 0; k < i; k++)
                    s.push(Vector3.CatmullRom(j[b], j[b + 1], j[b + 2], j[b + 3], d)),
                    d += c
            }
            b--,
            s.push(Vector3.CatmullRom(j[b], j[b + 1], j[b + 2], j[b + 3], d))
        }
        return new a(s)
    }
    ,
    a.prototype.getPoints = function() {
        return this._points
    }
    ,
    a.prototype.length = function() {
        return this._length
    }
    ,
    a.prototype.continue = function(e) {
        for (var i = this._points[this._points.length - 1], o = this._points.slice(), s = e.getPoints(), c = 1; c < s.length; c++)
            o.push(s[c].subtract(s[0]).add(i));
        var d = new a(o);
        return d
    }
    ,
    a.prototype._computeLength = function(e) {
        for (var i = 0, o = 1; o < e.length; o++)
            i += e[o].subtract(e[o - 1]).length();
        return i
    }
    ,
    a
}()
  , PositionNormalTextureVertex = function() {
    function a(e, i, o) {
        e === void 0 && (e = Vector3.Zero()),
        i === void 0 && (i = Vector3.Up()),
        o === void 0 && (o = Vector2.Zero()),
        this.position = e,
        this.normal = i,
        this.uv = o
    }
    return a.prototype.clone = function() {
        return new a(this.position.clone(),this.normal.clone(),this.uv.clone())
    }
    ,
    a
}()
  , 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(a) {
    return 1
}
, function(a) {
    return a.y
}
, function(a) {
    return a.z
}
, function(a) {
    return a.x
}
, function(a) {
    return a.x * a.y
}
, function(a) {
    return a.y * a.z
}
, function(a) {
    return 3 * a.z * a.z - 1
}
, function(a) {
    return a.x * a.z
}
, function(a) {
    return a.x * a.x - a.y * a.y
}
]
  , applySH3 = function(a, e) {
    return SH3ylmBasisConstants[a] * SH3ylmBasisTrigonometricTerms[a](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 a() {
        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 a.prototype.addLight = function(e, i, o) {
        TmpVectors.Vector3[0].set(i.r, i.g, i.b);
        var s = TmpVectors.Vector3[0]
          , c = TmpVectors.Vector3[1];
        s.scaleToRef(o, c),
        c.scaleToRef(applySH3(0, e), TmpVectors.Vector3[2]),
        this.l00.addInPlace(TmpVectors.Vector3[2]),
        c.scaleToRef(applySH3(1, e), TmpVectors.Vector3[2]),
        this.l1_1.addInPlace(TmpVectors.Vector3[2]),
        c.scaleToRef(applySH3(2, e), TmpVectors.Vector3[2]),
        this.l10.addInPlace(TmpVectors.Vector3[2]),
        c.scaleToRef(applySH3(3, e), TmpVectors.Vector3[2]),
        this.l11.addInPlace(TmpVectors.Vector3[2]),
        c.scaleToRef(applySH3(4, e), TmpVectors.Vector3[2]),
        this.l2_2.addInPlace(TmpVectors.Vector3[2]),
        c.scaleToRef(applySH3(5, e), TmpVectors.Vector3[2]),
        this.l2_1.addInPlace(TmpVectors.Vector3[2]),
        c.scaleToRef(applySH3(6, e), TmpVectors.Vector3[2]),
        this.l20.addInPlace(TmpVectors.Vector3[2]),
        c.scaleToRef(applySH3(7, e), TmpVectors.Vector3[2]),
        this.l21.addInPlace(TmpVectors.Vector3[2]),
        c.scaleToRef(applySH3(8, e), TmpVectors.Vector3[2]),
        this.l22.addInPlace(TmpVectors.Vector3[2])
    }
    ,
    a.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)
    }
    ,
    a.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])
    }
    ,
    a.prototype.convertIrradianceToLambertianRadiance = function() {
        this.scaleInPlace(1 / Math.PI)
    }
    ,
    a.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])
    }
    ,
    a.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
    }
    ,
    a.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
    }
    ,
    a.FromArray = function(e) {
        var i = new a;
        return i.updateFromArray(e)
    }
    ,
    a.FromPolynomial = function(e) {
        var i = new a;
        return i.l00 = e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),
        i.l1_1 = e.y.scale(.977204),
        i.l10 = e.z.scale(.977204),
        i.l11 = e.x.scale(.977204),
        i.l2_2 = e.xy.scale(1.16538),
        i.l2_1 = e.yz.scale(1.16538),
        i.l20 = e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),
        i.l21 = e.zx.scale(1.16538),
        i.l22 = e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),
        i.l1_1.scaleInPlace(-1),
        i.l11.scaleInPlace(-1),
        i.l2_1.scaleInPlace(-1),
        i.l21.scaleInPlace(-1),
        i.scaleInPlace(Math.PI),
        i
    }
    ,
    a
}()
  , SphericalPolynomial = function() {
    function a() {
        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(a.prototype, "preScaledHarmonics", {
        get: function() {
            return this._harmonics || (this._harmonics = SphericalHarmonics.FromPolynomial(this)),
            this._harmonics.preScaled || this._harmonics.preScaleForRendering(),
            this._harmonics
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.addAmbient = function(e) {
        TmpVectors.Vector3[0].copyFromFloats(e.r, e.g, e.b);
        var i = TmpVectors.Vector3[0];
        this.xx.addInPlace(i),
        this.yy.addInPlace(i),
        this.zz.addInPlace(i)
    }
    ,
    a.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)
    }
    ,
    a.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
    }
    ,
    a.FromHarmonics = function(e) {
        var i = new a;
        return i.updateFromHarmonics(e)
    }
    ,
    a.FromArray = function(e) {
        var i = new a;
        return Vector3.FromArrayToRef(e[0], 0, i.x),
        Vector3.FromArrayToRef(e[1], 0, i.y),
        Vector3.FromArrayToRef(e[2], 0, i.z),
        Vector3.FromArrayToRef(e[3], 0, i.xx),
        Vector3.FromArrayToRef(e[4], 0, i.yy),
        Vector3.FromArrayToRef(e[5], 0, i.zz),
        Vector3.FromArrayToRef(e[6], 0, i.yz),
        Vector3.FromArrayToRef(e[7], 0, i.zx),
        Vector3.FromArrayToRef(e[8], 0, i.xy),
        i
    }
    ,
    a
}()
  , 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 a(e, i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt) {
        _ === void 0 && (_ = 1),
        j === void 0 && (j = null),
        $ === void 0 && ($ = 0),
        _e === void 0 && (_e = "postprocess"),
        tt === void 0 && (tt = !1),
        rt === void 0 && (rt = 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,
        d != null ? (this._camera = d,
        this._scene = d.getScene(),
        d.attachPostProcess(this),
        this._engine = this._scene.getEngine(),
        this._scene.postProcesses.push(this),
        this.uniqueId = this._scene.getUniqueId()) : b && (this._engine = b,
        this._engine.postProcesses.push(this)),
        this._options = c,
        this.renderTargetSamplingMode = _ || 1,
        this._reusable = k || !1,
        this._textureType = $,
        this._textureFormat = rt,
        this._samplers = s || [],
        this._samplers.push("textureSampler"),
        this._fragmentUrl = i,
        this._vertexUrl = _e,
        this._parameters = o || [],
        this._parameters.push("scale"),
        this._indexParameters = et,
        this._drawWrapper = new DrawWrapper(this._engine),
        tt || this.updateEffect(j)
    }
    return Object.defineProperty(a.prototype, "samples", {
        get: function() {
            return this._samples
        },
        set: function(e) {
            var i = this;
            this._samples = Math.min(e, this._engine.getCaps().maxMSAASamples),
            this._textures.forEach(function(o) {
                o.samples !== i._samples && i._engine.updateRenderTargetTextureSampleCount(o, i._samples)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getEffectName = function() {
        return this._fragmentUrl
    }
    ,
    Object.defineProperty(a.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(a.prototype, "onSizeChanged", {
        set: function(e) {
            this._onSizeChangedObserver && this.onSizeChangedObservable.remove(this._onSizeChangedObserver),
            this._onSizeChangedObserver = this.onSizeChangedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onApply", {
        set: function(e) {
            this._onApplyObserver && this.onApplyObservable.remove(this._onApplyObserver),
            this._onApplyObserver = this.onApplyObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onBeforeRender", {
        set: function(e) {
            this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),
            this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onAfterRender", {
        set: function(e) {
            this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver),
            this._onAfterRenderObserver = this.onAfterRenderObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "inputTexture", {
        get: function() {
            return this._textures.data[this._currentRenderTextureInd]
        },
        set: function(e) {
            this._forcedOutputTexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.restoreDefaultInputTexture = function() {
        this._forcedOutputTexture && (this._forcedOutputTexture = null,
        this.markTextureDirty())
    }
    ,
    a.prototype.getCamera = function() {
        return this._camera
    }
    ,
    Object.defineProperty(a.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
    }),
    a.prototype.getClassName = function() {
        return "PostProcess"
    }
    ,
    a.prototype.getEngine = function() {
        return this._engine
    }
    ,
    a.prototype.getEffect = function() {
        return this._drawWrapper.effect
    }
    ,
    a.prototype.shareOutputWith = function(e) {
        return this._disposeTextures(),
        this._shareOutputWithPostProcess = e,
        this
    }
    ,
    a.prototype.useOwnOutput = function() {
        this._textures.length == 0 && (this._textures = new SmartArray(2)),
        this._shareOutputWithPostProcess = null
    }
    ,
    a.prototype.updateEffect = function(e, i, o, s, c, d, _, b) {
        e === void 0 && (e = null),
        i === void 0 && (i = null),
        o === void 0 && (o = null),
        this._postProcessDefines = e,
        this._drawWrapper.effect = this._engine.createEffect({
            vertex: _ != null ? _ : this._vertexUrl,
            fragment: b != null ? b : this._fragmentUrl
        }, ["position"], i || this._parameters, o || this._samplers, e !== null ? e : "", void 0, c, d, s || this._indexParameters)
    }
    ,
    a.prototype.isReusable = function() {
        return this._reusable
    }
    ,
    a.prototype.markTextureDirty = function() {
        this.width = -1
    }
    ,
    a.prototype._createRenderTargetTexture = function(e, i, o) {
        o === void 0 && (o = 0);
        for (var s = 0; s < this._textureCache.length; s++)
            if (this._textureCache[s].texture.width === e.width && this._textureCache[s].texture.height === e.height && this._textureCache[s].postProcessChannel === o && this._textureCache[s].texture._generateDepthBuffer === i.generateDepthBuffer)
                return this._textureCache[s].texture;
        var c = this._engine.createRenderTargetTexture(e, i);
        return this._textureCache.push({
            texture: c,
            postProcessChannel: o,
            lastUsedRenderId: -1
        }),
        c
    }
    ,
    a.prototype._flushTextureCache = function() {
        for (var e = this._renderId, i = this._textureCache.length - 1; i >= 0; i--)
            if (e - this._textureCache[i].lastUsedRenderId > 100) {
                for (var o = !1, s = 0; s < this._textures.length; s++)
                    if (this._textures.data[s] === this._textureCache[i].texture) {
                        o = !0;
                        break
                    }
                o || (this._textureCache[i].texture.dispose(),
                this._textureCache.splice(i, 1))
            }
    }
    ,
    a.prototype._resize = function(e, i, o, s, c) {
        this._textures.length > 0 && this._textures.reset(),
        this.width = e,
        this.height = i;
        for (var d = null, _ = 0; _ < o._postProcesses.length; _++)
            if (o._postProcesses[_] !== null) {
                d = o._postProcesses[_];
                break
            }
        var b = {
            width: this.width,
            height: this.height
        }
          , k = {
            generateMipMaps: s,
            generateDepthBuffer: c || d === this,
            generateStencilBuffer: (c || d === this) && this._engine.isStencilEnable,
            samplingMode: this.renderTargetSamplingMode,
            type: this._textureType,
            format: this._textureFormat
        };
        this._textures.push(this._createRenderTargetTexture(b, k, 0)),
        this._reusable && this._textures.push(this._createRenderTargetTexture(b, k, 1)),
        this._texelSize.copyFromFloats(1 / this.width, 1 / this.height),
        this.onSizeChangedObservable.notifyObservers(this)
    }
    ,
    a.prototype.activate = function(e, i, o) {
        var s = this, c, d;
        i === void 0 && (i = null),
        e = e || this._camera;
        var _ = e.getScene()
          , b = _.getEngine()
          , k = b.getCaps().maxTextureSize
          , j = (i ? i.width : this._engine.getRenderWidth(!0)) * this._options | 0
          , $ = (i ? i.height : this._engine.getRenderHeight(!0)) * this._options | 0
          , _e = e.parent;
        _e && (_e.leftCamera == e || _e.rightCamera == e) && (j /= 2);
        var et = this._options.width || j
          , tt = this._options.height || $
          , rt = this.renderTargetSamplingMode !== 7 && this.renderTargetSamplingMode !== 1 && this.renderTargetSamplingMode !== 2;
        if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
            if (this.adaptScaleToCurrentViewport) {
                var it = b.currentViewport;
                it && (et *= it.width,
                tt *= it.height)
            }
            (rt || this.alwaysForcePOT) && (this._options.width || (et = b.needPOTTextures ? Engine.GetExponentOfTwo(et, k, this.scaleMode) : et),
            this._options.height || (tt = b.needPOTTextures ? Engine.GetExponentOfTwo(tt, k, this.scaleMode) : tt)),
            (this.width !== et || this.height !== tt) && this._resize(et, tt, e, rt, o),
            this._textures.forEach(function(st) {
                st.samples !== s.samples && s._engine.updateRenderTargetTextureSampleCount(st, s.samples)
            }),
            this._flushTextureCache(),
            this._renderId++
        }
        var nt;
        if (this._shareOutputWithPostProcess)
            nt = this._shareOutputWithPostProcess.inputTexture;
        else if (this._forcedOutputTexture)
            nt = this._forcedOutputTexture,
            this.width = this._forcedOutputTexture.width,
            this.height = this._forcedOutputTexture.height;
        else {
            nt = this.inputTexture;
            for (var ot = void 0, at = 0; at < this._textureCache.length; at++)
                if (this._textureCache[at].texture === nt) {
                    ot = this._textureCache[at];
                    break
                }
            ot && (ot.lastUsedRenderId = this._renderId)
        }
        return this.enablePixelPerfectMode ? (this._scaleRatio.copyFromFloats(j / et, $ / tt),
        this._engine.bindFramebuffer(nt, 0, j, $, this.forceFullscreenViewport)) : (this._scaleRatio.copyFromFloats(1, 1),
        this._engine.bindFramebuffer(nt, 0, void 0, void 0, this.forceFullscreenViewport)),
        (d = (c = this._engine)._debugInsertMarker) === null || d === void 0 || d.call(c, "post process " + this.name + " input"),
        this.onActivateObservable.notifyObservers(e),
        this.autoClear && this.alphaMode === 0 && this._engine.clear(this.clearColor ? this.clearColor : _.clearColor, _._allowPostProcessClearColor, !0, !0),
        this._reusable && (this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2),
        nt
    }
    ,
    Object.defineProperty(a.prototype, "isSupported", {
        get: function() {
            return this._drawWrapper.effect.isSupported
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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
    }),
    a.prototype.isReady = function() {
        var e, i;
        return (i = (e = this._drawWrapper.effect) === null || e === void 0 ? void 0 : e.isReady()) !== null && i !== void 0 ? i : !1
    }
    ,
    a.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 i;
        return this._shareOutputWithPostProcess ? i = this._shareOutputWithPostProcess.inputTexture : this._forcedOutputTexture ? i = this._forcedOutputTexture : i = this.inputTexture,
        this.externalTextureSamplerBinding || this._drawWrapper.effect._bindTexture("textureSampler", i == null ? void 0 : i.texture),
        this._drawWrapper.effect.setVector2("scale", this._scaleRatio),
        this.onApplyObservable.notifyObservers(this._drawWrapper.effect),
        this._drawWrapper.effect
    }
    ,
    a.prototype._disposeTextures = function() {
        if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
            this._disposeTextureCache();
            return
        }
        this._disposeTextureCache(),
        this._textures.dispose()
    }
    ,
    a.prototype._disposeTextureCache = function() {
        for (var e = this._textureCache.length - 1; e >= 0; e--)
            this._textureCache[e].texture.dispose();
        this._textureCache.length = 0
    }
    ,
    a.prototype.setPrePassRenderer = function(e) {
        return this._prePassEffectConfiguration ? (this._prePassEffectConfiguration = e.addEffectConfiguration(this._prePassEffectConfiguration),
        this._prePassEffectConfiguration.enabled = !0,
        !0) : !1
    }
    ,
    a.prototype.dispose = function(e) {
        e = e || this._camera,
        this._disposeTextures();
        var i;
        if (this._scene && (i = this._scene.postProcesses.indexOf(this),
        i !== -1 && this._scene.postProcesses.splice(i, 1)),
        this._parentContainer) {
            var o = this._parentContainer.postProcesses.indexOf(this);
            o > -1 && this._parentContainer.postProcesses.splice(o, 1),
            this._parentContainer = null
        }
        if (i = this._engine.postProcesses.indexOf(this),
        i !== -1 && this._engine.postProcesses.splice(i, 1),
        !!e) {
            if (e.detachPostProcess(this),
            i = e._postProcesses.indexOf(this),
            i === 0 && e._postProcesses.length > 0) {
                var s = this._camera._getFirstPostProcess();
                s && s.markTextureDirty()
            }
            this.onActivateObservable.clear(),
            this.onAfterRenderObservable.clear(),
            this.onApplyObservable.clear(),
            this.onBeforeRenderObservable.clear(),
            this.onSizeChangedObservable.clear()
        }
    }
    ,
    a.prototype.serialize = function() {
        var e = SerializationHelper.Serialize(this)
          , i = this.getCamera() || this._scene && this._scene.activeCamera;
        return e.customType = "BABYLON." + this.getClassName(),
        e.cameraId = i ? i.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
    }
    ,
    a.prototype.clone = function() {
        var e = this.serialize();
        e._engine = this._engine,
        e.cameraId = null;
        var i = a.Parse(e, this._scene, "");
        return i ? (i.onActivateObservable = this.onActivateObservable.clone(),
        i.onSizeChangedObservable = this.onSizeChangedObservable.clone(),
        i.onApplyObservable = this.onApplyObservable.clone(),
        i.onBeforeRenderObservable = this.onBeforeRenderObservable.clone(),
        i.onAfterRenderObservable = this.onAfterRenderObservable.clone(),
        i._prePassEffectConfiguration = this._prePassEffectConfiguration,
        i) : null
    }
    ,
    a.Parse = function(e, i, o) {
        var s = GetClass(e.customType);
        if (!s || !s._Parse)
            return null;
        var c = i ? i.getCameraById(e.cameraId) : null;
        return s._Parse(e, c, i, o)
    }
    ,
    a._Parse = function(e, i, o, s) {
        return SerializationHelper.Parse(function() {
            return new a(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,i,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)
        }, e, o, s)
    }
    ,
    __decorate([serialize()], a.prototype, "uniqueId", void 0),
    __decorate([serialize()], a.prototype, "name", void 0),
    __decorate([serialize()], a.prototype, "width", void 0),
    __decorate([serialize()], a.prototype, "height", void 0),
    __decorate([serialize()], a.prototype, "renderTargetSamplingMode", void 0),
    __decorate([serializeAsColor4()], a.prototype, "clearColor", void 0),
    __decorate([serialize()], a.prototype, "autoClear", void 0),
    __decorate([serialize()], a.prototype, "alphaMode", void 0),
    __decorate([serialize()], a.prototype, "alphaConstants", void 0),
    __decorate([serialize()], a.prototype, "enablePixelPerfectMode", void 0),
    __decorate([serialize()], a.prototype, "forceFullscreenViewport", void 0),
    __decorate([serialize()], a.prototype, "scaleMode", void 0),
    __decorate([serialize()], a.prototype, "alwaysForcePOT", void 0),
    __decorate([serialize("samples")], a.prototype, "_samples", void 0),
    __decorate([serialize()], a.prototype, "adaptScaleToCurrentViewport", void 0),
    a
}();
RegisterClass("BABYLON.PostProcess", PostProcess);
var name$2_ = "helperFunctions"
  , shader$2_ = `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$2_] = shader$2_;
var name$2Z = "rgbdDecodePixelShader"
  , shader$2Z = `
varying vec2 vUV;
uniform sampler2D textureSampler;
#include<helperFunctions>
void main(void)
{
gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);
}`;
ShaderStore.ShadersStore[name$2Z] = shader$2Z;
var name$2Y = "passPixelShader"
  , shader$2Y = `
varying vec2 vUV;
uniform sampler2D textureSampler;
void main(void)
{
gl_FragColor=texture2D(textureSampler,vUV);
}`;
ShaderStore.ShadersStore[name$2Y] = shader$2Y;
var name$2X = "passCubePixelShader"
  , shader$2X = `
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$2X] = shader$2X;
var PassPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        return s === void 0 && (s = null),
        b === void 0 && (b = 0),
        k === void 0 && (k = !1),
        a.call(this, i, "pass", null, null, o, s, c, d, _, void 0, b, void 0, null, k) || this
    }
    return e.prototype.getClassName = function() {
        return "PassPostProcess"
    }
    ,
    e._Parse = function(i, o, s, c) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,i.options,o,i.renderTargetSamplingMode,i._engine,i.reusable)
        }, i, s, c)
    }
    ,
    e
}(PostProcess);
RegisterClass("BABYLON.PassPostProcess", PassPostProcess);
(function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        s === void 0 && (s = null),
        b === void 0 && (b = 0),
        k === void 0 && (k = !1);
        var j = a.call(this, i, "passCube", null, null, o, s, c, d, _, "#define POSITIVEX", b, void 0, null, k) || this;
        return j._face = 0,
        j
    }
    return Object.defineProperty(e.prototype, "face", {
        get: function() {
            return this._face
        },
        set: function(i) {
            if (!(i < 0 || i > 5))
                switch (this._face = i,
                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(i, o, s, c) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,i.options,o,i.renderTargetSamplingMode,i._engine,i.reusable)
        }, i, s, c)
    }
    ,
    e
}
)(PostProcess);
Engine._RescalePostProcessFactory = function(a) {
    return new PassPostProcess("rescale",1,null,2,a,!1,0)
}
;
function CreateResizedCopy(a, e, i, o) {
    o === void 0 && (o = !0);
    var s = a.getScene()
      , c = s.getEngine()
      , d = new RenderTargetTexture("resized" + a.name,{
        width: e,
        height: i
    },s,!a.noMipmap,!0,a._texture.type,!1,a.samplingMode,!1);
    d.wrapU = a.wrapU,
    d.wrapV = a.wrapV,
    d.uOffset = a.uOffset,
    d.vOffset = a.vOffset,
    d.uScale = a.uScale,
    d.vScale = a.vScale,
    d.uAng = a.uAng,
    d.vAng = a.vAng,
    d.wAng = a.wAng,
    d.coordinatesIndex = a.coordinatesIndex,
    d.level = a.level,
    d.anisotropicFilteringLevel = a.anisotropicFilteringLevel,
    d._texture.isReady = !1,
    a.wrapU = Texture.CLAMP_ADDRESSMODE,
    a.wrapV = Texture.CLAMP_ADDRESSMODE;
    var _ = new PassPostProcess("pass",1,null,o ? Texture.BILINEAR_SAMPLINGMODE : Texture.NEAREST_SAMPLINGMODE,c,!1,0);
    return _.externalTextureSamplerBinding = !0,
    _.getEffect().executeWhenCompiled(function() {
        _.onApply = function(k) {
            k.setTexture("textureSampler", a)
        }
        ;
        var b = d.renderTarget;
        b && (s.postProcessManager.directRender([_], b),
        c.unBindFramebuffer(b),
        d.disposeFramebufferObjects(),
        _.dispose(),
        d.getInternalTexture().isReady = !0)
    }),
    d
}
function ApplyPostProcess(a, e, i, o, s, c) {
    var d = e.getEngine();
    return e.isReady = !1,
    s = s != null ? s : e.samplingMode,
    o = o != null ? o : e.type,
    c = c != null ? c : e.format,
    o === -1 && (o = 0),
    new Promise(function(_) {
        var b = new PostProcess("postprocess",a,null,null,1,null,s,d,!1,void 0,o,void 0,null,!1,c);
        b.externalTextureSamplerBinding = !0;
        var k = d.createRenderTargetTexture({
            width: e.width,
            height: e.height
        }, {
            generateDepthBuffer: !1,
            generateMipMaps: !1,
            generateStencilBuffer: !1,
            samplingMode: s,
            type: o,
            format: c
        });
        b.getEffect().executeWhenCompiled(function() {
            b.onApply = function(j) {
                j._bindTexture("textureSampler", e),
                j.setFloat2("scale", 1, 1)
            }
            ,
            i.postProcessManager.directRender([b], k, !0),
            d.restoreDefaultFramebuffer(),
            d._releaseTexture(e),
            b && b.dispose(),
            k._swapAndDie(e),
            e.type = o,
            e.format = 5,
            e.isReady = !0,
            _(e)
        })
    }
    )
}
var _FloatView, _Int32View;
function ToHalfFloat(a) {
    _FloatView || (_FloatView = new Float32Array(1),
    _Int32View = new Int32Array(_FloatView.buffer)),
    _FloatView[0] = a;
    var e = _Int32View[0]
      , i = e >> 16 & 32768
      , o = e >> 12 & 2047
      , s = e >> 23 & 255;
    return s < 103 ? i : s > 142 ? (i |= 31744,
    i |= (s == 255 ? 0 : 1) && e & 8388607,
    i) : s < 113 ? (o |= 2048,
    i |= (o >> 114 - s) + (o >> 113 - s & 1),
    i) : (i |= s - 112 << 10 | o >> 1,
    i += o & 1,
    i)
}
function FromHalfFloat(a) {
    var e = (a & 32768) >> 15
      , i = (a & 31744) >> 10
      , o = a & 1023;
    return i === 0 ? (e ? -1 : 1) * Math.pow(2, -14) * (o / Math.pow(2, 10)) : i == 31 ? o ? NaN : (e ? -1 : 1) * (1 / 0) : (e ? -1 : 1) * Math.pow(2, i - 15) * (1 + o / Math.pow(2, 10))
}
var TextureTools = {
    CreateResizedCopy,
    ApplyPostProcess,
    ToHalfFloat,
    FromHalfFloat
}
  , RGBDTextureTools = function() {
    function a() {}
    return a.ExpandRGBDTexture = function(e) {
        var i = e._texture;
        if (!(!i || !e.isRGBD)) {
            var o = i.getEngine()
              , s = o.getCaps()
              , c = i.isReady
              , d = !1;
            s.textureHalfFloatRender && s.textureHalfFloatLinearFiltering ? (d = !0,
            i.type = 2) : s.textureFloatRender && s.textureFloatLinearFiltering && (d = !0,
            i.type = 1),
            d && (i.isReady = !1,
            i._isRGBD = !1,
            i.invertY = !1);
            var _ = function() {
                if (d) {
                    var b = new PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,o,!1,void 0,i.type,void 0,null,!1);
                    b.externalTextureSamplerBinding = !0;
                    var k = o.createRenderTargetTexture(i.width, {
                        generateDepthBuffer: !1,
                        generateMipMaps: !1,
                        generateStencilBuffer: !1,
                        samplingMode: i.samplingMode,
                        type: i.type,
                        format: 5
                    });
                    b.getEffect().executeWhenCompiled(function() {
                        b.onApply = function(j) {
                            j._bindTexture("textureSampler", i),
                            j.setFloat2("scale", 1, 1)
                        }
                        ,
                        e.getScene().postProcessManager.directRender([b], k, !0),
                        o.restoreDefaultFramebuffer(),
                        o._releaseTexture(i),
                        b && b.dispose(),
                        k._swapAndDie(i),
                        i.isReady = !0
                    })
                }
            };
            c ? _() : e.onLoadObservable.addOnce(_)
        }
    }
    ,
    a.EncodeTextureToRGBD = function(e, i, o) {
        return o === void 0 && (o = 0),
        ApplyPostProcess("rgbdEncode", e, i, o, 1, 5)
    }
    ,
    a
}()
  , FileFaceOrientation = function() {
    function a(e, i, o, s) {
        this.name = e,
        this.worldAxisForNormal = i,
        this.worldAxisForFileX = o,
        this.worldAxisForFileY = s
    }
    return a
}()
  , CubeMapToSphericalPolynomialTools = function() {
    function a() {}
    return a.ConvertCubeMapTextureToSphericalPolynomial = function(e) {
        var i = this, o;
        if (!e.isCube)
            return null;
        (o = e.getScene()) === null || o === void 0 || o.getEngine().flushFramebuffer();
        var s = e.getSize().width, c = e.readPixels(0, void 0, void 0, !1), d = e.readPixels(1, void 0, void 0, !1), _, b;
        e.isRenderTarget ? (_ = e.readPixels(3, void 0, void 0, !1),
        b = e.readPixels(2, void 0, void 0, !1)) : (_ = e.readPixels(2, void 0, void 0, !1),
        b = e.readPixels(3, void 0, void 0, !1));
        var k = e.readPixels(4, void 0, void 0, !1)
          , j = e.readPixels(5, void 0, void 0, !1)
          , $ = e.gammaSpace
          , _e = 5
          , et = 0;
        return (e.textureType == 1 || e.textureType == 2) && (et = 1),
        new Promise(function(tt, rt) {
            Promise.all([d, c, _, b, k, j]).then(function(it) {
                var nt = it[0]
                  , ot = it[1]
                  , at = it[2]
                  , st = it[3]
                  , ut = it[4]
                  , ct = it[5]
                  , lt = {
                    size: s,
                    right: ot,
                    left: nt,
                    up: at,
                    down: st,
                    front: ut,
                    back: ct,
                    format: _e,
                    type: et,
                    gammaSpace: $
                };
                tt(i.ConvertCubeMapToSphericalPolynomial(lt))
            })
        }
        )
    }
    ,
    a.ConvertCubeMapToSphericalPolynomial = function(e) {
        for (var i = new SphericalHarmonics, o = 0, s = 2 / e.size, c = s, d = s * .5 - 1, _ = 0; _ < 6; _++)
            for (var b = this.FileFaces[_], k = e[b.name], j = d, $ = e.format === 5 ? 4 : 3, _e = 0; _e < e.size; _e++) {
                for (var et = d, tt = 0; tt < e.size; tt++) {
                    var rt = b.worldAxisForFileX.scale(et).add(b.worldAxisForFileY.scale(j)).add(b.worldAxisForNormal);
                    rt.normalize();
                    var it = Math.pow(1 + et * et + j * j, -3 / 2)
                      , nt = k[_e * e.size * $ + tt * $ + 0]
                      , ot = k[_e * e.size * $ + tt * $ + 1]
                      , at = k[_e * e.size * $ + tt * $ + 2];
                    isNaN(nt) && (nt = 0),
                    isNaN(ot) && (ot = 0),
                    isNaN(at) && (at = 0),
                    e.type === 0 && (nt /= 255,
                    ot /= 255,
                    at /= 255),
                    e.gammaSpace && (nt = Math.pow(Scalar.Clamp(nt), ToLinearSpace),
                    ot = Math.pow(Scalar.Clamp(ot), ToLinearSpace),
                    at = Math.pow(Scalar.Clamp(at), ToLinearSpace));
                    var st = 4096;
                    nt = Scalar.Clamp(nt, 0, st),
                    ot = Scalar.Clamp(ot, 0, st),
                    at = Scalar.Clamp(at, 0, st);
                    var ut = new Color3(nt,ot,at);
                    i.addLight(rt, ut, it),
                    o += it,
                    et += s
                }
                j += c
            }
        var ct = 4 * Math.PI
          , lt = 6
          , ft = ct * lt / 6
          , ht = ft / o;
        return i.scaleInPlace(ht),
        i.convertIncidentRadianceToIrradiance(),
        i.convertIrradianceToLambertianRadiance(),
        SphericalPolynomial.FromHarmonics(i)
    }
    ,
    a.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))],
    a
}();
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 a = 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) {
                    a._texture._sphericalPolynomial = e,
                    a._texture._sphericalPolynomialComputed = !0
                })),
                null
        }
        return null
    },
    set: function(a) {
        this._texture && (this._texture._sphericalPolynomial = a)
    },
    enumerable: !0,
    configurable: !0
});
var name$2W = "rgbdEncodePixelShader"
  , shader$2W = `
varying vec2 vUV;
uniform sampler2D textureSampler;
#include<helperFunctions>
void main(void)
{
gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);
}`;
ShaderStore.ShadersStore[name$2W] = shader$2W;
var defaultEnvironmentTextureImageType = "image/png"
  , currentVersion = 2
  , _MagicBytes = [134, 22, 135, 150, 246, 214, 150, 54];
function GetEnvInfo(a) {
    for (var e = new DataView(a.buffer,a.byteOffset,a.byteLength), i = 0, o = 0; o < _MagicBytes.length; o++)
        if (e.getUint8(i++) !== _MagicBytes[o])
            return Logger$2.Error("Not a babylon environment map"),
            null;
    for (var s = "", c = 0; c = e.getUint8(i++); )
        s += String.fromCharCode(c);
    var d = JSON.parse(s);
    return d = normalizeEnvInfo(d),
    d.specular && (d.specular.specularDataPosition = i,
    d.specular.lodGenerationScale = d.specular.lodGenerationScale || .8),
    d
}
function normalizeEnvInfo(a) {
    if (a.version > currentVersion)
        throw new Error('Unsupported babylon environment map version "' + a.version + '". Latest supported version is "' + currentVersion + '".');
    return a.version === 2 || (a = __assign(__assign({}, a), {
        version: 2,
        imageType: defaultEnvironmentTextureImageType
    })),
    a
}
function CreateImageDataArrayBufferViews(a, e) {
    e = normalizeEnvInfo(e);
    var i = e.specular
      , o = Scalar.Log2(e.width);
    if (o = Math.round(o) + 1,
    i.mipmaps.length !== 6 * o)
        throw new Error('Unsupported specular mipmaps number "' + i.mipmaps.length + '"');
    for (var s = new Array(o), c = 0; c < o; c++) {
        s[c] = new Array(6);
        for (var d = 0; d < 6; d++) {
            var _ = i.mipmaps[c * 6 + d];
            s[c][d] = new Uint8Array(a.buffer,a.byteOffset + i.specularDataPosition + _.position,_.length)
        }
    }
    return s
}
function UploadEnvLevelsAsync(a, e, i) {
    i = normalizeEnvInfo(i);
    var o = i.specular;
    if (!o)
        return Promise.resolve();
    a._lodGenerationScale = o.lodGenerationScale;
    var s = CreateImageDataArrayBufferViews(e, i);
    return UploadLevelsAsync(a, s, i.imageType)
}
function _OnImageReadyAsync(a, e, i, o, s, c, d, _, b, k, j) {
    return new Promise(function($, _e) {
        if (i) {
            var et = e.createTexture(null, !0, !0, null, 1, null, function(rt) {
                _e(rt)
            }, a);
            o.getEffect().executeWhenCompiled(function() {
                o.externalTextureSamplerBinding = !0,
                o.onApply = function(rt) {
                    rt._bindTexture("textureSampler", et),
                    rt.setFloat2("scale", 1, e._features.needsInvertingBitmap && a instanceof ImageBitmap ? -1 : 1)
                }
                ,
                e.scenes.length && (e.scenes[0].postProcessManager.directRender([o], k, !0, c, d),
                e.restoreDefaultFramebuffer(),
                et.dispose(),
                URL.revokeObjectURL(s),
                $())
            })
        } else {
            if (e._uploadImageToTexture(j, a, c, d),
            _) {
                var tt = b[d];
                tt && e._uploadImageToTexture(tt._texture, a, c, 0)
            }
            $()
        }
    }
    )
}
function UploadLevelsAsync(a, e, i) {
    if (i === void 0 && (i = defaultEnvironmentTextureImageType),
    !Tools.IsExponentOfTwo(a.width))
        throw new Error("Texture size must be a power of two");
    var o = Scalar.ILog2(a.width) + 1
      , s = a.getEngine()
      , c = !1
      , d = !1
      , _ = null
      , b = null
      , k = null
      , j = s.getCaps();
    if (a.format = 5,
    a.type = 0,
    a.generateMipMaps = !0,
    a._cachedAnisotropicFilteringLevel = null,
    s.updateTextureSamplingMode(3, a),
    j.textureLOD ? s._features.supportRenderAndCopyToLodForFloatTextures ? j.textureHalfFloatRender && j.textureHalfFloatLinearFiltering ? (c = !0,
    a.type = 2) : j.textureFloatRender && j.textureFloatLinearFiltering && (c = !0,
    a.type = 1) : c = !1 : (c = !1,
    d = !0,
    k = {}),
    c)
        _ = new PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,a.type,void 0,null,!1),
        a._isRGBD = !1,
        a.invertY = !1,
        b = s.createRenderTargetCubeTexture(a.width, {
            generateDepthBuffer: !1,
            generateMipMaps: !0,
            generateStencilBuffer: !1,
            samplingMode: 3,
            type: a.type,
            format: 5
        });
    else if (a._isRGBD = !0,
    a.invertY = !0,
    d)
        for (var $ = 3, _e = a._lodGenerationScale, et = a._lodGenerationOffset, tt = 0; tt < $; tt++) {
            var rt = tt / ($ - 1)
              , it = 1 - rt
              , nt = et
              , ot = (o - 1) * _e + et
              , at = nt + (ot - nt) * it
              , st = Math.round(Math.min(Math.max(at, 0), ot))
              , ut = new InternalTexture(s,InternalTextureSource.Temp);
            ut.isCube = !0,
            ut.invertY = !0,
            ut.generateMipMaps = !1,
            s.updateTextureSamplingMode(2, ut);
            var ct = new BaseTexture(null);
            switch (ct.isCube = !0,
            ct._texture = ut,
            k[st] = ct,
            tt) {
            case 0:
                a._lodTextureLow = ct;
                break;
            case 1:
                a._lodTextureMid = ct;
                break;
            case 2:
                a._lodTextureHigh = ct;
                break
            }
        }
    for (var lt = [], ft = function(mt) {
        for (var vt = function(Et) {
            var At = e[mt][Et]
              , gt = new Blob([At],{
                type: i
            })
              , St = URL.createObjectURL(gt)
              , xt = void 0;
            if (typeof Image == "undefined" || s._features.forceBitmapOverHTMLImageElement)
                xt = s.createImageBitmap(gt, {
                    premultiplyAlpha: "none"
                }).then(function(Rt) {
                    return _OnImageReadyAsync(Rt, s, c, _, St, Et, mt, d, k, b, a)
                });
            else {
                var bt = new Image;
                bt.src = St,
                xt = new Promise(function(Rt, Mt) {
                    bt.onload = function() {
                        _OnImageReadyAsync(bt, s, c, _, St, Et, mt, d, k, b, a).then(function() {
                            return Rt()
                        }).catch(function(Pt) {
                            Mt(Pt)
                        })
                    }
                    ,
                    bt.onerror = function(Pt) {
                        Mt(Pt)
                    }
                }
                )
            }
            lt.push(xt)
        }, yt = 0; yt < 6; yt++)
            vt(yt)
    }, tt = 0; tt < e.length; tt++)
        ft(tt);
    if (e.length < o) {
        var ht = void 0
          , pt = Math.pow(2, o - 1 - e.length)
          , dt = pt * pt * 4;
        switch (a.type) {
        case 0:
            {
                ht = new Uint8Array(dt);
                break
            }
        case 2:
            {
                ht = new Uint16Array(dt);
                break
            }
        case 1:
            {
                ht = new Float32Array(dt);
                break
            }
        }
        for (var tt = e.length; tt < o; tt++)
            for (var _t = 0; _t < 6; _t++)
                s._uploadArrayBufferViewToTexture(a, ht, _t, tt)
    }
    return Promise.all(lt).then(function() {
        b && (s._releaseTexture(a),
        b._swapAndDie(a)),
        _ && _.dispose(),
        d && (a._lodTextureHigh && a._lodTextureHigh._texture && (a._lodTextureHigh._texture.isReady = !0),
        a._lodTextureMid && a._lodTextureMid._texture && (a._lodTextureMid._texture.isReady = !0),
        a._lodTextureLow && a._lodTextureLow._texture && (a._lodTextureLow._texture.isReady = !0))
    })
}
function UploadEnvSpherical(a, e) {
    e = normalizeEnvInfo(e);
    var i = e.irradiance;
    if (!!i) {
        var o = new SphericalPolynomial;
        Vector3.FromArrayToRef(i.x, 0, o.x),
        Vector3.FromArrayToRef(i.y, 0, o.y),
        Vector3.FromArrayToRef(i.z, 0, o.z),
        Vector3.FromArrayToRef(i.xx, 0, o.xx),
        Vector3.FromArrayToRef(i.yy, 0, o.yy),
        Vector3.FromArrayToRef(i.zz, 0, o.zz),
        Vector3.FromArrayToRef(i.yz, 0, o.yz),
        Vector3.FromArrayToRef(i.zx, 0, o.zx),
        Vector3.FromArrayToRef(i.xy, 0, o.xy),
        a._sphericalPolynomial = o
    }
}
function _UpdateRGBDAsync(a, e, i, o, s) {
    var c = a.getEngine().createRawCubeTexture(null, a.width, a.format, a.type, a.generateMipMaps, a.invertY, a.samplingMode, a._compression)
      , d = UploadLevelsAsync(c, e).then(function() {
        return a
    });
    return a.onRebuildCallback = function(_) {
        return {
            proxy: d,
            isReady: !0,
            isAsync: !0
        }
    }
    ,
    a._source = InternalTextureSource.CubeRawRGBD,
    a._bufferViewArrayArray = e,
    a._lodGenerationScale = o,
    a._lodGenerationOffset = s,
    a._sphericalPolynomial = i,
    UploadLevelsAsync(a, e).then(function() {
        return a.isReady = !0,
        a
    })
}
function ExtractBetweenMarkers(a, e, i, o) {
    for (var s = o, c = 0, d = ""; s < i.length; ) {
        var _ = i.charAt(s);
        if (d)
            _ === d ? d === '"' || d === "'" ? i.charAt(s - 1) !== "\\" && (d = "") : d = "" : d === "*/" && _ === "*" && s + 1 < i.length && (i.charAt(s + 1) === "/" && (d = ""),
            d === "" && s++);
        else
            switch (_) {
            case a:
                c++;
                break;
            case e:
                c--;
                break;
            case '"':
            case "'":
            case "`":
                d = _;
                break;
            case "/":
                if (s + 1 < i.length) {
                    var b = i.charAt(s + 1);
                    b === "/" ? d = `
` : b === "*" && (d = "*/")
                }
                break
            }
        if (s++,
        c === 0)
            break
    }
    return c === 0 ? s - 1 : -1
}
function SkipWhitespaces(a, e) {
    for (; e < a.length; ) {
        var i = a[e];
        if (i !== " " && i !== `
` && i !== "\r" && i !== "	" && i !== `
` && i !== "\xA0")
            break;
        e++
    }
    return e
}
function IsIdentifierChar(a) {
    var e = a.charCodeAt(0);
    return e >= 48 && e <= 57 || e >= 65 && e <= 90 || e >= 97 && e <= 122 || e == 95
}
function RemoveComments(a) {
    for (var e = 0, i = "", o = !1, s = []; e < a.length; ) {
        var c = a.charAt(e);
        if (i)
            c === i ? i === '"' || i === "'" ? (a.charAt(e - 1) !== "\\" && (i = ""),
            s.push(c)) : (i = "",
            o = !1) : i === "*/" && c === "*" && e + 1 < a.length ? (a.charAt(e + 1) === "/" && (i = ""),
            i === "" && (o = !1,
            e++)) : o || s.push(c);
        else {
            switch (c) {
            case '"':
            case "'":
            case "`":
                i = c;
                break;
            case "/":
                if (e + 1 < a.length) {
                    var d = a.charAt(e + 1);
                    d === "/" ? (i = `
`,
                    o = !0) : d === "*" && (i = "*/",
                    o = !0)
                }
                break
            }
            o || s.push(c)
        }
        e++
    }
    return s.join("")
}
function FindBackward(a, e, i) {
    for (; e >= 0 && a.charAt(e) !== i; )
        e--;
    return e
}
function EscapeRegExp(a) {
    return a.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
var ShaderCodeInliner = function() {
    function a(e, i) {
        i === void 0 && (i = 20),
        this.debug = !1,
        this._sourceCode = e,
        this._numMaxIterations = i,
        this._functionDescr = [],
        this.inlineToken = "#define inline"
    }
    return Object.defineProperty(a.prototype, "code", {
        get: function() {
            return this._sourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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.")
    }
    ,
    a.prototype._collectFunctions = function() {
        for (var e = 0; e < this._sourceCode.length; ) {
            var i = this._sourceCode.indexOf(this.inlineToken, e);
            if (i < 0)
                break;
            var o = this._sourceCode.indexOf("(", i + this.inlineToken.length);
            if (o < 0) {
                this.debug && console.warn("Could not find the opening parenthesis after the token. startIndex=" + e),
                e = i + this.inlineToken.length;
                continue
            }
            var s = a._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(i + this.inlineToken.length, o));
            if (!s) {
                this.debug && console.warn("Could not extract the name/type of the function from: " + this._sourceCode.substring(i + this.inlineToken.length, o)),
                e = i + this.inlineToken.length;
                continue
            }
            var c = [s[3], s[4]]
              , d = c[0]
              , _ = c[1]
              , b = ExtractBetweenMarkers("(", ")", this._sourceCode, o);
            if (b < 0) {
                this.debug && console.warn("Could not extract the parameters the function '" + _ + "' (type=" + d + "). funcParamsStartIndex=" + o),
                e = i + this.inlineToken.length;
                continue
            }
            var k = this._sourceCode.substring(o + 1, b)
              , j = SkipWhitespaces(this._sourceCode, b + 1);
            if (j === this._sourceCode.length) {
                this.debug && console.warn("Could not extract the body of the function '" + _ + "' (type=" + d + "). funcParamsEndIndex=" + b),
                e = i + this.inlineToken.length;
                continue
            }
            var $ = ExtractBetweenMarkers("{", "}", this._sourceCode, j);
            if ($ < 0) {
                this.debug && console.warn("Could not extract the body of the function '" + _ + "' (type=" + d + "). funcBodyStartIndex=" + j),
                e = i + this.inlineToken.length;
                continue
            }
            for (var _e = this._sourceCode.substring(j, $ + 1), et = RemoveComments(k).split(","), tt = [], rt = 0; rt < et.length; ++rt) {
                var it = et[rt].trim()
                  , nt = it.lastIndexOf(" ");
                nt >= 0 && tt.push(it.substring(nt + 1))
            }
            d !== "void" && tt.push("return"),
            this._functionDescr.push({
                name: _,
                type: d,
                parameters: tt,
                body: _e,
                callIndex: 0
            }),
            e = $ + 1;
            var ot = i > 0 ? this._sourceCode.substring(0, i) : ""
              , at = $ + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring($ + 1) : "";
            this._sourceCode = ot + at,
            e -= $ + 1 - i
        }
        this.debug && console.log("Collect functions: " + this._functionDescr.length + " functions found. functionDescr=", this._functionDescr)
    }
    ,
    a.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
    }
    ,
    a.prototype._replaceFunctionCallsByCode = function() {
        for (var e = !1, i = 0, o = this._functionDescr; i < o.length; i++)
            for (var s = o[i], c = s.name, d = s.type, _ = s.parameters, b = s.body, k = 0; k < this._sourceCode.length; ) {
                var j = this._sourceCode.indexOf(c, k);
                if (j < 0)
                    break;
                if (j === 0 || IsIdentifierChar(this._sourceCode.charAt(j - 1))) {
                    k = j + c.length;
                    continue
                }
                var $ = SkipWhitespaces(this._sourceCode, j + c.length);
                if ($ === this._sourceCode.length || this._sourceCode.charAt($) !== "(") {
                    k = j + c.length;
                    continue
                }
                var _e = ExtractBetweenMarkers("(", ")", this._sourceCode, $);
                if (_e < 0) {
                    this.debug && console.warn("Could not extract the parameters of the function call. Function '" + c + "' (type=" + d + "). callParamsStartIndex=" + $),
                    k = j + c.length;
                    continue
                }
                var et = this._sourceCode.substring($ + 1, _e)
                  , tt = function(ht) {
                    for (var pt = [], dt = 0, _t = 0; dt < ht.length; ) {
                        if (ht.charAt(dt) === "(") {
                            var mt = ExtractBetweenMarkers("(", ")", ht, dt);
                            if (mt < 0)
                                return null;
                            dt = mt
                        } else
                            ht.charAt(dt) === "," && (pt.push(ht.substring(_t, dt)),
                            _t = dt + 1);
                        dt++
                    }
                    return _t < dt && pt.push(ht.substring(_t, dt)),
                    pt
                }
                  , rt = tt(RemoveComments(et));
                if (rt === null) {
                    this.debug && console.warn("Invalid function call: can't extract the parameters of the function call. Function '" + c + "' (type=" + d + "). callParamsStartIndex=" + $ + ", callParams=" + et),
                    k = j + c.length;
                    continue
                }
                for (var it = [], nt = 0; nt < rt.length; ++nt) {
                    var ot = rt[nt].trim();
                    it.push(ot)
                }
                var at = d !== "void" ? c + "_" + s.callIndex++ : null;
                if (at && it.push(at + " ="),
                it.length !== _.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 '" + c + "' (type=" + d + "). function parameters=" + _ + ", call parameters=" + it),
                    k = j + c.length;
                    continue
                }
                k = _e + 1;
                var st = this._replaceNames(b, _, it)
                  , ut = j > 0 ? this._sourceCode.substring(0, j) : ""
                  , ct = _e + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(_e + 1) : "";
                if (at) {
                    var lt = FindBackward(this._sourceCode, j - 1, `
`);
                    ut = this._sourceCode.substring(0, lt + 1);
                    var ft = this._sourceCode.substring(lt + 1, j);
                    this._sourceCode = ut + d + " " + at + `;
` + st + `
` + ft + at + ct,
                    this.debug && console.log("Replace function call by code. Function '" + c + "' (type=" + d + "). injectDeclarationIndex=" + lt + ", call parameters=" + it)
                } else
                    this._sourceCode = ut + st + ct,
                    k += st.length - (_e + 1 - j),
                    this.debug && console.log("Replace function call by code. Function '" + c + "' (type=" + d + "). functionCallIndex=" + j + ", call parameters=" + it);
                e = !0
            }
        return e
    }
    ,
    a.prototype._replaceNames = function(e, i, o) {
        for (var s = function(d) {
            var _ = new RegExp(EscapeRegExp(i[d]),"g")
              , b = i[d].length
              , k = o[d];
            e = e.replace(_, function(j) {
                for (var $ = [], _e = 1; _e < arguments.length; _e++)
                    $[_e - 1] = arguments[_e];
                var et = $[0];
                return IsIdentifierChar(e.charAt(et - 1)) || IsIdentifierChar(e.charAt(et + b)) ? i[d] : k
            })
        }, c = 0; c < i.length; ++c)
            s(c);
        return e
    }
    ,
    a._RegexpFindFunctionNameAndType = /((\s+?)(\w+)\s+(\w+)\s*?)$/,
    a
}()
  , NativePipelineContext = function() {
    function a(e) {
        this.isAsync = !1,
        this.isReady = !1,
        this._valueCache = {},
        this.engine = e
    }
    return a.prototype._getVertexShaderCode = function() {
        return null
    }
    ,
    a.prototype._getFragmentShaderCode = function() {
        return null
    }
    ,
    a.prototype._handlesSpectorRebuildCallback = function(e) {
        throw new Error("Not implemented")
    }
    ,
    a.prototype._fillEffectInformation = function(e, i, o, s, c, d, _, b) {
        var k = this.engine;
        if (k.supportsUniformBuffers)
            for (var j in i)
                e.bindUniformBlock(j, i[j]);
        var $ = this.engine.getUniforms(this, o);
        $.forEach(function(tt, rt) {
            s[o[rt]] = tt
        }),
        this._uniforms = s;
        var _e;
        for (_e = 0; _e < c.length; _e++) {
            var et = e.getUniform(c[_e]);
            et == null && (c.splice(_e, 1),
            _e--)
        }
        c.forEach(function(tt, rt) {
            d[tt] = rt
        }),
        b.push.apply(b, k.getAttributes(this, _))
    }
    ,
    a.prototype.dispose = function() {
        this._uniforms = {}
    }
    ,
    a.prototype._cacheMatrix = function(e, i) {
        var o = this._valueCache[e]
          , s = i.updateFlag;
        return o !== void 0 && o === s ? !1 : (this._valueCache[e] = s,
        !0)
    }
    ,
    a.prototype._cacheFloat2 = function(e, i, o) {
        var s = this._valueCache[e];
        if (!s)
            return s = [i, o],
            this._valueCache[e] = s,
            !0;
        var c = !1;
        return s[0] !== i && (s[0] = i,
        c = !0),
        s[1] !== o && (s[1] = o,
        c = !0),
        c
    }
    ,
    a.prototype._cacheFloat3 = function(e, i, o, s) {
        var c = this._valueCache[e];
        if (!c)
            return c = [i, o, s],
            this._valueCache[e] = c,
            !0;
        var d = !1;
        return c[0] !== i && (c[0] = i,
        d = !0),
        c[1] !== o && (c[1] = o,
        d = !0),
        c[2] !== s && (c[2] = s,
        d = !0),
        d
    }
    ,
    a.prototype._cacheFloat4 = function(e, i, o, s, c) {
        var d = this._valueCache[e];
        if (!d)
            return d = [i, o, s, c],
            this._valueCache[e] = d,
            !0;
        var _ = !1;
        return d[0] !== i && (d[0] = i,
        _ = !0),
        d[1] !== o && (d[1] = o,
        _ = !0),
        d[2] !== s && (d[2] = s,
        _ = !0),
        d[3] !== c && (d[3] = c,
        _ = !0),
        _
    }
    ,
    a.prototype.setInt = function(e, i) {
        var o = this._valueCache[e];
        o !== void 0 && o === i || this.engine.setInt(this._uniforms[e], i) && (this._valueCache[e] = i)
    }
    ,
    a.prototype.setInt2 = function(e, i, o) {
        this._cacheFloat2(e, i, o) && (this.engine.setInt2(this._uniforms[e], i, o) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setInt3 = function(e, i, o, s) {
        this._cacheFloat3(e, i, o, s) && (this.engine.setInt3(this._uniforms[e], i, o, s) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setInt4 = function(e, i, o, s, c) {
        this._cacheFloat4(e, i, o, s, c) && (this.engine.setInt4(this._uniforms[e], i, o, s, c) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setIntArray = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setIntArray(this._uniforms[e], i)
    }
    ,
    a.prototype.setIntArray2 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setIntArray2(this._uniforms[e], i)
    }
    ,
    a.prototype.setIntArray3 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setIntArray3(this._uniforms[e], i)
    }
    ,
    a.prototype.setIntArray4 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setIntArray4(this._uniforms[e], i)
    }
    ,
    a.prototype.setFloatArray = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setFloatArray(this._uniforms[e], i)
    }
    ,
    a.prototype.setFloatArray2 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setFloatArray2(this._uniforms[e], i)
    }
    ,
    a.prototype.setFloatArray3 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setFloatArray3(this._uniforms[e], i)
    }
    ,
    a.prototype.setFloatArray4 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setFloatArray4(this._uniforms[e], i)
    }
    ,
    a.prototype.setArray = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setArray(this._uniforms[e], i)
    }
    ,
    a.prototype.setArray2 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setArray2(this._uniforms[e], i)
    }
    ,
    a.prototype.setArray3 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setArray3(this._uniforms[e], i)
    }
    ,
    a.prototype.setArray4 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setArray4(this._uniforms[e], i)
    }
    ,
    a.prototype.setMatrices = function(e, i) {
        !i || (this._valueCache[e] = null,
        this.engine.setMatrices(this._uniforms[e], i))
    }
    ,
    a.prototype.setMatrix = function(e, i) {
        this._cacheMatrix(e, i) && (this.engine.setMatrices(this._uniforms[e], i.toArray()) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setMatrix3x3 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setMatrix3x3(this._uniforms[e], i)
    }
    ,
    a.prototype.setMatrix2x2 = function(e, i) {
        this._valueCache[e] = null,
        this.engine.setMatrix2x2(this._uniforms[e], i)
    }
    ,
    a.prototype.setFloat = function(e, i) {
        var o = this._valueCache[e];
        o !== void 0 && o === i || this.engine.setFloat(this._uniforms[e], i) && (this._valueCache[e] = i)
    }
    ,
    a.prototype.setBool = function(e, i) {
        var o = this._valueCache[e];
        o !== void 0 && o === i || this.engine.setInt(this._uniforms[e], i ? 1 : 0) && (this._valueCache[e] = i ? 1 : 0)
    }
    ,
    a.prototype.setVector2 = function(e, i) {
        this._cacheFloat2(e, i.x, i.y) && (this.engine.setFloat2(this._uniforms[e], i.x, i.y) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setFloat2 = function(e, i, o) {
        this._cacheFloat2(e, i, o) && (this.engine.setFloat2(this._uniforms[e], i, o) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setVector3 = function(e, i) {
        this._cacheFloat3(e, i.x, i.y, i.z) && (this.engine.setFloat3(this._uniforms[e], i.x, i.y, i.z) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setFloat3 = function(e, i, o, s) {
        this._cacheFloat3(e, i, o, s) && (this.engine.setFloat3(this._uniforms[e], i, o, s) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setVector4 = function(e, i) {
        this._cacheFloat4(e, i.x, i.y, i.z, i.w) && (this.engine.setFloat4(this._uniforms[e], i.x, i.y, i.z, i.w) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setFloat4 = function(e, i, o, s, c) {
        this._cacheFloat4(e, i, o, s, c) && (this.engine.setFloat4(this._uniforms[e], i, o, s, c) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setColor3 = function(e, i) {
        this._cacheFloat3(e, i.r, i.g, i.b) && (this.engine.setFloat3(this._uniforms[e], i.r, i.g, i.b) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setColor4 = function(e, i, o) {
        this._cacheFloat4(e, i.r, i.g, i.b, o) && (this.engine.setFloat4(this._uniforms[e], i.r, i.g, i.b, o) || (this._valueCache[e] = null))
    }
    ,
    a.prototype.setDirectColor4 = function(e, i) {
        this._cacheFloat4(e, i.r, i.g, i.b, i.a) && (this.engine.setFloat4(this._uniforms[e], i.r, i.g, i.b, i.a) || (this._valueCache[e] = null))
    }
    ,
    a
}()
  , NativeRenderTargetWrapper = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        var d = a.call(this, i, o, s, c) || this;
        return d.__framebuffer = null,
        d.__framebufferDepthStencil = null,
        d._engine = c,
        d
    }
    return Object.defineProperty(e.prototype, "_framebuffer", {
        get: function() {
            return this.__framebuffer
        },
        set: function(i) {
            this.__framebuffer && this._engine._releaseFramebufferObjects(this.__framebuffer),
            this.__framebuffer = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "_framebufferDepthStencil", {
        get: function() {
            return this.__framebufferDepthStencil
        },
        set: function(i) {
            this.__framebufferDepthStencil && this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),
            this.__framebufferDepthStencil = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.dispose = function(i) {
        i === void 0 && (i = !1),
        this._framebuffer = null,
        this._framebufferDepthStencil = null,
        a.prototype.dispose.call(this, i)
    }
    ,
    e
}(RenderTargetWrapper)
  , NativeDataBuffer = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e
}(DataBuffer)
  , CommandBufferEncoder = function() {
    function a(e) {
        this._engine = e,
        this._pending = new Array,
        this._isCommandBufferScopeActive = !1,
        this._commandStream = NativeEngine._createNativeDataStream(),
        this._engine.setCommandDataStream(this._commandStream)
    }
    return a.prototype.beginCommandScope = function() {
        if (this._isCommandBufferScopeActive)
            throw new Error("Command scope already active.");
        this._isCommandBufferScopeActive = !0
    }
    ,
    a.prototype.endCommandScope = function() {
        if (!this._isCommandBufferScopeActive)
            throw new Error("Command scope is not active.");
        this._isCommandBufferScopeActive = !1,
        this._submit()
    }
    ,
    a.prototype.startEncodingCommand = function(e) {
        this._commandStream.writeNativeData(e)
    }
    ,
    a.prototype.encodeCommandArgAsUInt32 = function(e) {
        this._commandStream.writeUint32(e)
    }
    ,
    a.prototype.encodeCommandArgAsUInt32s = function(e) {
        this._commandStream.writeUint32Array(e)
    }
    ,
    a.prototype.encodeCommandArgAsInt32 = function(e) {
        this._commandStream.writeInt32(e)
    }
    ,
    a.prototype.encodeCommandArgAsInt32s = function(e) {
        this._commandStream.writeInt32Array(e)
    }
    ,
    a.prototype.encodeCommandArgAsFloat32 = function(e) {
        this._commandStream.writeFloat32(e)
    }
    ,
    a.prototype.encodeCommandArgAsFloat32s = function(e) {
        this._commandStream.writeFloat32Array(e)
    }
    ,
    a.prototype.encodeCommandArgAsNativeData = function(e) {
        this._commandStream.writeNativeData(e),
        this._pending.push(e)
    }
    ,
    a.prototype.finishEncodingCommand = function() {
        this._isCommandBufferScopeActive || this._submit()
    }
    ,
    a.prototype._submit = function() {
        this._engine.submitCommands(),
        this._pending.length = 0
    }
    ,
    a
}()
  , NativeEngine = function(a) {
    __extends(e, a);
    function e(i) {
        i === void 0 && (i = {});
        var o = a.call(this, null, !1, void 0, i.adaptToDeviceRatio) || this;
        if (o._engine = new _native.Engine,
        o._camera = _native.Camera ? new _native.Camera : null,
        o._commandBufferEncoder = new CommandBufferEncoder(o._engine),
        o._boundBuffersVertexArray = null,
        o._currentDepthTest = _native.Engine.DEPTH_TEST_LEQUAL,
        o._stencilTest = !1,
        o._stencilMask = 255,
        o._stencilFunc = 519,
        o._stencilFuncRef = 0,
        o._stencilFuncMask = 255,
        o._stencilOpStencilFail = 7680,
        o._stencilOpDepthFail = 7680,
        o._stencilOpStencilDepthPass = 7681,
        o._zOffset = 0,
        o._zOffsetUnits = 0,
        o._depthWrite = !0,
        _native.Engine.PROTOCOL_VERSION !== e.PROTOCOL_VERSION)
            throw new Error("Protocol version mismatch: " + _native.Engine.PROTOCOL_VERSION + " (Native) !== " + e.PROTOCOL_VERSION + " (JS)");
        o._webGLVersion = 2,
        o.disableUniformBuffers = !0,
        o._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
        },
        o._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(d, _, b, k) {
            Tools.LoadFile(d, function(j) {
                Function(j).apply(null),
                _ && _()
            }, void 0, void 0, !1, function(j, $) {
                b && b("LoadScript Error", $)
            })
        }
        ,
        typeof URL == "undefined" && (window.URL = {
            createObjectURL: function() {},
            revokeObjectURL: function() {}
        }),
        typeof Blob == "undefined" && (window.Blob = function(d) {
            return d
        }
        );
        var s = window && window.devicePixelRatio || 1;
        o._hardwareScalingLevel = i.adaptToDeviceRatio ? s : 1,
        o.resize();
        var c = o.getDepthFunction();
        return c && o.setDepthFunction(c),
        o._shaderProcessor = new WebGL2ShaderProcessor,
        o.onNewSceneAddedObservable.add(function(d) {
            var _ = d.render;
            d.render = function() {
                for (var b = [], k = 0; k < arguments.length; k++)
                    b[k] = arguments[k];
                o._commandBufferEncoder.beginCommandScope(),
                _.apply(d, b),
                o._commandBufferEncoder.endCommandScope()
            }
        }),
        o
    }
    return e.prototype.getHardwareScalingLevel = function() {
        return this._engine.getHardwareScalingLevel()
    }
    ,
    e.prototype.setHardwareScalingLevel = function(i) {
        this._engine.setHardwareScalingLevel(i)
    }
    ,
    e.prototype.dispose = function() {
        a.prototype.dispose.call(this),
        this._boundBuffersVertexArray && this._deleteVertexArray(this._boundBuffersVertexArray),
        this._engine.dispose()
    }
    ,
    e._createNativeDataStream = function() {
        return new NativeDataStream
    }
    ,
    e.prototype._queueNewFrame = function(i, o) {
        return o.requestAnimationFrame && o !== window ? o.requestAnimationFrame(i) : this._engine.requestAnimationFrame(i),
        0
    }
    ,
    e.prototype._bindUnboundFramebuffer = function(i) {
        this._currentFramebuffer !== i && (this._currentFramebuffer && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),
        this._commandBufferEncoder.finishEncodingCommand()),
        i && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.finishEncodingCommand()),
        this._currentFramebuffer = i)
    }
    ,
    e.prototype.getHostDocument = function() {
        return null
    }
    ,
    e.prototype.clear = function(i, o, s, c) {
        if (c === void 0 && (c = !1),
        this.useReverseDepthBuffer)
            throw new Error("reverse depth buffer is not currently implemented");
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o && i ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(i ? i.r : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(i ? i.g : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(i ? i.b : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(i ? i.a : 1),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(s ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(1),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(c ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(0),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.createIndexBuffer = function(i, o) {
        var s = this._normalizeIndexData(i)
          , c = new NativeDataBuffer;
        return c.references = 1,
        c.is32Bits = s.BYTES_PER_ELEMENT === 4,
        s.byteLength && (c.nativeIndexBuffer = this._engine.createIndexBuffer(s.buffer, s.byteOffset, s.byteLength, c.is32Bits, o != null ? o : !1)),
        c
    }
    ,
    e.prototype.createVertexBuffer = function(i, o) {
        var s = ArrayBuffer.isView(i) ? i : new Float32Array(i)
          , c = new NativeDataBuffer;
        return c.references = 1,
        s.byteLength && (c.nativeVertexBuffer = this._engine.createVertexBuffer(s.buffer, s.byteOffset, s.byteLength, o != null ? o : !1)),
        c
    }
    ,
    e.prototype._recordVertexArrayObject = function(i, o, s, c) {
        s && this._engine.recordIndexBuffer(i, s.nativeIndexBuffer);
        for (var d = c.getAttributesNames(), _ = 0; _ < d.length; _++) {
            var b = c.getAttributeLocation(_);
            if (b >= 0) {
                var k = d[_]
                  , j = o[k];
                if (j) {
                    var $ = j.getBuffer();
                    $ && this._engine.recordVertexBuffer(i, $.nativeVertexBuffer, b, j.byteOffset, j.byteStride, j.getSize(), this._getNativeAttribType(j.type), j.normalized)
                }
            }
        }
    }
    ,
    e.prototype.bindBuffers = function(i, o, s) {
        this._boundBuffersVertexArray && this._deleteVertexArray(this._boundBuffersVertexArray),
        this._boundBuffersVertexArray = this._engine.createVertexArray(),
        this._recordVertexArrayObject(this._boundBuffersVertexArray, i, o, s),
        this.bindVertexArrayObject(this._boundBuffersVertexArray)
    }
    ,
    e.prototype.recordVertexArrayObject = function(i, o, s) {
        var c = this._engine.createVertexArray();
        return this._recordVertexArrayObject(c, i, o, s),
        c
    }
    ,
    e.prototype._deleteVertexArray = function(i) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.bindVertexArrayObject = function(i) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.releaseVertexArrayObject = function(i) {
        this._deleteVertexArray(i)
    }
    ,
    e.prototype.getAttributes = function(i, o) {
        var s = i;
        return this._engine.getAttributes(s.nativeProgram, o)
    }
    ,
    e.prototype.drawElementsType = function(i, o, s, c) {
        this._drawCalls.addCount(1, !1),
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(i),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(s),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.drawArraysType = function(i, o, s, c) {
        this._drawCalls.addCount(1, !1),
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(i),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(s),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.createPipelineContext = function() {
        return new NativePipelineContext(this)
    }
    ,
    e.prototype.createMaterialContext = function() {}
    ,
    e.prototype.createDrawContext = function() {}
    ,
    e.prototype._preparePipelineContext = function(i, o, s, c, d, _, b, k, j) {
        var $ = i;
        c ? $.nativeProgram = this.createRawShaderProgram(i, o, s, void 0, j) : $.nativeProgram = this.createShaderProgram(i, o, s, k, void 0, j)
    }
    ,
    e.prototype._isRenderingStateCompiled = function(i) {
        return !0
    }
    ,
    e.prototype._executeWhenRenderingStateIsCompiled = function(i, o) {
        o()
    }
    ,
    e.prototype.createRawShaderProgram = function(i, o, s, c, d) {
        throw new Error("Not Supported")
    }
    ,
    e.prototype.createShaderProgram = function(i, o, s, c, d, _) {
        this.onBeforeShaderCompilationObservable.notifyObservers(this);
        var b = new ShaderCodeInliner(o);
        b.processCode(),
        o = b.code;
        var k = new ShaderCodeInliner(s);
        k.processCode(),
        s = k.code,
        o = ThinEngine._ConcatenateShader(o, c),
        s = ThinEngine._ConcatenateShader(s, c);
        var j = this._engine.createProgram(o, s);
        return this.onAfterShaderCompilationObservable.notifyObservers(this),
        j
    }
    ,
    e.prototype.inlineShaderCode = function(i) {
        var o = new ShaderCodeInliner(i);
        return o.debug = !1,
        o.processCode(),
        o.code
    }
    ,
    e.prototype._setProgram = function(i) {
        this._currentProgram !== i && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.finishEncodingCommand(),
        this._currentProgram = i)
    }
    ,
    e.prototype._deletePipelineContext = function(i) {
        var o = i;
        o && o.nativeProgram && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(o.nativeProgram),
        this._commandBufferEncoder.finishEncodingCommand())
    }
    ,
    e.prototype.getUniforms = function(i, o) {
        var s = i;
        return this._engine.getUniforms(s.nativeProgram, o)
    }
    ,
    e.prototype.bindUniformBlock = function(i, o, s) {
        throw new Error("Not Implemented")
    }
    ,
    e.prototype.bindSamplers = function(i) {
        var o = i.getPipelineContext();
        this._setProgram(o.nativeProgram);
        for (var s = i.getSamplers(), c = 0; c < s.length; c++) {
            var d = i.getUniform(s[c]);
            d && (this._boundUniforms[c] = d)
        }
        this._currentEffect = null
    }
    ,
    e.prototype.setMatrix = function(i, o) {
        if (!!i) {
            var s = o.toArray();
            this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX),
            this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
            this._commandBufferEncoder.encodeCommandArgAsFloat32s(s),
            this._commandBufferEncoder.finishEncodingCommand()
        }
    }
    ,
    e.prototype.getRenderWidth = function(i) {
        return i === void 0 && (i = !1),
        !i && this._currentRenderTarget ? this._currentRenderTarget.width : this._engine.getRenderWidth()
    }
    ,
    e.prototype.getRenderHeight = function(i) {
        return i === void 0 && (i = !1),
        !i && this._currentRenderTarget ? this._currentRenderTarget.height : this._engine.getRenderHeight()
    }
    ,
    e.prototype.setViewport = function(i, o, s) {
        this._cachedViewport = i,
        this._engine.setViewPort(i.x, i.y, i.width, i.height)
    }
    ,
    e.prototype.setState = function(i, o, s, c, d, _, b) {
        var k, j;
        o === void 0 && (o = 0),
        c === void 0 && (c = !1),
        b === void 0 && (b = 0),
        this._zOffset = o,
        this._zOffsetUnits = b,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(i ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(o),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(b),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(!((j = (k = this.cullBackFaces) !== null && k !== void 0 ? k : d) !== null && j !== void 0) || j ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(c ? 1 : 0),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.getInputElementClientRect = function() {
        var i = {
            bottom: this.getRenderHeight(),
            height: this.getRenderHeight(),
            left: 0,
            right: this.getRenderWidth(),
            top: 0,
            width: this.getRenderWidth(),
            x: 0,
            y: 0,
            toJSON: function() {}
        };
        return i
    }
    ,
    e.prototype.setZOffset = function(i) {
        i !== this._zOffset && (this._zOffset = i,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -i : i),
        this._commandBufferEncoder.finishEncodingCommand())
    }
    ,
    e.prototype.getZOffset = function() {
        return this._zOffset
    }
    ,
    e.prototype.setZOffsetUnits = function(i) {
        i !== this._zOffsetUnits && (this._zOffsetUnits = i,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -i : i),
        this._commandBufferEncoder.finishEncodingCommand())
    }
    ,
    e.prototype.getZOffsetUnits = function() {
        return this._zOffsetUnits
    }
    ,
    e.prototype.setDepthBuffer = function(i) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(i ? 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(i) {
        var o = 0;
        switch (i) {
        case 512:
            o = _native.Engine.DEPTH_TEST_NEVER;
            break;
        case 519:
            o = _native.Engine.DEPTH_TEST_ALWAYS;
            break;
        case 516:
            o = _native.Engine.DEPTH_TEST_GREATER;
            break;
        case 518:
            o = _native.Engine.DEPTH_TEST_GEQUAL;
            break;
        case 517:
            o = _native.Engine.DEPTH_TEST_NOTEQUAL;
            break;
        case 514:
            o = _native.Engine.DEPTH_TEST_EQUAL;
            break;
        case 513:
            o = _native.Engine.DEPTH_TEST_LESS;
            break;
        case 515:
            o = _native.Engine.DEPTH_TEST_LEQUAL;
            break
        }
        this._currentDepthTest = o,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.setDepthWrite = function(i) {
        this._depthWrite = i,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(i)),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.setColorWrite = function(i) {
        this._colorWrite = i,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(i)),
        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(i, o, s, c, d, _) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(i),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(s),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(c),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(d),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(_),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.setStencilBuffer = function(i) {
        this._stencilTest = i,
        i ? 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(i) {
        this._stencilOpStencilDepthPass = i,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilMask = function(i) {
        this._stencilMask = i,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilFunction = function(i) {
        this._stencilFunc = i,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilFunctionReference = function(i) {
        this._stencilFuncRef = i,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilFunctionMask = function(i) {
        this._stencilFuncMask = i
    }
    ,
    e.prototype.setStencilOperationFail = function(i) {
        this._stencilOpStencilFail = i,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilOperationDepthFail = function(i) {
        this._stencilOpDepthFail = i,
        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(i, o, s, c) {
        throw new Error("Setting alpha blend constant color not yet implemented.")
    }
    ,
    e.prototype.setAlphaMode = function(i, o) {
        o === void 0 && (o = !1),
        this._alphaMode !== i && (i = this._getNativeAlphaMode(i),
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(i),
        this._commandBufferEncoder.finishEncodingCommand(),
        o || this.setDepthWrite(i === 0),
        this._alphaMode = i)
    }
    ,
    e.prototype.getAlphaMode = function() {
        return this._alphaMode
    }
    ,
    e.prototype.setInt = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsInt32(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setIntArray = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsInt32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setIntArray2 = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsInt32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setIntArray3 = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsInt32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setIntArray4 = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsInt32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloatArray = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloatArray2 = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloatArray3 = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloatArray4 = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setArray = function(i, o) {
        return i ? this.setFloatArray(i, new Float32Array(o)) : !1
    }
    ,
    e.prototype.setArray2 = function(i, o) {
        return i ? (this.setFloatArray2(i, new Float32Array(o)),
        !0) : !1
    }
    ,
    e.prototype.setArray3 = function(i, o) {
        return i ? (this.setFloatArray3(i, new Float32Array(o)),
        !0) : !1
    }
    ,
    e.prototype.setArray4 = function(i, o) {
        return i ? (this.setFloatArray4(i, new Float32Array(o)),
        !0) : !1
    }
    ,
    e.prototype.setMatrices = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setMatrix3x3 = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setMatrix2x2 = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloat = function(i, o) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloat2 = function(i, o, s) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(o),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(s),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloat3 = function(i, o, s, c) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(o),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(s),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(c),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloat4 = function(i, o, s, c, d) {
        return i ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(o),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(s),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(c),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(d),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setColor3 = function(i, o) {
        return i ? (this.setFloat3(i, o.r, o.g, o.b),
        !0) : !1
    }
    ,
    e.prototype.setColor4 = function(i, o, s) {
        return i ? (this.setFloat4(i, o.r, o.g, o.b, s),
        !0) : !1
    }
    ,
    e.prototype.wipeCaches = function(i) {
        this.preventCacheWipeBetweenFrames || (this.resetTextureCache(),
        this._currentEffect = null,
        i && (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(i) {
        i && this._engine.deleteTexture(i)
    }
    ,
    e.prototype.updateDynamicTexture = function(i, o, s, c, d) {
        if (!!i && !!i._hardwareTexture) {
            var _ = o.getCanvasTexture()
              , b = i._hardwareTexture.underlyingResource;
            this._engine.copyTexture(b, _),
            i.isReady = !0
        }
    }
    ,
    e.prototype.createDynamicTexture = function(i, o, s, c) {
        return i = Math.max(i, 1),
        o = Math.max(o, 1),
        this.createRawTexture(new Uint8Array(i * o * 4), i, o, 5, !1, !1, c)
    }
    ,
    e.prototype.createVideoElement = function(i) {
        return this._camera ? this._camera.createVideo(i) : null
    }
    ,
    e.prototype.updateVideoTexture = function(i, o, s) {
        if (i && i._hardwareTexture && this._camera) {
            var c = i._hardwareTexture.underlyingResource;
            this._camera.updateVideoTexture(c, o, s)
        }
    }
    ,
    e.prototype.createRawTexture = function(i, o, s, c, d, _, b, k, j) {
        k === void 0 && (k = null),
        j === void 0 && (j = 0);
        var $ = new InternalTexture(this,InternalTextureSource.Raw);
        if ($.format = c,
        $.generateMipMaps = d,
        $.samplingMode = b,
        $.invertY = _,
        $.baseWidth = o,
        $.baseHeight = s,
        $.width = $.baseWidth,
        $.height = $.baseHeight,
        $._compression = k,
        $.type = j,
        this.updateRawTexture($, i, c, _, k, j),
        $._hardwareTexture) {
            var _e = $._hardwareTexture.underlyingResource
              , et = this._getNativeSamplingMode(b);
            this._setTextureSampling(_e, et)
        }
        return this._internalTexturesCache.push($),
        $
    }
    ,
    e.prototype.updateRawTexture = function(i, o, s, c, d, _) {
        if (_ === void 0 && (_ = 0),
        !!i) {
            if (o && i._hardwareTexture) {
                var b = i._hardwareTexture.underlyingResource;
                this._engine.loadRawTexture(b, o, i.width, i.height, this._getNativeTextureFormat(s, _), i.generateMipMaps, i.invertY)
            }
            i.isReady = !0
        }
    }
    ,
    e.prototype.createTexture = function(i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it) {
        var nt = this;
        d === void 0 && (d = 3),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null),
        k === void 0 && (k = null),
        j === void 0 && (j = null),
        $ === void 0 && ($ = null),
        _e === void 0 && (_e = null),
        it === void 0 && (it = !1),
        i = i || "";
        var ot = i.substr(0, 5) === "data:"
          , at = ot && i.indexOf(";base64,") !== -1
          , st = j || new InternalTexture(this,InternalTextureSource.Url)
          , ut = i;
        this._transformTextureUrl && !at && !j && !k && (i = this._transformTextureUrl(i));
        for (var ct = i.lastIndexOf("."), lt = _e || (ct > -1 ? i.substring(ct).toLowerCase() : ""), ft = null, ht = 0, pt = Engine._TextureLoaders; ht < pt.length; ht++) {
            var dt = pt[ht];
            if (dt.canLoad(lt)) {
                ft = dt;
                break
            }
        }
        c && c._addPendingData(st),
        st.url = i,
        st.generateMipMaps = !o,
        st.samplingMode = d,
        st.invertY = s,
        st._useSRGBBuffer = this._getUseSRGBBuffer(it, o),
        this.doNotHandleContextLost || (st._buffer = k);
        var _t = null;
        _ && !j && (_t = st.onLoadedObservable.add(_)),
        j || this._internalTexturesCache.push(st);
        var mt = function(yt, Et) {
            c && c._removePendingData(st),
            i === ut ? (_t && st.onLoadedObservable.remove(_t),
            EngineStore.UseFallbackTexture && nt.createTexture(EngineStore.FallbackTexture, o, st.invertY, c, d, null, b, k, st),
            b && b((yt || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), Et)) : (Logger$2.Warn("Failed to load " + i + ", falling back to " + ut),
            nt.createTexture(ut, o, st.invertY, c, d, _, b, k, st, $, _e, et, tt))
        };
        if (ft)
            throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
        var vt = function(yt) {
            if (!st._hardwareTexture) {
                c && c._removePendingData(st);
                return
            }
            var Et = st._hardwareTexture.underlyingResource;
            nt._engine.loadTexture(Et, yt, !o, s, it, function() {
                st.baseWidth = nt._engine.getTextureWidth(Et),
                st.baseHeight = nt._engine.getTextureHeight(Et),
                st.width = st.baseWidth,
                st.height = st.baseHeight,
                st.isReady = !0;
                var At = nt._getNativeSamplingMode(d);
                nt._setTextureSampling(Et, At),
                c && c._removePendingData(st),
                st.onLoadedObservable.notifyObservers(st),
                st.onLoadedObservable.clear()
            }, function() {
                throw new Error("Could not load a native texture.")
            })
        };
        if (ot && k)
            if (k instanceof ArrayBuffer)
                vt(new Uint8Array(k));
            else if (ArrayBuffer.isView(k))
                vt(k);
            else if (typeof k == "string")
                vt(new Uint8Array(Tools.DecodeBase64(k)));
            else
                throw new Error("Unsupported buffer type");
        else
            at ? vt(new Uint8Array(Tools.DecodeBase64(i))) : this._loadFile(i, function(yt) {
                return vt(new Uint8Array(yt))
            }, void 0, void 0, !0, function(yt, Et) {
                mt("Unable to load " + (yt && yt.responseURL,
                Et))
            });
        return st
    }
    ,
    e.prototype._createDepthStencilTexture = function(i, o, s) {
        var c = s
          , d = new InternalTexture(this,InternalTextureSource.DepthStencil)
          , _ = i.width || i
          , b = i.height || i
          , k = this._engine.createFrameBuffer(d._hardwareTexture.underlyingResource, _, b, _native.Engine.TEXTURE_FORMAT_RGBA8, !1, !0, !1);
        return c._framebufferDepthStencil = k,
        d
    }
    ,
    e.prototype._releaseFramebufferObjects = function(i) {
        i && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.finishEncodingCommand())
    }
    ,
    e.prototype.createImageBitmap = function(i, o) {
        var s = this;
        return new Promise(function(c, d) {
            if (Array.isArray(i)) {
                var _ = i;
                if (_.length) {
                    var b = s._engine.createImageBitmap(_[0]);
                    if (b) {
                        c(b);
                        return
                    }
                }
            }
            d("Unsupported data for createImageBitmap.")
        }
        )
    }
    ,
    e.prototype.resizeImageBitmap = function(i, o, s) {
        return this._engine.resizeImageBitmap(i, o, s)
    }
    ,
    e.prototype.createCubeTexture = function(i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt) {
        var it = this;
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        k === void 0 && (k = null),
        $ === void 0 && ($ = 0),
        _e === void 0 && (_e = 0),
        et === void 0 && (et = null),
        rt === void 0 && (rt = !1);
        var nt = et || new InternalTexture(this,InternalTextureSource.Cube);
        nt.isCube = !0,
        nt.url = i,
        nt.generateMipMaps = !c,
        nt._lodGenerationScale = $,
        nt._lodGenerationOffset = _e,
        this._doNotHandleContextLost || (nt._extension = k,
        nt._files = s);
        var ot = i.lastIndexOf(".")
          , at = k || (ot > -1 ? i.substring(ot).toLowerCase() : "");
        if (at === ".env") {
            var st = function(lt) {
                var ft = GetEnvInfo(lt);
                nt.width = ft.width,
                nt.height = ft.width,
                UploadEnvSpherical(nt, ft);
                var ht = ft.specular;
                if (!ht)
                    throw new Error("Nothing else parsed so far");
                nt._lodGenerationScale = ht.lodGenerationScale;
                var pt = CreateImageDataArrayBufferViews(lt, ft);
                nt.format = 5,
                nt.type = 0,
                nt.generateMipMaps = !0,
                nt.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, nt),
                nt._isRGBD = !0,
                nt.invertY = !0,
                it._engine.loadCubeTextureWithMips(nt._hardwareTexture.underlyingResource, pt, !1, rt, function() {
                    nt.isReady = !0,
                    d && d()
                }, function() {
                    throw new Error("Could not load a native cube texture.")
                })
            };
            if (s && s.length === 6)
                throw new Error("Multi-file loading not allowed on env files.");
            var ut = function(lt, ft) {
                _ && lt && _(lt.status + " " + lt.statusText, ft)
            };
            this._loadFile(i, function(lt) {
                return st(new Uint8Array(lt))
            }, void 0, void 0, !0, ut)
        } else {
            if (!s || s.length !== 6)
                throw new Error("Cannot load cubemap because 6 files were not defined");
            var ct = [s[0], s[3], s[1], s[4], s[2], s[5]];
            Promise.all(ct.map(function(lt) {
                return Tools.LoadFileAsync(lt).then(function(ft) {
                    return new Uint8Array(ft)
                })
            })).then(function(lt) {
                return new Promise(function(ft, ht) {
                    it._engine.loadCubeTexture(nt._hardwareTexture.underlyingResource, lt, !c, !0, rt, ft, ht)
                }
                )
            }).then(function() {
                nt.isReady = !0,
                d && d()
            }, function(lt) {
                _ && _("Failed to load cubemap: " + lt.message, lt)
            })
        }
        return this._internalTexturesCache.push(nt),
        nt
    }
    ,
    e.prototype._createHardwareRenderTargetWrapper = function(i, o, s) {
        var c = new NativeRenderTargetWrapper(i,o,s,this);
        return this._renderTargetWrapperCache.push(c),
        c
    }
    ,
    e.prototype.createRenderTargetTexture = function(i, o) {
        var s = this._createHardwareRenderTargetWrapper(!1, !1, i)
          , c = {};
        o !== void 0 && typeof o == "object" ? (c.generateMipMaps = o.generateMipMaps,
        c.generateDepthBuffer = o.generateDepthBuffer === void 0 ? !0 : o.generateDepthBuffer,
        c.generateStencilBuffer = c.generateDepthBuffer && o.generateStencilBuffer,
        c.type = o.type === void 0 ? 0 : o.type,
        c.samplingMode = o.samplingMode === void 0 ? 3 : o.samplingMode,
        c.format = o.format === void 0 ? 5 : o.format) : (c.generateMipMaps = o,
        c.generateDepthBuffer = !0,
        c.generateStencilBuffer = !1,
        c.type = 0,
        c.samplingMode = 3,
        c.format = 5),
        (c.type === 1 && !this._caps.textureFloatLinearFiltering || c.type === 2 && !this._caps.textureHalfFloatLinearFiltering) && (c.samplingMode = 1);
        var d = new InternalTexture(this,InternalTextureSource.RenderTarget)
          , _ = i.width || i
          , b = i.height || i;
        c.type === 1 && !this._caps.textureFloat && (c.type = 0,
        Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));
        var k = this._engine.createFrameBuffer(d._hardwareTexture.underlyingResource, _, b, this._getNativeTextureFormat(c.format, c.type), !!c.generateStencilBuffer, c.generateDepthBuffer, !!c.generateMipMaps);
        return s._framebuffer = k,
        s._generateDepthBuffer = c.generateDepthBuffer,
        s._generateStencilBuffer = !!c.generateStencilBuffer,
        d.baseWidth = _,
        d.baseHeight = b,
        d.width = _,
        d.height = b,
        d.isReady = !0,
        d.samples = 1,
        d.generateMipMaps = !!c.generateMipMaps,
        d.samplingMode = c.samplingMode,
        d.type = c.type,
        d.format = c.format,
        this._internalTexturesCache.push(d),
        s.setTextures(d),
        s
    }
    ,
    e.prototype.updateTextureSamplingMode = function(i, o) {
        if (o._hardwareTexture) {
            var s = this._getNativeSamplingMode(i);
            this._setTextureSampling(o._hardwareTexture.underlyingResource, s)
        }
        o.samplingMode = i
    }
    ,
    e.prototype.bindFramebuffer = function(i, o, s, c, d) {
        var _ = i;
        if (o)
            throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
        if (s || c)
            throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
        _._framebufferDepthStencil ? this._bindUnboundFramebuffer(_._framebufferDepthStencil) : this._bindUnboundFramebuffer(_._framebuffer)
    }
    ,
    e.prototype.unBindFramebuffer = function(i, o, s) {
        s && s(),
        this._bindUnboundFramebuffer(null)
    }
    ,
    e.prototype.createDynamicVertexBuffer = function(i) {
        return this.createVertexBuffer(i, !0)
    }
    ,
    e.prototype.updateDynamicIndexBuffer = function(i, o, s) {
        s === void 0 && (s = 0);
        var c = i
          , d = this._normalizeIndexData(o);
        c.is32Bits = d.BYTES_PER_ELEMENT === 4,
        this._engine.updateDynamicIndexBuffer(c.nativeIndexBuffer, d.buffer, d.byteOffset, d.byteLength, s)
    }
    ,
    e.prototype.updateDynamicVertexBuffer = function(i, o, s, c) {
        var d = i
          , _ = ArrayBuffer.isView(o) ? o : new Float32Array(o);
        this._engine.updateDynamicVertexBuffer(d.nativeVertexBuffer, _.buffer, _.byteOffset + (s != null ? s : 0), c != null ? c : _.byteLength)
    }
    ,
    e.prototype._setTexture = function(i, o, s, c) {
        c === void 0 && (c = !1);
        var d = this._boundUniforms[i];
        if (!d)
            return !1;
        if (!o)
            return this._boundTexturesCache[i] != null && (this._activeChannel = i,
            this._setTextureCore(d, null)),
            !1;
        if (o.video)
            this._activeChannel = i,
            o.update();
        else if (o.delayLoadState === 4)
            return o.delayLoad(),
            !1;
        var _;
        return c ? _ = o.depthStencilTexture : o.isReady() ? _ = o.getInternalTexture() : o.isCube ? _ = this.emptyCubeTexture : o.is3D ? _ = this.emptyTexture3D : o.is2DArray ? _ = this.emptyTexture2DArray : _ = this.emptyTexture,
        this._activeChannel = i,
        !_ || !_._hardwareTexture ? !1 : (this._setTextureWrapMode(_._hardwareTexture.underlyingResource, this._getAddressMode(o.wrapU), this._getAddressMode(o.wrapV), this._getAddressMode(o.wrapR)),
        this._updateAnisotropicLevel(o),
        this._setTextureCore(d, _._hardwareTexture.underlyingResource),
        !0)
    }
    ,
    e.prototype._setTextureSampling = function(i, o) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype._setTextureWrapMode = function(i, o, s, c) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(s),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(c),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype._setTextureCore = function(i, o) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(o),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype._updateAnisotropicLevel = function(i) {
        var o = i.getInternalTexture()
          , s = i.anisotropicFilteringLevel;
        !o || !o._hardwareTexture || o._cachedAnisotropicFilteringLevel !== s && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(o._hardwareTexture.underlyingResource),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(s),
        this._commandBufferEncoder.finishEncodingCommand(),
        o._cachedAnisotropicFilteringLevel = s)
    }
    ,
    e.prototype._getAddressMode = function(i) {
        switch (i) {
        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: " + i + ".")
        }
    }
    ,
    e.prototype._bindTexture = function(i, o) {
        var s = this._boundUniforms[i];
        if (!!s && o && o._hardwareTexture) {
            var c = o._hardwareTexture.underlyingResource;
            this._setTextureCore(s, c)
        }
    }
    ,
    e.prototype._deleteBuffer = function(i) {
        i.nativeIndexBuffer && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i.nativeIndexBuffer),
        this._commandBufferEncoder.finishEncodingCommand(),
        delete i.nativeIndexBuffer),
        i.nativeVertexBuffer && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(i.nativeVertexBuffer),
        this._commandBufferEncoder.finishEncodingCommand(),
        delete i.nativeVertexBuffer)
    }
    ,
    e.prototype.createCanvas = function(i, o) {
        if (!_native.Canvas)
            throw new Error("Native Canvas plugin not available.");
        var s = new _native.Canvas;
        return s.width = i,
        s.height = o,
        s
    }
    ,
    e.prototype.createCanvasImage = function() {
        if (!_native.Canvas)
            throw new Error("Native Canvas plugin not available.");
        var i = new _native.Image;
        return i
    }
    ,
    e.prototype._uploadCompressedDataToTextureDirectly = function(i, o, s, c, d, _, b) {
        throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")
    }
    ,
    e.prototype._uploadDataToTextureDirectly = function(i, o, s, c) {
        throw new Error("_uploadDataToTextureDirectly not implemented.")
    }
    ,
    e.prototype._uploadArrayBufferViewToTexture = function(i, o, s, c) {
        throw new Error("_uploadArrayBufferViewToTexture not implemented.")
    }
    ,
    e.prototype._uploadImageToTexture = function(i, o, s, c) {
        throw new Error("_uploadArrayBufferViewToTexture not implemented.")
    }
    ,
    e.prototype._getNativeSamplingMode = function(i) {
        switch (i) {
        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: " + i + ".")
        }
    }
    ,
    e.prototype._getStencilFunc = function(i) {
        switch (i) {
        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: " + i + ".")
        }
    }
    ,
    e.prototype._getStencilOpFail = function(i) {
        switch (i) {
        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: " + i + ".")
        }
    }
    ,
    e.prototype._getStencilDepthFail = function(i) {
        switch (i) {
        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: " + i + ".")
        }
    }
    ,
    e.prototype._getStencilDepthPass = function(i) {
        switch (i) {
        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: " + i + ".")
        }
    }
    ,
    e.prototype._getNativeTextureFormat = function(i, o) {
        if (i == 4 && o == 0)
            return _native.Engine.TEXTURE_FORMAT_RGB8;
        if (i == 5 && o == 0)
            return _native.Engine.TEXTURE_FORMAT_RGBA8;
        if (i == 5 && o == 1)
            return _native.Engine.TEXTURE_FORMAT_RGBA32F;
        throw new Error("Unsupported texture format or type: format " + i + ", type " + o + ".")
    }
    ,
    e.prototype._getNativeAlphaMode = function(i) {
        switch (i) {
        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: " + i + ".")
        }
    }
    ,
    e.prototype._getNativeAttribType = function(i) {
        switch (i) {
        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: " + i + ".")
        }
    }
    ,
    e.prototype.getFontOffset = function(i) {
        var o = {
            ascent: 0,
            height: 0,
            descent: 0
        };
        return o
    }
    ,
    e.PROTOCOL_VERSION = 2,
    e
}(Engine);
NativeEngine._createNativeDataStream = function() {
    return _native.NativeDataStream.VALIDATION_ENABLED ? new ValidatedNativeDataStream : new NativeDataStream
}
;
var ValidatedNativeDataStream = function(a) {
    __extends(e, a);
    function e() {
        return a.call(this) || this
    }
    return e.prototype.writeUint32 = function(i) {
        a.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_UINT_32),
        a.prototype.writeUint32.call(this, i)
    }
    ,
    e.prototype.writeInt32 = function(i) {
        a.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_INT_32),
        a.prototype.writeInt32.call(this, i)
    }
    ,
    e.prototype.writeFloat32 = function(i) {
        a.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_FLOAT_32),
        a.prototype.writeFloat32.call(this, i)
    }
    ,
    e.prototype.writeUint32Array = function(i) {
        a.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_UINT_32_ARRAY),
        a.prototype.writeUint32Array.call(this, i)
    }
    ,
    e.prototype.writeInt32Array = function(i) {
        a.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_INT_32_ARRAY),
        a.prototype.writeInt32Array.call(this, i)
    }
    ,
    e.prototype.writeFloat32Array = function(i) {
        a.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),
        a.prototype.writeFloat32Array.call(this, i)
    }
    ,
    e.prototype.writeNativeData = function(i) {
        a.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_NATIVE_DATA),
        a.prototype.writeNativeData.call(this, i)
    }
    ,
    e.prototype.writeBoolean = function(i) {
        a.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_BOOLEAN),
        a.prototype.writeBoolean.call(this, i)
    }
    ,
    e
}(NativeDataStream), PowerPreference;
(function(a) {
    a.SRGB = "srgb"
}
)(PowerPreference || (PowerPreference = {}));
(function(a) {
    a.LowPower = "low-power",
    a.HighPerformance = "high-performance"
}
)(PowerPreference || (PowerPreference = {}));
var FeatureName;
(function(a) {
    a.DepthClipControl = "depth-clip-control",
    a.Depth24UnormStencil8 = "depth24unorm-stencil8",
    a.Depth32FloatStencil8 = "depth32float-stencil8",
    a.TextureCompressionBC = "texture-compression-bc",
    a.TextureCompressionETC2 = "texture-compression-etc2",
    a.TextureCompressionASTC = "texture-compression-astc",
    a.TimestampQuery = "timestamp-query",
    a.IndirectFirstInstance = "indirect-first-instance"
}
)(FeatureName || (FeatureName = {}));
var BufferUsage;
(function(a) {
    a[a.MapRead = 1] = "MapRead",
    a[a.MapWrite = 2] = "MapWrite",
    a[a.CopySrc = 4] = "CopySrc",
    a[a.CopyDst = 8] = "CopyDst",
    a[a.Index = 16] = "Index",
    a[a.Vertex = 32] = "Vertex",
    a[a.Uniform = 64] = "Uniform",
    a[a.Storage = 128] = "Storage",
    a[a.Indirect = 256] = "Indirect",
    a[a.QueryResolve = 512] = "QueryResolve"
}
)(BufferUsage || (BufferUsage = {}));
var MapMode;
(function(a) {
    a[a.Read = 1] = "Read",
    a[a.Write = 2] = "Write"
}
)(MapMode || (MapMode = {}));
var TextureDimension;
(function(a) {
    a.E1d = "1d",
    a.E2d = "2d",
    a.E3d = "3d"
}
)(TextureDimension || (TextureDimension = {}));
var TextureUsage;
(function(a) {
    a[a.CopySrc = 1] = "CopySrc",
    a[a.CopyDst = 2] = "CopyDst",
    a[a.TextureBinding = 4] = "TextureBinding",
    a[a.StorageBinding = 8] = "StorageBinding",
    a[a.RenderAttachment = 16] = "RenderAttachment"
}
)(TextureUsage || (TextureUsage = {}));
var TextureViewDimension;
(function(a) {
    a.E1d = "1d",
    a.E2d = "2d",
    a.E2dArray = "2d-array",
    a.Cube = "cube",
    a.CubeArray = "cube-array",
    a.E3d = "3d"
}
)(TextureViewDimension || (TextureViewDimension = {}));
var TextureAspect;
(function(a) {
    a.All = "all",
    a.StencilOnly = "stencil-only",
    a.DepthOnly = "depth-only"
}
)(TextureAspect || (TextureAspect = {}));
var TextureFormat;
(function(a) {
    a.R8Unorm = "r8unorm",
    a.R8Snorm = "r8snorm",
    a.R8Uint = "r8uint",
    a.R8Sint = "r8sint",
    a.R16Uint = "r16uint",
    a.R16Sint = "r16sint",
    a.R16Float = "r16float",
    a.RG8Unorm = "rg8unorm",
    a.RG8Snorm = "rg8snorm",
    a.RG8Uint = "rg8uint",
    a.RG8Sint = "rg8sint",
    a.R32Uint = "r32uint",
    a.R32Sint = "r32sint",
    a.R32Float = "r32float",
    a.RG16Uint = "rg16uint",
    a.RG16Sint = "rg16sint",
    a.RG16Float = "rg16float",
    a.RGBA8Unorm = "rgba8unorm",
    a.RGBA8UnormSRGB = "rgba8unorm-srgb",
    a.RGBA8Snorm = "rgba8snorm",
    a.RGBA8Uint = "rgba8uint",
    a.RGBA8Sint = "rgba8sint",
    a.BGRA8Unorm = "bgra8unorm",
    a.BGRA8UnormSRGB = "bgra8unorm-srgb",
    a.RGB9E5UFloat = "rgb9e5ufloat",
    a.RGB10A2Unorm = "rgb10a2unorm",
    a.RG11B10UFloat = "rg11b10ufloat",
    a.RG32Uint = "rg32uint",
    a.RG32Sint = "rg32sint",
    a.RG32Float = "rg32float",
    a.RGBA16Uint = "rgba16uint",
    a.RGBA16Sint = "rgba16sint",
    a.RGBA16Float = "rgba16float",
    a.RGBA32Uint = "rgba32uint",
    a.RGBA32Sint = "rgba32sint",
    a.RGBA32Float = "rgba32float",
    a.Stencil8 = "stencil8",
    a.Depth16Unorm = "depth16unorm",
    a.Depth24Plus = "depth24plus",
    a.Depth24PlusStencil8 = "depth24plus-stencil8",
    a.Depth32Float = "depth32float",
    a.BC1RGBAUnorm = "bc1-rgba-unorm",
    a.BC1RGBAUnormSRGB = "bc1-rgba-unorm-srgb",
    a.BC2RGBAUnorm = "bc2-rgba-unorm",
    a.BC2RGBAUnormSRGB = "bc2-rgba-unorm-srgb",
    a.BC3RGBAUnorm = "bc3-rgba-unorm",
    a.BC3RGBAUnormSRGB = "bc3-rgba-unorm-srgb",
    a.BC4RUnorm = "bc4-r-unorm",
    a.BC4RSnorm = "bc4-r-snorm",
    a.BC5RGUnorm = "bc5-rg-unorm",
    a.BC5RGSnorm = "bc5-rg-snorm",
    a.BC6HRGBUFloat = "bc6h-rgb-ufloat",
    a.BC6HRGBFloat = "bc6h-rgb-float",
    a.BC7RGBAUnorm = "bc7-rgba-unorm",
    a.BC7RGBAUnormSRGB = "bc7-rgba-unorm-srgb",
    a.ETC2RGB8Unorm = "etc2-rgb8unorm",
    a.ETC2RGB8UnormSRGB = "etc2-rgb8unorm-srgb",
    a.ETC2RGB8A1Unorm = "etc2-rgb8a1unorm",
    a.ETC2RGB8A1UnormSRGB = "etc2-rgb8a1unorm-srgb",
    a.ETC2RGBA8Unorm = "etc2-rgba8unorm",
    a.ETC2RGBA8UnormSRGB = "etc2-rgba8unorm-srgb",
    a.EACR11Unorm = "eac-r11unorm",
    a.EACR11Snorm = "eac-r11snorm",
    a.EACRG11Unorm = "eac-rg11unorm",
    a.EACRG11Snorm = "eac-rg11snorm",
    a.ASTC4x4Unorm = "astc-4x4-unorm",
    a.ASTC4x4UnormSRGB = "astc-4x4-unorm-srgb",
    a.ASTC5x4Unorm = "astc-5x4-unorm",
    a.ASTC5x4UnormSRGB = "astc-5x4-unorm-srgb",
    a.ASTC5x5Unorm = "astc-5x5-unorm",
    a.ASTC5x5UnormSRGB = "astc-5x5-unorm-srgb",
    a.ASTC6x5Unorm = "astc-6x5-unorm",
    a.ASTC6x5UnormSRGB = "astc-6x5-unorm-srgb",
    a.ASTC6x6Unorm = "astc-6x6-unorm",
    a.ASTC6x6UnormSRGB = "astc-6x6-unorm-srgb",
    a.ASTC8x5Unorm = "astc-8x5-unorm",
    a.ASTC8x5UnormSRGB = "astc-8x5-unorm-srgb",
    a.ASTC8x6Unorm = "astc-8x6-unorm",
    a.ASTC8x6UnormSRGB = "astc-8x6-unorm-srgb",
    a.ASTC8x8Unorm = "astc-8x8-unorm",
    a.ASTC8x8UnormSRGB = "astc-8x8-unorm-srgb",
    a.ASTC10x5Unorm = "astc-10x5-unorm",
    a.ASTC10x5UnormSRGB = "astc-10x5-unorm-srgb",
    a.ASTC10x6Unorm = "astc-10x6-unorm",
    a.ASTC10x6UnormSRGB = "astc-10x6-unorm-srgb",
    a.ASTC10x8Unorm = "astc-10x8-unorm",
    a.ASTC10x8UnormSRGB = "astc-10x8-unorm-srgb",
    a.ASTC10x10Unorm = "astc-10x10-unorm",
    a.ASTC10x10UnormSRGB = "astc-10x10-unorm-srgb",
    a.ASTC12x10Unorm = "astc-12x10-unorm",
    a.ASTC12x10UnormSRGB = "astc-12x10-unorm-srgb",
    a.ASTC12x12Unorm = "astc-12x12-unorm",
    a.ASTC12x12UnormSRGB = "astc-12x12-unorm-srgb",
    a.Depth24UnormStencil8 = "depth24unorm-stencil8",
    a.Depth32FloatStencil8 = "depth32float-stencil8"
}
)(TextureFormat || (TextureFormat = {}));
var AddressMode;
(function(a) {
    a.ClampToEdge = "clamp-to-edge",
    a.Repeat = "repeat",
    a.MirrorRepeat = "mirror-repeat"
}
)(AddressMode || (AddressMode = {}));
var FilterMode;
(function(a) {
    a.Nearest = "nearest",
    a.Linear = "linear"
}
)(FilterMode || (FilterMode = {}));
var CompareFunction;
(function(a) {
    a.Never = "never",
    a.Less = "less",
    a.Equal = "equal",
    a.LessEqual = "less-equal",
    a.Greater = "greater",
    a.NotEqual = "not-equal",
    a.GreaterEqual = "greater-equal",
    a.Always = "always"
}
)(CompareFunction || (CompareFunction = {}));
var ShaderStage;
(function(a) {
    a[a.Vertex = 1] = "Vertex",
    a[a.Fragment = 2] = "Fragment",
    a[a.Compute = 4] = "Compute"
}
)(ShaderStage || (ShaderStage = {}));
var BufferBindingType;
(function(a) {
    a.Uniform = "uniform",
    a.Storage = "storage",
    a.ReadOnlyStorage = "read-only-storage"
}
)(BufferBindingType || (BufferBindingType = {}));
var SamplerBindingType;
(function(a) {
    a.Filtering = "filtering",
    a.NonFiltering = "non-filtering",
    a.Comparison = "comparison"
}
)(SamplerBindingType || (SamplerBindingType = {}));
var TextureSampleType;
(function(a) {
    a.Float = "float",
    a.UnfilterableFloat = "unfilterable-float",
    a.Depth = "depth",
    a.Sint = "sint",
    a.Uint = "uint"
}
)(TextureSampleType || (TextureSampleType = {}));
var StorageTextureAccess;
(function(a) {
    a.WriteOnly = "write-only"
}
)(StorageTextureAccess || (StorageTextureAccess = {}));
var CompilationMessageType;
(function(a) {
    a.Error = "error",
    a.Warning = "warning",
    a.Info = "info"
}
)(CompilationMessageType || (CompilationMessageType = {}));
var PrimitiveTopology;
(function(a) {
    a.PointList = "point-list",
    a.LineList = "line-list",
    a.LineStrip = "line-strip",
    a.TriangleList = "triangle-list",
    a.TriangleStrip = "triangle-strip"
}
)(PrimitiveTopology || (PrimitiveTopology = {}));
var FrontFace;
(function(a) {
    a.CCW = "ccw",
    a.CW = "cw"
}
)(FrontFace || (FrontFace = {}));
var CullMode;
(function(a) {
    a.None = "none",
    a.Front = "front",
    a.Back = "back"
}
)(CullMode || (CullMode = {}));
var ColorWrite;
(function(a) {
    a[a.Red = 1] = "Red",
    a[a.Green = 2] = "Green",
    a[a.Blue = 4] = "Blue",
    a[a.Alpha = 8] = "Alpha",
    a[a.All = 15] = "All"
}
)(ColorWrite || (ColorWrite = {}));
var BlendFactor;
(function(a) {
    a.Zero = "zero",
    a.One = "one",
    a.Src = "src",
    a.OneMinusSrc = "one-minus-src",
    a.SrcAlpha = "src-alpha",
    a.OneMinusSrcAlpha = "one-minus-src-alpha",
    a.Dst = "dst",
    a.OneMinusDst = "one-minus-dst",
    a.DstAlpha = "dst-alpha",
    a.OneMinusDstAlpha = "one-minus-dst-alpha",
    a.SrcAlphaSaturated = "src-alpha-saturated",
    a.Constant = "constant",
    a.OneMinusConstant = "one-minus-constant"
}
)(BlendFactor || (BlendFactor = {}));
var BlendOperation;
(function(a) {
    a.Add = "add",
    a.Subtract = "subtract",
    a.ReverseSubtract = "reverse-subtract",
    a.Min = "min",
    a.Max = "max"
}
)(BlendOperation || (BlendOperation = {}));
var StencilOperation;
(function(a) {
    a.Keep = "keep",
    a.Zero = "zero",
    a.Replace = "replace",
    a.Invert = "invert",
    a.IncrementClamp = "increment-clamp",
    a.DecrementClamp = "decrement-clamp",
    a.IncrementWrap = "increment-wrap",
    a.DecrementWrap = "decrement-wrap"
}
)(StencilOperation || (StencilOperation = {}));
var IndexFormat;
(function(a) {
    a.Uint16 = "uint16",
    a.Uint32 = "uint32"
}
)(IndexFormat || (IndexFormat = {}));
var VertexFormat;
(function(a) {
    a.Uint8x2 = "uint8x2",
    a.Uint8x4 = "uint8x4",
    a.Sint8x2 = "sint8x2",
    a.Sint8x4 = "sint8x4",
    a.Unorm8x2 = "unorm8x2",
    a.Unorm8x4 = "unorm8x4",
    a.Snorm8x2 = "snorm8x2",
    a.Snorm8x4 = "snorm8x4",
    a.Uint16x2 = "uint16x2",
    a.Uint16x4 = "uint16x4",
    a.Sint16x2 = "sint16x2",
    a.Sint16x4 = "sint16x4",
    a.Unorm16x2 = "unorm16x2",
    a.Unorm16x4 = "unorm16x4",
    a.Snorm16x2 = "snorm16x2",
    a.Snorm16x4 = "snorm16x4",
    a.Float16x2 = "float16x2",
    a.Float16x4 = "float16x4",
    a.Float32 = "float32",
    a.Float32x2 = "float32x2",
    a.Float32x3 = "float32x3",
    a.Float32x4 = "float32x4",
    a.Uint32 = "uint32",
    a.Uint32x2 = "uint32x2",
    a.Uint32x3 = "uint32x3",
    a.Uint32x4 = "uint32x4",
    a.Sint32 = "sint32",
    a.Sint32x2 = "sint32x2",
    a.Sint32x3 = "sint32x3",
    a.Sint32x4 = "sint32x4"
}
)(VertexFormat || (VertexFormat = {}));
var InputStepMode;
(function(a) {
    a.Vertex = "vertex",
    a.Instance = "instance"
}
)(InputStepMode || (InputStepMode = {}));
var ComputePassTimestampLocation;
(function(a) {
    a.Beginning = "beginning",
    a.End = "end"
}
)(ComputePassTimestampLocation || (ComputePassTimestampLocation = {}));
var RenderPassTimestampLocation;
(function(a) {
    a.Beginning = "beginning",
    a.End = "end"
}
)(RenderPassTimestampLocation || (RenderPassTimestampLocation = {}));
var LoadOp;
(function(a) {
    a.Load = "load"
}
)(LoadOp || (LoadOp = {}));
var StoreOp;
(function(a) {
    a.Store = "store",
    a.Discard = "discard"
}
)(StoreOp || (StoreOp = {}));
var QueryType;
(function(a) {
    a.Occlusion = "occlusion",
    a.Timestamp = "timestamp"
}
)(QueryType || (QueryType = {}));
var CanvasCompositingAlphaMode;
(function(a) {
    a.Opaque = "opaque",
    a.Premultiplied = "premultiplied"
}
)(CanvasCompositingAlphaMode || (CanvasCompositingAlphaMode = {}));
var DeviceLostReason;
(function(a) {
    a.Destroyed = "destroyed"
}
)(DeviceLostReason || (DeviceLostReason = {}));
var ErrorFilter;
(function(a) {
    a.OutOfMemory = "out-of-memory",
    a.Validation = "validation"
}
)(ErrorFilter || (ErrorFilter = {}));
var WebGPUShaderProcessor = function() {
    function a() {
        this.shaderLanguage = ShaderLanguage.GLSL
    }
    return a.prototype._addUniformToLeftOverUBO = function(e, i, o) {
        var s, c = 0;
        s = this._getArraySize(e, i, o),
        e = s[0],
        i = s[1],
        c = s[2];
        for (var d = 0; d < this.webgpuProcessingContext.leftOverUniforms.length; d++)
            if (this.webgpuProcessingContext.leftOverUniforms[d].name === e)
                return;
        this.webgpuProcessingContext.leftOverUniforms.push({
            name: e,
            type: i,
            length: c
        })
    }
    ,
    a.prototype._buildLeftOverUBO = function() {
        if (!this.webgpuProcessingContext.leftOverUniforms.length)
            return "";
        var e = a.LeftOvertUBOName
          , i = this.webgpuProcessingContext.availableBuffers[e];
        return i || (i = {
            binding: this.webgpuProcessingContext.getNextFreeUBOBinding()
        },
        this.webgpuProcessingContext.availableBuffers[e] = i,
        this._addBufferBindingDescription(e, i, BufferBindingType.Uniform, !0),
        this._addBufferBindingDescription(e, i, BufferBindingType.Uniform, !1)),
        this._generateLeftOverUBOCode(e, i)
    }
    ,
    a.prototype._collectBindingNames = function() {
        for (var e = 0; e < this.webgpuProcessingContext.bindGroupLayoutEntries.length; e++) {
            var i = this.webgpuProcessingContext.bindGroupLayoutEntries[e];
            if (i === void 0) {
                this.webgpuProcessingContext.bindGroupLayoutEntries[e] = [];
                continue
            }
            for (var o = 0; o < i.length; o++) {
                var s = this.webgpuProcessingContext.bindGroupLayoutEntries[e][o]
                  , c = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[e][s.binding].name
                  , d = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[e][s.binding].nameInArrayOfTexture;
                s && (s.texture || s.externalTexture || s.storageTexture ? this.webgpuProcessingContext.textureNames.push(d) : s.sampler ? this.webgpuProcessingContext.samplerNames.push(c) : s.buffer && this.webgpuProcessingContext.bufferNames.push(c))
            }
        }
    }
    ,
    a.prototype._preCreateBindGroupEntries = function() {
        for (var e = this.webgpuProcessingContext.bindGroupEntries, i = 0; i < this.webgpuProcessingContext.bindGroupLayoutEntries.length; i++) {
            for (var o = this.webgpuProcessingContext.bindGroupLayoutEntries[i], s = [], c = 0; c < o.length; c++) {
                var d = this.webgpuProcessingContext.bindGroupLayoutEntries[i][c];
                d.sampler || d.texture || d.storageTexture || d.externalTexture ? s.push({
                    binding: d.binding,
                    resource: void 0
                }) : d.buffer && s.push({
                    binding: d.binding,
                    resource: {
                        buffer: void 0,
                        offset: 0,
                        size: 0
                    }
                })
            }
            e[i] = s
        }
    }
    ,
    a.prototype._addTextureBindingDescription = function(e, i, o, s, c, d) {
        var _ = i.textures[o]
          , b = _.groupIndex
          , k = _.bindingIndex;
        if (this.webgpuProcessingContext.bindGroupLayoutEntries[b] || (this.webgpuProcessingContext.bindGroupLayoutEntries[b] = [],
        this.webgpuProcessingContext.bindGroupLayoutEntryInfo[b] = []),
        !this.webgpuProcessingContext.bindGroupLayoutEntryInfo[b][k]) {
            var j = void 0;
            s === null ? j = this.webgpuProcessingContext.bindGroupLayoutEntries[b].push({
                binding: k,
                visibility: 0,
                externalTexture: {}
            }) : c ? j = this.webgpuProcessingContext.bindGroupLayoutEntries[b].push({
                binding: k,
                visibility: 0,
                storageTexture: {
                    access: StorageTextureAccess.WriteOnly,
                    format: c,
                    viewDimension: s
                }
            }) : j = this.webgpuProcessingContext.bindGroupLayoutEntries[b].push({
                binding: k,
                visibility: 0,
                texture: {
                    sampleType: i.sampleType,
                    viewDimension: s,
                    multisampled: !1
                }
            });
            var $ = i.isTextureArray ? e + o : e;
            this.webgpuProcessingContext.bindGroupLayoutEntryInfo[b][k] = {
                name: e,
                index: j - 1,
                nameInArrayOfTexture: $
            }
        }
        k = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[b][k].index,
        d ? this.webgpuProcessingContext.bindGroupLayoutEntries[b][k].visibility |= ShaderStage.Vertex : this.webgpuProcessingContext.bindGroupLayoutEntries[b][k].visibility |= ShaderStage.Fragment
    }
    ,
    a.prototype._addSamplerBindingDescription = function(e, i, o) {
        var s = i.binding
          , c = s.groupIndex
          , d = s.bindingIndex;
        if (this.webgpuProcessingContext.bindGroupLayoutEntries[c] || (this.webgpuProcessingContext.bindGroupLayoutEntries[c] = [],
        this.webgpuProcessingContext.bindGroupLayoutEntryInfo[c] = []),
        !this.webgpuProcessingContext.bindGroupLayoutEntryInfo[c][d]) {
            var _ = this.webgpuProcessingContext.bindGroupLayoutEntries[c].push({
                binding: d,
                visibility: 0,
                sampler: {
                    type: i.type
                }
            });
            this.webgpuProcessingContext.bindGroupLayoutEntryInfo[c][d] = {
                name: e,
                index: _ - 1
            }
        }
        d = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[c][d].index,
        o ? this.webgpuProcessingContext.bindGroupLayoutEntries[c][d].visibility |= ShaderStage.Vertex : this.webgpuProcessingContext.bindGroupLayoutEntries[c][d].visibility |= ShaderStage.Fragment
    }
    ,
    a.prototype._addBufferBindingDescription = function(e, i, o, s) {
        var c = i.binding
          , d = c.groupIndex
          , _ = c.bindingIndex;
        if (this.webgpuProcessingContext.bindGroupLayoutEntries[d] || (this.webgpuProcessingContext.bindGroupLayoutEntries[d] = [],
        this.webgpuProcessingContext.bindGroupLayoutEntryInfo[d] = []),
        !this.webgpuProcessingContext.bindGroupLayoutEntryInfo[d][_]) {
            var b = this.webgpuProcessingContext.bindGroupLayoutEntries[d].push({
                binding: _,
                visibility: 0,
                buffer: {
                    type: o
                }
            });
            this.webgpuProcessingContext.bindGroupLayoutEntryInfo[d][_] = {
                name: e,
                index: b - 1
            }
        }
        _ = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[d][_].index,
        s ? this.webgpuProcessingContext.bindGroupLayoutEntries[d][_].visibility |= ShaderStage.Vertex : this.webgpuProcessingContext.bindGroupLayoutEntries[d][_].visibility |= ShaderStage.Fragment
    }
    ,
    a.AutoSamplerSuffix = "Sampler",
    a.LeftOvertUBOName = "LeftOver",
    a.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
    },
    a._SamplerFunctionByWebGLSamplerType = {
        sampler2D: "sampler2D",
        sampler2DArray: "sampler2DArray",
        sampler2DShadow: "sampler2DShadow",
        sampler2DArrayShadow: "sampler2DArrayShadow",
        samplerCube: "samplerCube",
        sampler3D: "sampler3D"
    },
    a._TextureTypeByWebGLSamplerType = {
        sampler2D: "texture2D",
        sampler2DArray: "texture2DArray",
        sampler2DShadow: "texture2D",
        sampler2DArrayShadow: "texture2DArray",
        samplerCube: "textureCube",
        samplerCubeArray: "textureCubeArray",
        sampler3D: "texture3D"
    },
    a._GpuTextureViewDimensionByWebGPUTextureType = {
        textureCube: TextureViewDimension.Cube,
        textureCubeArray: TextureViewDimension.CubeArray,
        texture2D: TextureViewDimension.E2d,
        texture2DArray: TextureViewDimension.E2dArray,
        texture3D: TextureViewDimension.E3d
    },
    a._SamplerTypeByWebGLSamplerType = {
        sampler2DShadow: "samplerShadow",
        sampler2DArrayShadow: "samplerShadow"
    },
    a._IsComparisonSamplerByWebGPUSamplerType = {
        samplerShadow: !0,
        samplerArrayShadow: !0,
        sampler: !1
    },
    a
}()
  , WebGPUPipelineContext = function() {
    function a(e, i) {
        this._name = "unnamed",
        this.shaderProcessingContext = e,
        this._leftOverUniformsByName = {},
        this.engine = i
    }
    return Object.defineProperty(a.prototype, "isAsync", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isReady", {
        get: function() {
            return !!this.stages
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._handlesSpectorRebuildCallback = function(e) {}
    ,
    a.prototype._fillEffectInformation = function(e, i, o, s, c, d, _, b) {
        var k = this.engine;
        e._fragmentSourceCode = "",
        e._vertexSourceCode = "";
        var j = this.shaderProcessingContext.availableTextures, $;
        for ($ = 0; $ < c.length; $++) {
            var _e = c[$]
              , et = j[c[$]];
            et == null || et == null ? (c.splice($, 1),
            $--) : d[_e] = $
        }
        for (var tt = 0, rt = k.getAttributes(this, _); tt < rt.length; tt++) {
            var it = rt[tt];
            b.push(it)
        }
        this.buildUniformLayout();
        var nt = []
          , ot = [];
        for ($ = 0; $ < _.length; $++) {
            var at = b[$];
            at >= 0 && (nt.push(_[$]),
            ot.push(at))
        }
        this.shaderProcessingContext.attributeNamesFromEffect = nt,
        this.shaderProcessingContext.attributeLocationsFromEffect = ot
    }
    ,
    a.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, i = this.shaderProcessingContext.leftOverUniforms; e < i.length; e++) {
                var o = i[e]
                  , s = o.type.replace(/^(.*?)(<.*>)?$/, "$1")
                  , c = WebGPUShaderProcessor.UniformSizes[s];
                this.uniformBuffer.addUniform(o.name, c, o.length),
                this._leftOverUniformsByName[o.name] = o.type
            }
            this.uniformBuffer.create()
        }
    }
    ,
    a.prototype.dispose = function() {
        this.uniformBuffer && this.uniformBuffer.dispose()
    }
    ,
    a.prototype.setInt = function(e, i) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateInt(e, i)
    }
    ,
    a.prototype.setInt2 = function(e, i, o) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateInt2(e, i, o)
    }
    ,
    a.prototype.setInt3 = function(e, i, o, s) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateInt3(e, i, o, s)
    }
    ,
    a.prototype.setInt4 = function(e, i, o, s, c) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateInt4(e, i, o, s, c)
    }
    ,
    a.prototype.setIntArray = function(e, i) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateIntArray(e, i)
    }
    ,
    a.prototype.setIntArray2 = function(e, i) {
        this.setIntArray(e, i)
    }
    ,
    a.prototype.setIntArray3 = function(e, i) {
        this.setIntArray(e, i)
    }
    ,
    a.prototype.setIntArray4 = function(e, i) {
        this.setIntArray(e, i)
    }
    ,
    a.prototype.setArray = function(e, i) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateArray(e, i)
    }
    ,
    a.prototype.setArray2 = function(e, i) {
        this.setArray(e, i)
    }
    ,
    a.prototype.setArray3 = function(e, i) {
        this.setArray(e, i)
    }
    ,
    a.prototype.setArray4 = function(e, i) {
        this.setArray(e, i)
    }
    ,
    a.prototype.setMatrices = function(e, i) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateMatrices(e, i)
    }
    ,
    a.prototype.setMatrix = function(e, i) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateMatrix(e, i)
    }
    ,
    a.prototype.setMatrix3x3 = function(e, i) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateMatrix3x3(e, i)
    }
    ,
    a.prototype.setMatrix2x2 = function(e, i) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateMatrix2x2(e, i)
    }
    ,
    a.prototype.setFloat = function(e, i) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateFloat(e, i)
    }
    ,
    a.prototype.setVector2 = function(e, i) {
        this.setFloat2(e, i.x, i.y)
    }
    ,
    a.prototype.setFloat2 = function(e, i, o) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateFloat2(e, i, o)
    }
    ,
    a.prototype.setVector3 = function(e, i) {
        this.setFloat3(e, i.x, i.y, i.z)
    }
    ,
    a.prototype.setFloat3 = function(e, i, o, s) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateFloat3(e, i, o, s)
    }
    ,
    a.prototype.setVector4 = function(e, i) {
        this.setFloat4(e, i.x, i.y, i.z, i.w)
    }
    ,
    a.prototype.setFloat4 = function(e, i, o, s, c) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateFloat4(e, i, o, s, c)
    }
    ,
    a.prototype.setColor3 = function(e, i) {
        this.setFloat3(e, i.r, i.g, i.b)
    }
    ,
    a.prototype.setColor4 = function(e, i, o) {
        this.setFloat4(e, i.r, i.g, i.b, o)
    }
    ,
    a.prototype.setDirectColor4 = function(e, i) {
        this.setFloat4(e, i.r, i.g, i.b, i.a)
    }
    ,
    a.prototype._getVertexShaderCode = function() {
        var e;
        return (e = this.sources) === null || e === void 0 ? void 0 : e.vertex
    }
    ,
    a.prototype._getFragmentShaderCode = function() {
        var e;
        return (e = this.sources) === null || e === void 0 ? void 0 : e.fragment
    }
    ,
    a
}()
  , _maxGroups = 4
  , _maxBindingsPerGroup = 1 << 16
  , _typeToLocationSize = {
    mat2: 2,
    mat3: 3,
    mat4: 4,
    mat2x2: 2,
    mat3x3: 3,
    mat4x4: 4
}
  , WebGPUShaderProcessingContext = function() {
    function a(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(a, "KnownUBOs", {
        get: function() {
            return a._SimplifiedKnownBindings ? a._SimplifiedKnownUBOs : a._KnownUBOs
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._findStartingGroupBinding = function() {
        var e = a.KnownUBOs
          , i = [];
        for (var o in e) {
            var s = e[o].binding;
            s.groupIndex !== -1 && (i[s.groupIndex] === void 0 ? i[s.groupIndex] = s.bindingIndex : i[s.groupIndex] = Math.max(i[s.groupIndex], s.bindingIndex))
        }
        this.freeGroupIndex = i.length - 1,
        this.freeGroupIndex === 0 ? (this.freeGroupIndex++,
        this.freeBindingIndex = 0) : this.freeBindingIndex = i[i.length - 1] + 1
    }
    ,
    a.prototype.getAttributeNextLocation = function(e, i) {
        var o;
        i === void 0 && (i = 0);
        var s = this._attributeNextLocation;
        return this._attributeNextLocation += ((o = _typeToLocationSize[e]) !== null && o !== void 0 ? o : 1) * (i || 1),
        s
    }
    ,
    a.prototype.getVaryingNextLocation = function(e, i) {
        var o;
        i === void 0 && (i = 0);
        var s = this._varyingNextLocation;
        return this._varyingNextLocation += ((o = _typeToLocationSize[e]) !== null && o !== void 0 ? o : 1) * (i || 1),
        s
    }
    ,
    a.prototype.getNextFreeUBOBinding = function() {
        return this._getNextFreeBinding(1)
    }
    ,
    a.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 i = {
            groupIndex: this.freeGroupIndex,
            bindingIndex: this.freeBindingIndex
        };
        return this.freeBindingIndex += e,
        i
    }
    ,
    a._SimplifiedKnownBindings = !0,
    a._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
            }
        }
    },
    a._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
            }
        }
    },
    a
}()
  , WebGPUShaderProcessorGLSL = function(a) {
    __extends(e, a);
    function e() {
        var i = a !== null && a.apply(this, arguments) || this;
        return i._missingVaryings = [],
        i._textureArrayProcessing = [],
        i.shaderLanguage = ShaderLanguage.GLSL,
        i
    }
    return e.prototype._getArraySize = function(i, o, s) {
        var c = 0
          , d = i.indexOf("[")
          , _ = i.indexOf("]");
        if (d > 0 && _ > 0) {
            var b = i.substring(d + 1, _);
            c = +b,
            isNaN(c) && (c = +s[b.trim()]),
            i = i.substr(0, d)
        }
        return [i, o, c]
    }
    ,
    e.prototype.initializeShaders = function(i) {
        this.webgpuProcessingContext = i,
        this._missingVaryings.length = 0,
        this._textureArrayProcessing.length = 0
    }
    ,
    e.prototype.varyingProcessor = function(i, o, s, c) {
        this._preProcessors = s;
        var d = /\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm
          , _ = d.exec(i);
        if (_ != null) {
            var b = _[1], k = _[2], j;
            o ? (j = this.webgpuProcessingContext.availableVaryings[k],
            this._missingVaryings[j] = "",
            j === void 0 && Logger$2.Warn('Invalid fragment shader: The varying named "' + k + '" is not declared in the vertex shader! This declaration will be ignored.')) : (j = this.webgpuProcessingContext.getVaryingNextLocation(b, this._getArraySize(k, b, s)[2]),
            this.webgpuProcessingContext.availableVaryings[k] = j,
            this._missingVaryings[j] = "layout(location = " + j + ") in " + b + " " + k + ";"),
            i = i.replace(_[0], j === void 0 ? "" : "layout(location = " + j + ") " + (o ? "in" : "out") + " " + b + " " + k + ";")
        }
        return i
    }
    ,
    e.prototype.attributeProcessor = function(i, o, s) {
        this._preProcessors = o;
        var c = /\s*attribute\s+(\S+)\s+(\S+)\s*;/gm
          , d = c.exec(i);
        if (d != null) {
            var _ = d[1]
              , b = d[2]
              , k = this.webgpuProcessingContext.getAttributeNextLocation(_, this._getArraySize(b, _, o)[2]);
            this.webgpuProcessingContext.availableAttributes[b] = k,
            this.webgpuProcessingContext.orderedAttributes[k] = b,
            i = i.replace(d[0], "layout(location = " + k + ") in " + _ + " " + b + ";")
        }
        return i
    }
    ,
    e.prototype.uniformProcessor = function(i, o, s, c) {
        var d, _;
        this._preProcessors = s;
        var b = /\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm
          , k = b.exec(i);
        if (k != null) {
            var j = k[1]
              , $ = k[2];
            if (j.indexOf("sampler") === 0 || j.indexOf("sampler") === 1) {
                var _e = 0;
                d = this._getArraySize($, j, s),
                $ = d[0],
                j = d[1],
                _e = d[2];
                var et = this.webgpuProcessingContext.availableTextures[$];
                if (!et) {
                    et = {
                        autoBindSampler: !0,
                        isTextureArray: _e > 0,
                        isStorageTexture: !1,
                        textures: [],
                        sampleType: TextureSampleType.Float
                    };
                    for (var tt = 0; tt < (_e || 1); ++tt)
                        et.textures.push(this.webgpuProcessingContext.getNextFreeUBOBinding())
                }
                var rt = (_ = WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[j]) !== null && _ !== void 0 ? _ : "sampler"
                  , it = !!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[rt]
                  , nt = it ? SamplerBindingType.Comparison : SamplerBindingType.Filtering
                  , ot = $ + WebGPUShaderProcessor.AutoSamplerSuffix
                  , at = this.webgpuProcessingContext.availableSamplers[ot];
                at || (at = {
                    binding: this.webgpuProcessingContext.getNextFreeUBOBinding(),
                    type: nt
                });
                var st = j.charAt(0) === "u" ? "u" : j.charAt(0) === "i" ? "i" : "";
                st && (j = j.substr(1));
                var ut = it ? TextureSampleType.Depth : st === "u" ? TextureSampleType.Uint : st === "i" ? TextureSampleType.Sint : TextureSampleType.Float;
                et.sampleType = ut;
                var ct = _e > 0
                  , lt = at.binding.groupIndex
                  , ft = at.binding.bindingIndex
                  , ht = WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[j]
                  , pt = WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[j]
                  , dt = WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[pt];
                if (!ct)
                    _e = 1,
                    i = "layout(set = " + lt + ", binding = " + ft + ") uniform " + st + rt + " " + ot + `;
                        layout(set = ` + et.textures[0].groupIndex + ", binding = " + et.textures[0].bindingIndex + ") uniform " + pt + " " + $ + `Texture;
                        #define ` + $ + " " + st + ht + "(" + $ + "Texture, " + ot + ")";
                else {
                    var _t = [];
                    _t.push("layout(set = " + lt + ", binding = " + ft + ") uniform " + st + rt + " " + ot + ";"),
                    i = `\r
`;
                    for (var tt = 0; tt < _e; ++tt) {
                        var mt = et.textures[tt].groupIndex
                          , vt = et.textures[tt].bindingIndex;
                        _t.push("layout(set = " + mt + ", binding = " + vt + ") uniform " + pt + " " + $ + "Texture" + tt + ";"),
                        i += (tt > 0 ? `\r
` : "") + "#define " + $ + tt + " " + st + ht + "(" + $ + "Texture" + tt + ", " + ot + ")"
                    }
                    i = _t.join(`\r
`) + i,
                    this._textureArrayProcessing.push($)
                }
                this.webgpuProcessingContext.availableTextures[$] = et,
                this.webgpuProcessingContext.availableSamplers[ot] = at,
                this._addSamplerBindingDescription(ot, at, !o);
                for (var tt = 0; tt < _e; ++tt)
                    this._addTextureBindingDescription($, et, tt, dt, null, !o)
            } else
                this._addUniformToLeftOverUBO($, j, s),
                i = ""
        }
        return i
    }
    ,
    e.prototype.uniformBufferProcessor = function(i, o, s) {
        var c = /uniform\s+(\w+)/gm
          , d = c.exec(i);
        if (d != null) {
            var _ = d[1]
              , b = this.webgpuProcessingContext.availableBuffers[_];
            if (!b) {
                var k = WebGPUShaderProcessingContext.KnownUBOs[_]
                  , j = void 0;
                k && k.binding.groupIndex !== -1 ? j = k.binding : j = this.webgpuProcessingContext.getNextFreeUBOBinding(),
                b = {
                    binding: j
                },
                this.webgpuProcessingContext.availableBuffers[_] = b
            }
            this._addBufferBindingDescription(_, b, BufferBindingType.Uniform, !o),
            i = i.replace("uniform", "layout(set = " + b.binding.groupIndex + ", binding = " + b.binding.bindingIndex + ") uniform")
        }
        return i
    }
    ,
    e.prototype.postProcessor = function(i, o, s, c, d) {
        var _ = i.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1
          , b = /#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 (i = i.replace(b, ""),
        i = i.replace(/texture2D\s*\(/g, "texture("),
        s)
            i = i.replace(/texture2DLodEXT\s*\(/g, "textureLod("),
            i = i.replace(/textureCubeLodEXT\s*\(/g, "textureLod("),
            i = i.replace(/textureCube\s*\(/g, "texture("),
            i = i.replace(/gl_FragDepthEXT/g, "gl_FragDepth"),
            i = i.replace(/gl_FragColor/g, "glFragColor"),
            i = i.replace(/gl_FragData/g, "glFragData"),
            i = i.replace(/void\s+?main\s*\(/g, (_ ? "" : `layout(location = 0) out vec4 glFragColor;
`) + "void main(");
        else {
            i = i.replace(/gl_InstanceID/g, "gl_InstanceIndex"),
            i = i.replace(/gl_VertexID/g, "gl_VertexIndex");
            var k = o.indexOf("#define MULTIVIEW") !== -1;
            if (k)
                return `#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
` + i
        }
        if (!s) {
            var j = i.lastIndexOf("}");
            i = i.substring(0, j),
            i += `gl_Position.y *= -1.;
`,
            d.isNDCHalfZRange || (i += `gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;
`),
            i += "}"
        }
        return i
    }
    ,
    e.prototype._applyTextureArrayProcessing = function(i, o) {
        for (var s = new RegExp(o + "\\s*\\[(.+)?\\]","gm"), c = s.exec(i); c != null; ) {
            var d = c[1]
              , _ = +d;
            this._preProcessors && isNaN(_) && (_ = +this._preProcessors[d.trim()]),
            i = i.replace(c[0], o + _),
            c = s.exec(i)
        }
        return i
    }
    ,
    e.prototype._generateLeftOverUBOCode = function(i, o) {
        for (var s = "layout(set = " + o.binding.groupIndex + ", binding = " + o.binding.bindingIndex + ") uniform " + i + ` {
    `, c = 0, d = this.webgpuProcessingContext.leftOverUniforms; c < d.length; c++) {
            var _ = d[c];
            _.length > 0 ? s += "    " + _.type + " " + _.name + "[" + _.length + `];
` : s += "    " + _.type + " " + _.name + `;
`
        }
        return s += `};

`,
        s
    }
    ,
    e.prototype.finalizeShaders = function(i, o, s) {
        for (var c = 0; c < this._textureArrayProcessing.length; ++c) {
            var d = this._textureArrayProcessing[c];
            i = this._applyTextureArrayProcessing(i, d),
            o = this._applyTextureArrayProcessing(o, d)
        }
        for (var c = 0; c < this._missingVaryings.length; ++c) {
            var _ = this._missingVaryings[c];
            _ && _.length > 0 && (o = _ + `
` + o)
        }
        var b = this._buildLeftOverUBO();
        return i = b + i,
        o = b + o,
        this._collectBindingNames(),
        this._preCreateBindGroupEntries(),
        this._preProcessors = null,
        {
            vertexCode: i,
            fragmentCode: o
        }
    }
    ,
    e
}(WebGPUShaderProcessor)
  , name$2V = "bonesDeclaration"
  , shader$2V = `#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$2V] = shader$2V;
var name$2U = "bonesVertex"
  , shader$2U = `#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$2U] = shader$2U;
var name$2T = "bakedVertexAnimationDeclaration"
  , shader$2T = `#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$2T] = shader$2T;
var name$2S = "bakedVertexAnimation"
  , shader$2S = `#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$2S] = shader$2S;
var name$2R = "clipPlaneFragment"
  , shader$2R = `#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$2R] = shader$2R;
var name$2Q = "clipPlaneFragmentDeclaration"
  , shader$2Q = `#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$2Q] = shader$2Q;
var name$2P = "clipPlaneVertex"
  , shader$2P = `#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$2P] = shader$2P;
var name$2O = "clipPlaneVertexDeclaration"
  , shader$2O = `#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$2O] = shader$2O;
var name$2N = "instancesDeclaration"
  , shader$2N = `#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$2N] = shader$2N;
var name$2M = "instancesVertex"
  , shader$2M = `#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$2M] = shader$2M;
var name$2L = "meshUboDeclaration"
  , shader$2L = `[[block]]
struct Mesh {
world : mat4x4<f32>;
visibility : f32;
};
var<uniform> mesh : Mesh;
#define WORLD_UBO
`;
ShaderStore.IncludesShadersStoreWGSL[name$2L] = shader$2L;
var name$2K = "morphTargetsVertex"
  , shader$2K = `#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$2K] = shader$2K;
var name$2J = "morphTargetsVertexDeclaration"
  , shader$2J = `#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$2J] = shader$2J;
var name$2I = "morphTargetsVertexGlobal"
  , shader$2I = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
var vertexID : f32;
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$2I] = shader$2I;
var name$2H = "morphTargetsVertexGlobalDeclaration"
  , shader$2H = `#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$2H] = shader$2H;
var name$2G = "sceneUboDeclaration"
  , shader$2G = `[[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$2G] = shader$2G;
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(a) {
    __extends(e, a);
    function e() {
        var i = a !== null && a.apply(this, arguments) || this;
        return i.shaderLanguage = ShaderLanguage.WGSL,
        i.uniformRegexp = /uniform\s+(\w+)\s*:\s*(.+)\s*;/,
        i.textureRegexp = /var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,
        i.noPrecision = !0,
        i
    }
    return e.prototype._getArraySize = function(i, o, s) {
        var c = 0
          , d = o.lastIndexOf(">");
        if (o.indexOf("array") >= 0 && d > 0) {
            for (var _ = d; _ > 0 && o.charAt(_) !== " " && o.charAt(_) !== ","; )
                _--;
            var b = o.substring(_ + 1, d);
            for (c = +b,
            isNaN(c) && (c = +s[b.trim()]); _ > 0 && (o.charAt(_) === " " || o.charAt(_) === ","); )
                _--;
            o = o.substring(o.indexOf("<") + 1, _ + 1)
        }
        return [i, o, c]
    }
    ,
    e.prototype.initializeShaders = function(i) {
        this.webgpuProcessingContext = i,
        this._attributesWGSL = [],
        this._attributesDeclWGSL = [],
        this._attributeNamesWGSL = [],
        this._varyingsWGSL = [],
        this._varyingsDeclWGSL = [],
        this._varyingNamesWGSL = []
    }
    ,
    e.prototype.preProcessShaderCode = function(i) {
        return RemoveComments(i)
    }
    ,
    e.prototype.varyingProcessor = function(i, o, s, c) {
        var d = /\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm
          , _ = d.exec(i);
        if (_ !== null) {
            var b = _[2], k = _[1], j;
            o ? (j = this.webgpuProcessingContext.availableVaryings[k],
            j === void 0 && Logger$2.Warn('Invalid fragment shader: The varying named "' + k + '" is not declared in the vertex shader! This declaration will be ignored.')) : (j = this.webgpuProcessingContext.getVaryingNextLocation(b, this._getArraySize(k, b, s)[2]),
            this.webgpuProcessingContext.availableVaryings[k] = j,
            this._varyingsWGSL.push("[[location(" + j + ")]] " + k + " : " + b + ";"),
            this._varyingsDeclWGSL.push("var<private> " + k + " : " + b + ";"),
            this._varyingNamesWGSL.push(k)),
            i = ""
        }
        return i
    }
    ,
    e.prototype.attributeProcessor = function(i, o, s) {
        var c = /\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm
          , d = c.exec(i);
        if (d !== null) {
            var _ = d[2]
              , b = d[1]
              , k = this.webgpuProcessingContext.getAttributeNextLocation(_, this._getArraySize(b, _, o)[2]);
            this.webgpuProcessingContext.availableAttributes[b] = k,
            this.webgpuProcessingContext.orderedAttributes[k] = b,
            this._attributesWGSL.push("[[location(" + k + ")]] " + b + " : " + _ + ";"),
            this._attributesDeclWGSL.push("var<private> " + b + " : " + _ + ";"),
            this._attributeNamesWGSL.push(b),
            i = ""
        }
        return i
    }
    ,
    e.prototype.uniformProcessor = function(i, o, s, c) {
        var d = this.uniformRegexp.exec(i);
        if (d !== null) {
            var _ = d[2]
              , b = d[1];
            this._addUniformToLeftOverUBO(b, _, s),
            i = ""
        }
        return i
    }
    ,
    e.prototype.textureProcessor = function(i, o, s, c) {
        var d = this.textureRegexp.exec(i);
        if (d !== null) {
            var _ = d[1]
              , b = d[2]
              , k = !!d[3]
              , j = d[4]
              , $ = j.indexOf("storage") > 0
              , _e = d[6]
              , et = $ ? _e.substring(0, _e.indexOf(",")).trim() : null
              , tt = k ? this._getArraySize(_, b, s)[2] : 0
              , rt = this.webgpuProcessingContext.availableTextures[_];
            if (rt)
                tt = rt.textures.length;
            else {
                rt = {
                    isTextureArray: tt > 0,
                    isStorageTexture: $,
                    textures: [],
                    sampleType: TextureSampleType.Float
                },
                tt = tt || 1;
                for (var it = 0; it < tt; ++it)
                    rt.textures.push(this.webgpuProcessingContext.getNextFreeUBOBinding())
            }
            this.webgpuProcessingContext.availableTextures[_] = rt;
            var nt = j.indexOf("depth") > 0
              , ot = gpuTextureViewDimensionByWebGPUTextureFunction[j]
              , at = nt ? TextureSampleType.Depth : _e === "u32" ? TextureSampleType.Uint : _e === "i32" ? TextureSampleType.Sint : TextureSampleType.Float;
            if (rt.sampleType = at,
            ot === void 0)
                throw `Can't get the texture dimension corresponding to the texture function "` + j + '"!';
            for (var it = 0; it < tt; ++it) {
                var st = rt.textures[it]
                  , ut = st.groupIndex
                  , ct = st.bindingIndex;
                it === 0 && (i = "[[group(" + ut + "), binding(" + ct + ")]] " + i),
                this._addTextureBindingDescription(_, rt, it, ot, et, !o)
            }
        }
        return i
    }
    ,
    e.prototype.postProcessor = function(i, o, s, c, d) {
        return i
    }
    ,
    e.prototype.finalizeShaders = function(i, o, s) {
        i = this._processSamplers(i, !0),
        o = this._processSamplers(o, !1),
        i = this._processCustomBuffers(i, !0),
        o = this._processCustomBuffers(o, !1);
        var c = this._buildLeftOverUBO();
        i = c + i,
        o = c + o,
        i = i.replace(/#define /g, "//#define ");
        var d = this._varyingsDeclWGSL.join(`
`) + `
`
          , _ = "var<private> " + builtInName_vertex_index + ` : u32;
var<private> ` + builtInName_instance_index + ` : u32;
var<private> ` + builtInName_position + ` : vec4<f32>;
`
          , b = this._attributesDeclWGSL.join(`
`) + `
`
          , k = `struct VertexInputs {
  [[builtin(vertex_index)]] vertexIndex : u32;
  [[builtin(instance_index)]] instanceIndex : u32;
`;
        this._attributesWGSL.length > 0 && (k += this._attributesWGSL.join(`
`)),
        k += `
};
`;
        var j = `struct FragmentInputs {
  [[builtin(position)]] position : vec4<f32>;
`;
        this._varyingsWGSL.length > 0 && (j += this._varyingsWGSL.join(`
`)),
        j += `
};
`,
        i = _ + k + b + j + d + i;
        for (var $ = `  var output : FragmentInputs;
  ` + builtInName_vertex_index + ` = input.vertexIndex;
  ` + builtInName_instance_index + ` = input.instanceIndex;
`, _e = 0; _e < this._attributeNamesWGSL.length; ++_e) {
            var et = this._attributeNamesWGSL[_e];
            $ += "  " + et + " = input." + et + `;
`
        }
        for (var tt = "  output.position = " + builtInName_position + `;
  output.position.y = -output.position.y;
`, _e = 0; _e < this._varyingNamesWGSL.length; ++_e) {
            var rt = this._varyingNamesWGSL[_e];
            tt += "  output." + rt + " = " + rt + `;
`
        }
        tt += "  return output;",
        i = this._injectStartingAndEndingCode(i, $, tt),
        o = o.replace(/#define /g, "//#define ");
        var it = "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;
`
          , nt = `struct FragmentInputs {
  [[builtin(position)]] position : vec4<f32>;
  [[builtin(front_facing)]] frontFacing : bool;
`;
        this._varyingsWGSL.length > 0 && (nt += this._varyingsWGSL.join(`
`)),
        nt += `
};
`;
        for (var ot = `struct FragmentOutputs {
  [[location(0)]] color : vec4<f32>;
`, at = !1, st = 0; !at && (st = o.indexOf(builtInName_frag_depth, st),
        !(st < 0)); ) {
            var ut = st;
            for (at = !0; st > 1 && o.charAt(st) !== `
`; ) {
                if (o.charAt(st) === "/" && o.charAt(st - 1) === "/") {
                    at = !1;
                    break
                }
                st--
            }
            st = ut + 12
        }
        at && (ot += `  [[builtin(frag_depth)]] fragDepth: f32;
`),
        ot += `};
`,
        o = it + nt + d + ot + o;
        for (var ct = `  var output : FragmentOutputs;
  ` + builtInName_position_frag + ` = input.position;
  ` + builtInName_front_facing + ` = input.frontFacing;
`, _e = 0; _e < this._varyingNamesWGSL.length; ++_e) {
            var lt = this._varyingNamesWGSL[_e];
            ct += "  " + lt + " = input." + lt + `;
`
        }
        var ft = "  output.color = " + builtInName_FragColor + `;
`;
        return at && (ft += "  output.fragDepth = " + builtInName_frag_depth + `;
`),
        ft += "  return output;",
        o = this._injectStartingAndEndingCode(o, ct, ft),
        this._collectBindingNames(),
        this._preCreateBindGroupEntries(),
        {
            vertexCode: i,
            fragmentCode: o
        }
    }
    ,
    e.prototype._generateLeftOverUBOCode = function(i, o) {
        for (var s = "[[block]] struct " + i + ` {
`, c = 0, d = this.webgpuProcessingContext.leftOverUniforms; c < d.length; c++) {
            var _ = d[c]
              , b = _.type.replace(/^(.*?)(<.*>)?$/, "$1")
              , k = WebGPUShaderProcessor.UniformSizes[b];
            _.length > 0 ? k <= 2 ? s += " [[align(16)]] " + _.name + " : [[stride(16)]] array<" + _.type + ", " + _.length + `>;
` : s += " " + _.name + " : array<" + _.type + ", " + _.length + `>;
` : s += "  " + _.name + " : " + _.type + `;
`
        }
        return s += `};
`,
        s += "[[group(" + o.binding.groupIndex + "), binding(" + o.binding.bindingIndex + ")]] var<uniform> " + leftOverVarName + " : " + i + `;
`,
        s
    }
    ,
    e.prototype._injectStartingAndEndingCode = function(i, o, s) {
        if (o) {
            var c = i.indexOf("fn main");
            if (c >= 0) {
                for (; c++ < i.length && i.charAt(c) != "{"; )
                    ;
                if (c < i.length) {
                    for (; c++ < i.length && i.charAt(c) != `
`; )
                        ;
                    if (c < i.length) {
                        var d = i.substring(0, c + 1)
                          , _ = i.substring(c + 1);
                        i = d + o + _
                    }
                }
            }
        }
        if (s) {
            var b = i.lastIndexOf("}");
            i = i.substring(0, b),
            i += s + `
}`
        }
        return i
    }
    ,
    e.prototype._processSamplers = function(i, o) {
        for (var s = /var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm; ; ) {
            var c = s.exec(i);
            if (c === null)
                break;
            var d = c[1]
              , _ = c[2]
              , b = d.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix) === d.length - WebGPUShaderProcessor.AutoSamplerSuffix.length ? d.substring(0, d.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)) : null
              , k = _ === "sampler_comparison" ? SamplerBindingType.Comparison : SamplerBindingType.Filtering;
            if (b) {
                var j = this.webgpuProcessingContext.availableTextures[b];
                j && (j.autoBindSampler = !0)
            }
            var $ = this.webgpuProcessingContext.availableSamplers[d];
            $ || ($ = {
                binding: this.webgpuProcessingContext.getNextFreeUBOBinding(),
                type: k
            },
            this.webgpuProcessingContext.availableSamplers[d] = $),
            this._addSamplerBindingDescription(d, $, o);
            var _e = i.substring(0, c.index)
              , et = "[[group(" + $.binding.groupIndex + "), binding(" + $.binding.bindingIndex + ")]] "
              , tt = i.substring(c.index);
            i = _e + et + tt,
            s.lastIndex += et.length
        }
        return i
    }
    ,
    e.prototype._processCustomBuffers = function(i, o) {
        for (var s = /var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm; ; ) {
            var c = s.exec(i);
            if (c === null)
                break;
            var d = c[1]
              , _ = c[3]
              , b = c[4]
              , k = c[5]
              , j = this.webgpuProcessingContext.availableBuffers[b];
            if (!j) {
                var $ = d === "uniform" ? WebGPUShaderProcessingContext.KnownUBOs[k] : null
                  , _e = void 0;
                $ ? (b = k,
                _e = $.binding,
                _e.groupIndex === -1 && (_e = this.webgpuProcessingContext.getNextFreeUBOBinding())) : _e = this.webgpuProcessingContext.getNextFreeUBOBinding(),
                j = {
                    binding: _e
                },
                this.webgpuProcessingContext.availableBuffers[b] = j
            }
            this._addBufferBindingDescription(b, this.webgpuProcessingContext.availableBuffers[b], _ === "read_write" ? BufferBindingType.Storage : d === "storage" ? BufferBindingType.ReadOnlyStorage : BufferBindingType.Uniform, o);
            var et = j.binding.groupIndex
              , tt = j.binding.bindingIndex
              , rt = i.substring(0, c.index)
              , it = "[[group(" + et + "), binding(" + tt + ")]] "
              , nt = i.substring(c.index);
            i = rt + it + nt,
            s.lastIndex += it.length
        }
        return i
    }
    ,
    e
}(WebGPUShaderProcessor), WebGPUHardwareTexture = function() {
    function a(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(a.prototype, "underlyingResource", {
        get: function() {
            return this._webgpuTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "msaaTexture", {
        get: function() {
            return this._webgpuMSAATexture
        },
        set: function(e) {
            this._webgpuMSAATexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.set = function(e) {
        this._webgpuTexture = e
    }
    ,
    a.prototype.setMSAATexture = function(e) {
        this._webgpuMSAATexture = e
    }
    ,
    a.prototype.setUsage = function(e, i, o, s, c) {
        i = e === InternalTextureSource.RenderTarget ? !1 : i,
        this.createView({
            format: this.format,
            dimension: o ? TextureViewDimension.Cube : TextureViewDimension.E2d,
            mipLevelCount: i ? Scalar.ILog2(Math.max(s, c)) + 1 : 1,
            baseArrayLayer: 0,
            baseMipLevel: 0,
            arrayLayerCount: o ? 6 : 1,
            aspect: TextureAspect.All
        })
    }
    ,
    a.prototype.createView = function(e) {
        this.view = this._webgpuTexture.createView(e)
    }
    ,
    a.prototype.reset = function() {
        this._webgpuTexture = null,
        this._webgpuMSAATexture = null,
        this.view = null
    }
    ,
    a.prototype.release = function() {
        var e, i, o;
        (e = this._webgpuTexture) === null || e === void 0 || e.destroy(),
        (i = this._webgpuMSAATexture) === null || i === void 0 || i.destroy(),
        (o = this._copyInvertYTempTexture) === null || o === void 0 || o.destroy(),
        this.reset()
    }
    ,
    a
}(), 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(a) {
    a[a.MipMap = 0] = "MipMap",
    a[a.InvertYPremultiplyAlpha = 1] = "InvertYPremultiplyAlpha",
    a[a.Clear = 2] = "Clear"
}
)(PipelineType || (PipelineType = {}));
var shadersForPipelineType = [{
    vertex: mipmapVertexSource,
    fragment: mipmapFragmentSource
}, {
    vertex: invertYPreMultiplyAlphaVertexSource,
    fragment: invertYPreMultiplyAlphaFragmentSource
}, {
    vertex: clearVertexSource,
    fragment: clearFragmentSource
}], WebGPUTextureHelper = function() {
    function a(e, i, o, s) {
        this._pipelines = {},
        this._compiledShaders = [],
        this._deferredReleaseTextures = [],
        this._device = e,
        this._glslang = i,
        this._tintWASM = o,
        this._bufferManager = s,
        this._mipmapSampler = e.createSampler({
            minFilter: FilterMode.Linear
        }),
        this._getPipeline(TextureFormat.RGBA8Unorm)
    }
    return a.ComputeNumMipmapLevels = function(e, i) {
        return Scalar.ILog2(Math.max(e, i)) + 1
    }
    ,
    a.prototype._getPipeline = function(e, i, o) {
        i === void 0 && (i = PipelineType.MipMap);
        var s = i === PipelineType.MipMap ? 1 << 0 : i === PipelineType.InvertYPremultiplyAlpha ? ((o.invertY ? 1 : 0) << 1) + ((o.premultiplyAlpha ? 1 : 0) << 2) : i === PipelineType.Clear ? 1 << 3 : 0;
        this._pipelines[e] || (this._pipelines[e] = []);
        var c = this._pipelines[e][s];
        if (!c) {
            var d = `#version 450\r
`;
            i === PipelineType.InvertYPremultiplyAlpha && (o.invertY && (d += `#define INVERTY\r
`),
            o.premultiplyAlpha && (d += `#define PREMULTIPLYALPHA\r
`));
            var _ = this._compiledShaders[s];
            if (!_) {
                var b = this._glslang.compileGLSL(d + shadersForPipelineType[i].vertex, "vertex")
                  , k = this._glslang.compileGLSL(d + shadersForPipelineType[i].fragment, "fragment");
                this._tintWASM && (b = this._tintWASM.convertSpirV2WGSL(b),
                k = this._tintWASM.convertSpirV2WGSL(k));
                var j = this._device.createShaderModule({
                    code: b
                })
                  , $ = this._device.createShaderModule({
                    code: k
                });
                _ = this._compiledShaders[s] = [j, $]
            }
            var _e = this._device.createRenderPipeline({
                vertex: {
                    module: _[0],
                    entryPoint: "main"
                },
                fragment: {
                    module: _[1],
                    entryPoint: "main",
                    targets: [{
                        format: e
                    }]
                },
                primitive: {
                    topology: PrimitiveTopology.TriangleStrip,
                    stripIndexFormat: IndexFormat.Uint16
                }
            });
            c = this._pipelines[e][s] = [_e, _e.getBindGroupLayout(0)]
        }
        return c
    }
    ,
    a._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
    }
    ,
    a._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
        }
    }
    ,
    a._IsHardwareTexture = function(e) {
        return !!e.release
    }
    ,
    a._IsInternalTexture = function(e) {
        return !!e.dispose
    }
    ,
    a.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
        }
    }
    ,
    a.IsImageBitmap = function(e) {
        return e.close !== void 0
    }
    ,
    a.IsImageBitmapArray = function(e) {
        return Array.isArray(e) && e[0].close !== void 0
    }
    ,
    a.prototype.setCommandEncoder = function(e) {
        this._commandEncoderForCreation = e
    }
    ,
    a.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
    }
    ,
    a.GetWebGPUTextureFormat = function(e, i, o) {
        switch (o === void 0 && (o = !1),
        i) {
        case 15:
            return TextureFormat.Depth16Unorm;
        case 13:
            return TextureFormat.Depth24PlusStencil8;
        case 14:
            return TextureFormat.Depth32Float;
        case 36492:
            return o ? TextureFormat.BC7RGBAUnormSRGB : TextureFormat.BC7RGBAUnorm;
        case 36495:
            return TextureFormat.BC6HRGBUFloat;
        case 36494:
            return TextureFormat.BC6HRGBFloat;
        case 33779:
            return o ? TextureFormat.BC3RGBAUnormSRGB : TextureFormat.BC3RGBAUnorm;
        case 33778:
            return o ? TextureFormat.BC2RGBAUnormSRGB : TextureFormat.BC2RGBAUnorm;
        case 33777:
        case 33776:
            return o ? TextureFormat.BC1RGBAUnormSRGB : TextureFormat.BC1RGBAUnorm;
        case 37808:
            return o ? TextureFormat.ASTC4x4UnormSRGB : TextureFormat.ASTC4x4Unorm;
        case 36196:
            return o ? TextureFormat.ETC2RGB8UnormSRGB : TextureFormat.ETC2RGB8Unorm
        }
        switch (e) {
        case 3:
            switch (i) {
            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 (i) {
            case 6:
                return TextureFormat.R8Unorm;
            case 7:
                return TextureFormat.RG8Unorm;
            case 4:
                throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
            case 5:
                return o ? TextureFormat.RGBA8UnormSRGB : TextureFormat.RGBA8Unorm;
            case 12:
                return o ? 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 (i) {
            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 (i) {
            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 (i) {
            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 (i) {
            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 (i) {
            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 (i) {
            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 (i) {
            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 o ? TextureFormat.RGBA8UnormSRGB : TextureFormat.RGBA8Unorm
    }
    ,
    a.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 + "!"
    }
    ,
    a.prototype.invertYPreMultiplyAlpha = function(e, i, o, s, c, d, _, b, k, j, $) {
        var _e, et, tt, rt, it, nt, ot;
        c === void 0 && (c = !1),
        d === void 0 && (d = !1),
        _ === void 0 && (_ = 0),
        b === void 0 && (b = 0),
        k === void 0 && (k = 1);
        var at = j === void 0
          , st = this._getPipeline(s, PipelineType.InvertYPremultiplyAlpha, {
            invertY: c,
            premultiplyAlpha: d
        })
          , ut = st[0]
          , ct = st[1];
        _ = Math.max(_, 0),
        at && (j = this._device.createCommandEncoder({})),
        (et = (_e = j).pushDebugGroup) === null || et === void 0 || et.call(_e, "internal process texture - invertY=" + c + " premultiplyAlpha=" + d);
        var lt;
        if (a._IsHardwareTexture(e) ? (lt = e.underlyingResource,
        c && !d && k === 1 && _ === 0 || (e = void 0)) : (lt = e,
        e = void 0),
        !!lt) {
            var ft = e
              , ht = (tt = ft == null ? void 0 : ft._copyInvertYTempTexture) !== null && tt !== void 0 ? tt : this.createTexture({
                width: i,
                height: o,
                layers: 1
            }, !1, !1, !1, !1, !1, s, 1, j, TextureUsage.CopySrc | TextureUsage.RenderAttachment | TextureUsage.TextureBinding)
              , pt = (rt = ft == null ? void 0 : ft._copyInvertYRenderPassDescr) !== null && rt !== void 0 ? rt : {
                colorAttachments: [{
                    view: ht.createView({
                        format: s,
                        dimension: TextureViewDimension.E2d,
                        baseMipLevel: 0,
                        mipLevelCount: 1,
                        arrayLayerCount: 1,
                        baseArrayLayer: 0
                    }),
                    loadValue: LoadOp.Load,
                    storeOp: StoreOp.Store
                }]
            }
              , dt = j.beginRenderPass(pt)
              , _t = (it = ft == null ? void 0 : ft._copyInvertYBindGroupd) !== null && it !== void 0 ? it : this._device.createBindGroup({
                layout: ct,
                entries: [{
                    binding: 0,
                    resource: lt.createView({
                        format: s,
                        dimension: TextureViewDimension.E2d,
                        baseMipLevel: b,
                        mipLevelCount: 1,
                        arrayLayerCount: k,
                        baseArrayLayer: _
                    })
                }]
            });
            dt.setPipeline(ut),
            dt.setBindGroup(0, _t),
            dt.draw(4, 1, 0, 0),
            dt.endPass(),
            j.copyTextureToTexture({
                texture: ht
            }, {
                texture: lt,
                mipLevel: b,
                origin: {
                    x: 0,
                    y: 0,
                    z: _
                }
            }, {
                width: i,
                height: o,
                depthOrArrayLayers: 1
            }),
            ft ? (ft._copyInvertYTempTexture = ht,
            ft._copyInvertYRenderPassDescr = pt,
            ft._copyInvertYBindGroupd = _t) : this._deferredReleaseTextures.push([ht, null]),
            (ot = (nt = j).popDebugGroup) === null || ot === void 0 || ot.call(nt),
            at && (this._device.queue.submit([j.finish()]),
            j = null)
        }
    }
    ,
    a.prototype.copyWithInvertY = function(e, i, o, s) {
        var c, d, _, b, k = s === void 0, j = this._getPipeline(i, PipelineType.InvertYPremultiplyAlpha, {
            invertY: !0,
            premultiplyAlpha: !1
        }), $ = j[0], _e = j[1];
        k && (s = this._device.createCommandEncoder({})),
        (d = (c = s).pushDebugGroup) === null || d === void 0 || d.call(c, "internal copy texture with invertY");
        var et = s.beginRenderPass(o)
          , tt = this._device.createBindGroup({
            layout: _e,
            entries: [{
                binding: 0,
                resource: e
            }]
        });
        et.setPipeline($),
        et.setBindGroup(0, tt),
        et.draw(4, 1, 0, 0),
        et.endPass(),
        (b = (_ = s).popDebugGroup) === null || b === void 0 || b.call(_),
        k && (this._device.queue.submit([s.finish()]),
        s = null)
    }
    ,
    a.prototype.createTexture = function(e, i, o, s, c, d, _, b, k, j, $) {
        i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        s === void 0 && (s = !1),
        c === void 0 && (c = !1),
        d === void 0 && (d = !1),
        _ === void 0 && (_ = TextureFormat.RGBA8Unorm),
        b === void 0 && (b = 1),
        j === void 0 && (j = -1),
        $ === void 0 && ($ = 0);
        var _e = e.layers || 1
          , et = {
            width: e.width,
            height: e.height,
            depthOrArrayLayers: _e
        }
          , tt = a.IsCompressedFormat(_)
          , rt = i ? a.ComputeNumMipmapLevels(e.width, e.height) : 1
          , it = j >= 0 ? j : TextureUsage.CopySrc | TextureUsage.CopyDst | TextureUsage.TextureBinding;
        $ |= i && !tt ? TextureUsage.CopySrc | TextureUsage.RenderAttachment : 0,
        tt || ($ |= TextureUsage.RenderAttachment | TextureUsage.CopyDst);
        var nt = this._device.createTexture({
            size: et,
            dimension: d ? TextureDimension.E3d : TextureDimension.E2d,
            format: _,
            usage: it | $,
            sampleCount: b,
            mipLevelCount: rt
        });
        return a.IsImageBitmap(e) && (this.updateTexture(e, nt, e.width, e.height, _e, _, 0, 0, s, c, 0, 0, k),
        i && o && this.generateMipmaps(nt, _, rt, 0, k)),
        nt
    }
    ,
    a.prototype.createCubeTexture = function(e, i, o, s, c, d, _, b, k, j) {
        i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        s === void 0 && (s = !1),
        c === void 0 && (c = !1),
        d === void 0 && (d = TextureFormat.RGBA8Unorm),
        _ === void 0 && (_ = 1),
        k === void 0 && (k = -1),
        j === void 0 && (j = 0);
        var $ = a.IsImageBitmapArray(e) ? e[0].width : e.width
          , _e = a.IsImageBitmapArray(e) ? e[0].height : e.height
          , et = a.IsCompressedFormat(d)
          , tt = i ? a.ComputeNumMipmapLevels($, _e) : 1
          , rt = k >= 0 ? k : TextureUsage.CopySrc | TextureUsage.CopyDst | TextureUsage.TextureBinding;
        j |= i && !et ? TextureUsage.CopySrc | TextureUsage.RenderAttachment : 0,
        et || (j |= TextureUsage.RenderAttachment | TextureUsage.CopyDst);
        var it = this._device.createTexture({
            size: {
                width: $,
                height: _e,
                depthOrArrayLayers: 6
            },
            dimension: TextureDimension.E2d,
            format: d,
            usage: rt | j,
            sampleCount: _,
            mipLevelCount: tt
        });
        return a.IsImageBitmapArray(e) && (this.updateCubeTextures(e, it, $, _e, d, s, c, 0, 0, b),
        i && o && this.generateCubeMipmaps(it, d, tt, b)),
        it
    }
    ,
    a.prototype.generateCubeMipmaps = function(e, i, o, s) {
        var c, d, _, b, k = s === void 0;
        k && (s = this._device.createCommandEncoder({})),
        (d = (c = s).pushDebugGroup) === null || d === void 0 || d.call(c, "create cube mipmaps - " + o + " levels");
        for (var j = 0; j < 6; ++j)
            this.generateMipmaps(e, i, o, j, s);
        (b = (_ = s).popDebugGroup) === null || b === void 0 || b.call(_),
        k && (this._device.queue.submit([s.finish()]),
        s = null)
    }
    ,
    a.prototype.generateMipmaps = function(e, i, o, s, c) {
        var d, _, b, k, j, $, _e, et;
        s === void 0 && (s = 0);
        var tt = c === void 0
          , rt = this._getPipeline(i)
          , it = rt[0]
          , nt = rt[1];
        s = Math.max(s, 0),
        tt && (c = this._device.createCommandEncoder({})),
        (_ = (d = c).pushDebugGroup) === null || _ === void 0 || _.call(d, "create mipmaps for face #" + s + " - " + o + " levels");
        var ot;
        if (a._IsHardwareTexture(e) ? (ot = e.underlyingResource,
        e._mipmapGenRenderPassDescr = e._mipmapGenRenderPassDescr || [],
        e._mipmapGenBindGroup = e._mipmapGenBindGroup || []) : (ot = e,
        e = void 0),
        !!ot) {
            for (var at = e, st = 1; st < o; ++st) {
                var ut = (k = (b = at == null ? void 0 : at._mipmapGenRenderPassDescr[s]) === null || b === void 0 ? void 0 : b[st - 1]) !== null && k !== void 0 ? k : {
                    colorAttachments: [{
                        view: ot.createView({
                            format: i,
                            dimension: TextureViewDimension.E2d,
                            baseMipLevel: st,
                            mipLevelCount: 1,
                            arrayLayerCount: 1,
                            baseArrayLayer: s
                        }),
                        loadValue: LoadOp.Load,
                        storeOp: StoreOp.Store
                    }]
                };
                at && (at._mipmapGenRenderPassDescr[s] = at._mipmapGenRenderPassDescr[s] || [],
                at._mipmapGenRenderPassDescr[s][st - 1] = ut);
                var ct = c.beginRenderPass(ut)
                  , lt = ($ = (j = at == null ? void 0 : at._mipmapGenBindGroup[s]) === null || j === void 0 ? void 0 : j[st - 1]) !== null && $ !== void 0 ? $ : this._device.createBindGroup({
                    layout: nt,
                    entries: [{
                        binding: 0,
                        resource: this._mipmapSampler
                    }, {
                        binding: 1,
                        resource: ot.createView({
                            format: i,
                            dimension: TextureViewDimension.E2d,
                            baseMipLevel: st - 1,
                            mipLevelCount: 1,
                            arrayLayerCount: 1,
                            baseArrayLayer: s
                        })
                    }]
                });
                at && (at._mipmapGenBindGroup[s] = at._mipmapGenBindGroup[s] || [],
                at._mipmapGenBindGroup[s][st - 1] = lt),
                ct.setPipeline(it),
                ct.setBindGroup(0, lt),
                ct.draw(4, 1, 0, 0),
                ct.endPass()
            }
            (et = (_e = c).popDebugGroup) === null || et === void 0 || et.call(_e),
            tt && (this._device.queue.submit([c.finish()]),
            c = null)
        }
    }
    ,
    a.prototype.createGPUTextureForInternalTexture = function(e, i, o, s, c) {
        e._hardwareTexture || (e._hardwareTexture = new WebGPUHardwareTexture),
        i === void 0 && (i = e.width),
        o === void 0 && (o = e.height),
        s === void 0 && (s = e.depth);
        var d = e._hardwareTexture;
        d.format = a.GetWebGPUTextureFormat(e.type, e.format, e._useSRGBBuffer),
        d.textureUsages = e._source === InternalTextureSource.RenderTarget || e.source === InternalTextureSource.MultiRenderTarget ? TextureUsage.TextureBinding | TextureUsage.CopySrc | TextureUsage.RenderAttachment : e._source === InternalTextureSource.DepthStencil ? TextureUsage.TextureBinding | TextureUsage.RenderAttachment : -1,
        d.textureAdditionalUsages = (c != null ? c : 0) & 1 ? TextureUsage.StorageBinding : 0;
        var _ = e.generateMipMaps
          , b = s || 1;
        if (e.isCube) {
            var k = this.createCubeTexture({
                width: i,
                height: o
            }, e.generateMipMaps, e.generateMipMaps, e.invertY, !1, d.format, 1, this._commandEncoderForCreation, d.textureUsages, d.textureAdditionalUsages);
            d.set(k),
            d.createView({
                format: d.format,
                dimension: TextureViewDimension.Cube,
                mipLevelCount: _ ? a.ComputeNumMipmapLevels(i, o) : 1,
                baseArrayLayer: 0,
                baseMipLevel: 0,
                arrayLayerCount: 6,
                aspect: TextureAspect.All
            })
        } else {
            var k = this.createTexture({
                width: i,
                height: o,
                layers: b
            }, e.generateMipMaps, e.generateMipMaps, e.invertY, !1, e.is3D, d.format, 1, this._commandEncoderForCreation, d.textureUsages, d.textureAdditionalUsages);
            d.set(k),
            d.createView({
                format: d.format,
                dimension: e.is2DArray ? TextureViewDimension.E2dArray : e.is3D ? TextureDimension.E3d : TextureViewDimension.E2d,
                mipLevelCount: _ ? a.ComputeNumMipmapLevels(i, o) : 1,
                baseArrayLayer: 0,
                baseMipLevel: 0,
                arrayLayerCount: e.is3D ? 1 : b,
                aspect: TextureAspect.All
            })
        }
        return e.width = e.baseWidth = i,
        e.height = e.baseHeight = o,
        e.depth = e.baseDepth = s,
        this.createMSAATexture(e, e.samples),
        d
    }
    ,
    a.prototype.createMSAATexture = function(e, i) {
        var o = e._hardwareTexture;
        if (o != null && o.msaaTexture && (this.releaseTexture(o.msaaTexture),
        o.msaaTexture = null),
        !(!o || (i != null ? i : 1) <= 1)) {
            var s = e.width
              , c = e.height
              , d = e.depth || 1;
            if (e.isCube) {
                var _ = this.createCubeTexture({
                    width: s,
                    height: c
                }, !1, !1, e.invertY, !1, o.format, i, this._commandEncoderForCreation, o.textureUsages, o.textureAdditionalUsages);
                o.setMSAATexture(_)
            } else {
                var _ = this.createTexture({
                    width: s,
                    height: c,
                    layers: d
                }, !1, !1, e.invertY, !1, e.is3D, o.format, i, this._commandEncoderForCreation, o.textureUsages, o.textureAdditionalUsages);
                o.setMSAATexture(_)
            }
        }
    }
    ,
    a.prototype.updateCubeTextures = function(e, i, o, s, c, d, _, b, k, j) {
        d === void 0 && (d = !1),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = 0),
        k === void 0 && (k = 0);
        for (var $ = [0, 3, 1, 4, 2, 5], _e = 0; _e < $.length; ++_e) {
            var et = e[$[_e]];
            this.updateTexture(et, i, o, s, 1, c, _e, 0, d, _, b, k, j)
        }
    }
    ,
    a.prototype.updateTexture = function(e, i, o, s, c, d, _, b, k, j, $, _e, et, tt) {
        _ === void 0 && (_ = 0),
        b === void 0 && (b = 0),
        k === void 0 && (k = !1),
        j === void 0 && (j = !1),
        $ === void 0 && ($ = 0),
        _e === void 0 && (_e = 0);
        var rt = a._IsInternalTexture(i) ? i._hardwareTexture.underlyingResource : i
          , it = a._GetBlockInformationFromFormat(d)
          , nt = a._IsInternalTexture(i) ? i._hardwareTexture : i
          , ot = {
            texture: rt,
            origin: {
                x: $,
                y: _e,
                z: Math.max(_, 0)
            },
            mipLevel: b,
            premultipliedAlpha: j
        }
          , at = {
            width: Math.ceil(o / it.width) * it.width,
            height: Math.ceil(s / it.height) * it.height,
            depthOrArrayLayers: c || 1
        };
        if (e.byteLength !== void 0) {
            e = e;
            var st = Math.ceil(o / it.width) * it.length
              , ut = Math.ceil(st / 256) * 256 === st;
            if (ut) {
                var ct = et === void 0;
                ct && (et = this._device.createCommandEncoder({}));
                var lt = this._bufferManager.createRawBuffer(e.byteLength, BufferUsage.MapWrite | BufferUsage.CopySrc, !0)
                  , ft = lt.getMappedRange();
                new Uint8Array(ft).set(e),
                lt.unmap(),
                et.copyBufferToTexture({
                    buffer: lt,
                    offset: 0,
                    bytesPerRow: st,
                    rowsPerImage: s
                }, ot, at),
                ct && (this._device.queue.submit([et.finish()]),
                et = null),
                this._bufferManager.releaseBuffer(lt)
            } else
                this._device.queue.writeTexture(ot, e, {
                    offset: 0,
                    bytesPerRow: st,
                    rowsPerImage: s
                }, at);
            (k || j) && this.invertYPreMultiplyAlpha(nt, o, s, d, k, j, _, b, c || 1, et, tt)
        } else if (e = e,
        k)
            if (ot.premultipliedAlpha = !1,
            a._IsInternalTexture(i) && $ === 0 && _e === 0 && o === i.width && s === i.height)
                this._device.queue.copyExternalImageToTexture({
                    source: e
                }, ot, at),
                this.invertYPreMultiplyAlpha(nt, o, s, d, k, j, _, b, c || 1, void 0, tt);
            else {
                et = this._device.createCommandEncoder({});
                var ht = this.createTexture({
                    width: o,
                    height: s,
                    layers: 1
                }, !1, !1, !1, !1, !1, d, 1, et, TextureUsage.CopySrc | TextureUsage.TextureBinding);
                this._deferredReleaseTextures.push([ht, null]),
                at.depthOrArrayLayers = 1,
                this._device.queue.copyExternalImageToTexture({
                    source: e
                }, {
                    texture: ht
                }, at),
                at.depthOrArrayLayers = c || 1,
                this.invertYPreMultiplyAlpha(ht, o, s, d, k, j, _, b, c || 1, et, tt),
                et.copyTextureToTexture({
                    texture: ht
                }, ot, at),
                this._device.queue.submit([et.finish()]),
                et = null
            }
        else
            this._device.queue.copyExternalImageToTexture({
                source: e
            }, ot, at)
    }
    ,
    a.prototype.readPixels = function(e, i, o, s, c, d, _, b, k, j) {
        _ === void 0 && (_ = 0),
        b === void 0 && (b = 0),
        k === void 0 && (k = null),
        j === void 0 && (j = !1);
        var $ = a._GetBlockInformationFromFormat(d)
          , _e = Math.ceil(s / $.width) * $.length
          , et = Math.ceil(_e / 256) * 256
          , tt = et * c
          , rt = this._bufferManager.createRawBuffer(tt, BufferUsage.MapRead | BufferUsage.CopyDst)
          , it = this._device.createCommandEncoder({});
        return it.copyTextureToBuffer({
            texture: e,
            mipLevel: b,
            origin: {
                x: i,
                y: o,
                z: Math.max(_, 0)
            }
        }, {
            buffer: rt,
            offset: 0,
            bytesPerRow: et
        }, {
            width: s,
            height: c,
            depthOrArrayLayers: 1
        }),
        this._device.queue.submit([it.finish()]),
        this._bufferManager.readDataFromBuffer(rt, tt, s, c, _e, et, a._GetTextureTypeFromFormat(d), 0, k, !0, j)
    }
    ,
    a.prototype.releaseTexture = function(e) {
        if (a._IsInternalTexture(e)) {
            var i = e._hardwareTexture
              , o = e._irradianceTexture;
            this._deferredReleaseTextures.push([i, o])
        } else
            this._deferredReleaseTextures.push([e, null])
    }
    ,
    a.prototype.destroyDeferredTextures = function() {
        for (var e = 0; e < this._deferredReleaseTextures.length; ++e) {
            var i = this._deferredReleaseTextures[e]
              , o = i[0]
              , s = i[1];
            o && (a._IsHardwareTexture(o) ? o.release() : o.destroy()),
            s == null || s.dispose()
        }
        this._deferredReleaseTextures.length = 0
    }
    ,
    a
}(), WebGPUDataBuffer = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this) || this;
        return o._buffer = i,
        o
    }
    return Object.defineProperty(e.prototype, "underlyingResource", {
        get: function() {
            return this._buffer
        },
        enumerable: !1,
        configurable: !0
    }),
    e
}(DataBuffer), WebGPUBufferManager = function() {
    function a(e) {
        this._deferredReleaseBuffers = [],
        this._device = e
    }
    return a._IsGPUBuffer = function(e) {
        return e.underlyingResource === void 0
    }
    ,
    a.prototype.createRawBuffer = function(e, i, o) {
        o === void 0 && (o = !1);
        var s = e.byteLength !== void 0 ? e.byteLength + 3 & -4 : e + 3 & -4
          , c = {
            mappedAtCreation: o,
            size: s,
            usage: i
        };
        return this._device.createBuffer(c)
    }
    ,
    a.prototype.createBuffer = function(e, i) {
        var o = e.byteLength !== void 0
          , s = this.createRawBuffer(e, i)
          , c = new WebGPUDataBuffer(s);
        return c.references = 1,
        c.capacity = o ? e.byteLength : e,
        o && this.setSubData(c, 0, e),
        c
    }
    ,
    a.prototype.setRawData = function(e, i, o, s, c) {
        this._device.queue.writeBuffer(e, i, o.buffer, s, c)
    }
    ,
    a.prototype.setSubData = function(e, i, o, s, c) {
        s === void 0 && (s = 0),
        c === void 0 && (c = 0);
        var d = e.underlyingResource;
        c = c || o.byteLength,
        c = Math.min(c, e.capacity - i);
        var _ = o.byteOffset + s
          , b = _ + c
          , k = c + 3 & -4;
        if (k !== c) {
            var j = new Uint8Array(o.buffer.slice(_, b));
            o = new Uint8Array(k),
            o.set(j),
            s = 0,
            _ = 0,
            b = k,
            c = k
        }
        for (var $ = 1024 * 1024 * 15, _e = 0; b - (_ + _e) > $; )
            this._device.queue.writeBuffer(d, i + _e, o.buffer, _ + _e, $),
            _e += $;
        this._device.queue.writeBuffer(d, i + _e, o.buffer, _ + _e, c - _e)
    }
    ,
    a.prototype._GetHalfFloatAsFloatRGBAArrayBuffer = function(e, i, o) {
        o || (o = new Float32Array(e));
        for (var s = new Uint16Array(i); e--; )
            o[e] = FromHalfFloat(s[e]);
        return o
    }
    ,
    a.prototype.readDataFromBuffer = function(e, i, o, s, c, d, _, b, k, j, $) {
        var _e = this;
        _ === void 0 && (_ = 0),
        b === void 0 && (b = 0),
        k === void 0 && (k = null),
        j === void 0 && (j = !0),
        $ === void 0 && ($ = !1);
        var et = _ === 1 ? 2 : _ === 2 ? 1 : 0;
        return new Promise(function(tt, rt) {
            e.mapAsync(MapMode.Read, b, i).then(function() {
                var it = e.getMappedRange(b, i)
                  , nt = k;
                if ($)
                    nt === null ? nt = allocateAndCopyTypedBuffer(_, i, !0, it) : nt = allocateAndCopyTypedBuffer(_, nt.buffer, void 0, it);
                else if (nt === null)
                    switch (et) {
                    case 0:
                        nt = new Uint8Array(i),
                        nt.set(new Uint8Array(it));
                        break;
                    case 1:
                        nt = _e._GetHalfFloatAsFloatRGBAArrayBuffer(i / 2, it);
                        break;
                    case 2:
                        nt = new Float32Array(i / 4),
                        nt.set(new Float32Array(it));
                        break
                    }
                else
                    switch (et) {
                    case 0:
                        nt = new Uint8Array(nt.buffer),
                        nt.set(new Uint8Array(it));
                        break;
                    case 1:
                        nt = _e._GetHalfFloatAsFloatRGBAArrayBuffer(i / 2, it, k);
                        break;
                    case 2:
                        nt = new Float32Array(nt.buffer),
                        nt.set(new Float32Array(it));
                        break
                    }
                if (c !== d) {
                    et === 1 && !$ && (c *= 2,
                    d *= 2);
                    for (var ot = new Uint8Array(nt.buffer), at = c, st = 0, ut = 1; ut < s; ++ut) {
                        st = ut * d;
                        for (var ct = 0; ct < c; ++ct)
                            ot[at++] = ot[st++]
                    }
                    et !== 0 && !$ ? nt = new Float32Array(ot.buffer,0,at / 4) : nt = new Uint8Array(ot.buffer,0,at)
                }
                e.unmap(),
                j && _e.releaseBuffer(e),
                tt(nt)
            }, function(it) {
                return rt(it)
            })
        }
        )
    }
    ,
    a.prototype.releaseBuffer = function(e) {
        return a._IsGPUBuffer(e) ? (this._deferredReleaseBuffers.push(e),
        !0) : (e.references--,
        e.references === 0 ? (this._deferredReleaseBuffers.push(e.underlyingResource),
        !0) : !1)
    }
    ,
    a.prototype.destroyDeferredBuffers = function() {
        for (var e = 0; e < this._deferredReleaseBuffers.length; ++e)
            this._deferredReleaseBuffers[e].destroy();
        this._deferredReleaseBuffers.length = 0
    }
    ,
    a
}(), WebGPURenderPassWrapper = function() {
    function a() {
        this.colorAttachmentGPUTextures = [],
        this.reset()
    }
    return a.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)
    }
    ,
    a
}(), 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 a(e) {
        this._samplers = {},
        this._device = e,
        this.disabled = !1
    }
    return a.GetSamplerHashCode = function(e) {
        var i, o, s, c = e._cachedAnisotropicFilteringLevel && e._cachedAnisotropicFilteringLevel > 1 ? 4 : 1, d = filterToBits[e.samplingMode] + comparisonFunctionToBits[(e._comparisonFunction || 514) - 512 + 1] + filterNoMipToBits[e.samplingMode] + (((i = e._cachedWrapU) !== null && i !== void 0 ? i : 1) << 8) + (((o = e._cachedWrapV) !== null && o !== void 0 ? o : 1) << 10) + (((s = e._cachedWrapR) !== null && s !== void 0 ? s : 1) << 12) + ((e.useMipMaps ? 1 : 0) << 14) + (c << 15);
        return d
    }
    ,
    a._GetSamplerFilterDescriptor = function(e, i) {
        var o, s, c, d, _, b = e.useMipMaps;
        switch (e.samplingMode) {
        case 11:
            o = FilterMode.Linear,
            s = FilterMode.Linear,
            c = FilterMode.Nearest,
            b || (d = _ = 0);
            break;
        case 3:
        case 3:
            o = FilterMode.Linear,
            s = FilterMode.Linear,
            b ? c = FilterMode.Linear : (c = FilterMode.Nearest,
            d = _ = 0);
            break;
        case 8:
            o = FilterMode.Nearest,
            s = FilterMode.Nearest,
            b ? c = FilterMode.Linear : (c = FilterMode.Nearest,
            d = _ = 0);
            break;
        case 4:
            o = FilterMode.Nearest,
            s = FilterMode.Nearest,
            c = FilterMode.Nearest,
            b || (d = _ = 0);
            break;
        case 5:
            o = FilterMode.Nearest,
            s = FilterMode.Linear,
            c = FilterMode.Nearest,
            b || (d = _ = 0);
            break;
        case 6:
            o = FilterMode.Nearest,
            s = FilterMode.Linear,
            b ? c = FilterMode.Linear : (c = FilterMode.Nearest,
            d = _ = 0);
            break;
        case 7:
            o = FilterMode.Nearest,
            s = FilterMode.Linear,
            c = FilterMode.Nearest,
            d = _ = 0;
            break;
        case 1:
        case 1:
            o = FilterMode.Nearest,
            s = FilterMode.Nearest,
            c = FilterMode.Nearest,
            d = _ = 0;
            break;
        case 9:
            o = FilterMode.Linear,
            s = FilterMode.Nearest,
            c = FilterMode.Nearest,
            b || (d = _ = 0);
            break;
        case 10:
            o = FilterMode.Linear,
            s = FilterMode.Nearest,
            b ? c = FilterMode.Linear : (c = FilterMode.Nearest,
            d = _ = 0);
            break;
        case 2:
        case 2:
            o = FilterMode.Linear,
            s = FilterMode.Linear,
            c = FilterMode.Nearest,
            d = _ = 0;
            break;
        case 12:
            o = FilterMode.Linear,
            s = FilterMode.Nearest,
            c = FilterMode.Nearest,
            d = _ = 0;
            break;
        default:
            o = FilterMode.Nearest,
            s = FilterMode.Nearest,
            c = FilterMode.Nearest,
            d = _ = 0;
            break
        }
        return i > 1 && (d !== 0 || _ !== 0) ? {
            magFilter: FilterMode.Linear,
            minFilter: FilterMode.Linear,
            mipmapFilter: FilterMode.Linear,
            anisotropyEnabled: !0
        } : {
            magFilter: o,
            minFilter: s,
            mipmapFilter: c,
            lodMinClamp: d,
            lodMaxClamp: _
        }
    }
    ,
    a._GetWrappingMode = function(e) {
        switch (e) {
        case 1:
            return AddressMode.Repeat;
        case 0:
            return AddressMode.ClampToEdge;
        case 2:
            return AddressMode.MirrorRepeat
        }
        return AddressMode.Repeat
    }
    ,
    a._GetSamplerWrappingDescriptor = function(e) {
        return {
            addressModeU: this._GetWrappingMode(e._cachedWrapU),
            addressModeV: this._GetWrappingMode(e._cachedWrapV),
            addressModeW: this._GetWrappingMode(e._cachedWrapR)
        }
    }
    ,
    a._GetSamplerDescriptor = function(e) {
        var i = e.useMipMaps && e._cachedAnisotropicFilteringLevel && e._cachedAnisotropicFilteringLevel > 1 ? 4 : 1
          , o = this._GetSamplerFilterDescriptor(e, i);
        return __assign(__assign(__assign({}, o), this._GetSamplerWrappingDescriptor(e)), {
            compare: e._comparisonFunction ? WebGPUTextureHelper.GetCompareFunction(e._comparisonFunction) : void 0,
            maxAnisotropy: o.anisotropyEnabled ? i : 1
        })
    }
    ,
    a.prototype.getSampler = function(e, i, o) {
        if (i === void 0 && (i = !1),
        o === void 0 && (o = 0),
        this.disabled)
            return this._device.createSampler(a._GetSamplerDescriptor(e));
        i ? o = 0 : o === 0 && (o = a.GetSamplerHashCode(e));
        var s = i ? void 0 : this._samplers[o];
        return s || (s = this._device.createSampler(a._GetSamplerDescriptor(e)),
        i || (this._samplers[o] = s)),
        s
    }
    ,
    a
}(), StatePosition;
(function(a) {
    a[a.StencilReadMask = 0] = "StencilReadMask",
    a[a.StencilWriteMask = 1] = "StencilWriteMask",
    a[a.DepthBias = 2] = "DepthBias",
    a[a.DepthBiasSlopeScale = 3] = "DepthBiasSlopeScale",
    a[a.MRTAttachments1 = 4] = "MRTAttachments1",
    a[a.MRTAttachments2 = 5] = "MRTAttachments2",
    a[a.DepthStencilState = 6] = "DepthStencilState",
    a[a.RasterizationState = 7] = "RasterizationState",
    a[a.ColorStates = 8] = "ColorStates",
    a[a.ShaderStage = 9] = "ShaderStage",
    a[a.TextureStage = 10] = "TextureStage",
    a[a.VertexState = 11] = "VertexState",
    a[a.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 a(e, i, o) {
        this._device = e,
        this._useTextureStage = o,
        this._states = new Array(30),
        this._statesLength = 0,
        this._stateDirtyLowestIndex = 0,
        this._emptyVertexBuffer = i,
        this._mrtFormats = [],
        this._parameter = {
            token: void 0,
            pipeline: null
        },
        this.disabled = !1,
        this.vertexBuffers = [],
        this._kMaxVertexBufferStride = e.limits.maxVertexBufferArrayStride || 2048,
        this.reset()
    }
    return a.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(a.prototype, "colorFormats", {
        get: function() {
            return this._mrtAttachments1 > 0 ? this._mrtFormats : this._webgpuColorFormat
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getRenderPipeline = function(e, i, o, s) {
        if (s === void 0 && (s = 0),
        this.disabled) {
            var c = a._GetTopology(e);
            return this._setVertexState(i),
            this._parameter.pipeline = this._createRenderPipeline(i, c, o),
            a.NumCacheMiss++,
            a._NumPipelineCreationCurrentFrame++,
            this._parameter.pipeline
        }
        if (this._setShaderStage(i.uniqueId),
        this._setRasterizationState(e, o),
        this._setColorStates(),
        this._setDepthStencilState(),
        this._setVertexState(i),
        this._setTextureState(s),
        this.lastStateDirtyLowestIndex = this._stateDirtyLowestIndex,
        !this._isDirty && this._parameter.pipeline)
            return this._stateDirtyLowestIndex = this._statesLength,
            a.NumCacheHitWithoutHash++,
            this._parameter.pipeline;
        if (this._getRenderPipeline(this._parameter),
        this._isDirty = !1,
        this._stateDirtyLowestIndex = this._statesLength,
        this._parameter.pipeline)
            return a.NumCacheHitWithHash++,
            this._parameter.pipeline;
        var d = a._GetTopology(e);
        return this._parameter.pipeline = this._createRenderPipeline(i, d, o),
        this._setRenderPipeline(this._parameter),
        a.NumCacheMiss++,
        a._NumPipelineCreationCurrentFrame++,
        this._parameter.pipeline
    }
    ,
    a.prototype.endFrame = function() {
        a.NumPipelineCreationLastFrame = a._NumPipelineCreationCurrentFrame,
        a._NumPipelineCreationCurrentFrame = 0
    }
    ,
    a.prototype.setAlphaToCoverage = function(e) {
        this._alphaToCoverageEnabled = e
    }
    ,
    a.prototype.setFrontFace = function(e) {
        this._frontFace = e
    }
    ,
    a.prototype.setCullEnabled = function(e) {
        this._cullEnabled = e
    }
    ,
    a.prototype.setCullFace = function(e) {
        this._cullFace = e
    }
    ,
    a.prototype.setClampDepth = function(e) {
        this._clampDepth = e
    }
    ,
    a.prototype.resetDepthCullingState = function() {
        this.setDepthCullingState(!1, 2, 1, 0, 0, !0, !0, 519)
    }
    ,
    a.prototype.setDepthCullingState = function(e, i, o, s, c, d, _, b) {
        this._depthWriteEnabled = _,
        this._depthTestEnabled = d,
        this._depthCompare = (b != null ? b : 519) - 512,
        this._cullFace = o,
        this._cullEnabled = e,
        this._frontFace = i,
        this.setDepthBiasSlopeScale(s),
        this.setDepthBias(c)
    }
    ,
    a.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))
    }
    ,
    a.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))
    }
    ,
    a.prototype.setColorFormat = function(e) {
        this._webgpuColorFormat[0] = e,
        this._colorFormat = textureFormatToIndex[e]
    }
    ,
    a.prototype.setMRTAttachments = function(e, i) {
        var o;
        if (e.length > 10)
            throw "Can't handle more than 10 attachments for a MRT in cache render pipeline!";
        this.mrtAttachments = e,
        this.mrtTextureArray = i;
        for (var s = [0, 0], c = 0, d = 0, _ = 0, b = 0; b < e.length; ++b) {
            var k = e[b];
            if (k !== 0) {
                var j = i[k - 1]
                  , $ = j == null ? void 0 : j._hardwareTexture;
                this._mrtFormats[_] = (o = $ == null ? void 0 : $.format) !== null && o !== void 0 ? o : this._webgpuColorFormat[0],
                s[c] += textureFormatToIndex[this._mrtFormats[_]] << d,
                d += 6,
                _++,
                d >= 32 && (d = 0,
                c++)
            }
        }
        this._mrtFormats.length = _,
        (this._mrtAttachments1 !== s[0] || this._mrtAttachments2 !== s[1]) && (this._mrtAttachments1 = s[0],
        this._mrtAttachments2 = s[1],
        this._states[StatePosition.MRTAttachments1] = s[0],
        this._states[StatePosition.MRTAttachments2] = s[1],
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1))
    }
    ,
    a.prototype.setAlphaBlendEnabled = function(e) {
        this._alphaBlendEnabled = e
    }
    ,
    a.prototype.setAlphaBlendFactors = function(e, i) {
        this._alphaBlendFuncParams = e,
        this._alphaBlendEqParams = i
    }
    ,
    a.prototype.setWriteMask = function(e) {
        this._writeMask = e
    }
    ,
    a.prototype.setDepthStencilFormat = function(e) {
        this._webgpuDepthStencilFormat = e,
        this._depthStencilFormat = e === void 0 ? 0 : textureFormatToIndex[e]
    }
    ,
    a.prototype.setDepthTestEnabled = function(e) {
        this._depthTestEnabled = e
    }
    ,
    a.prototype.setDepthWriteEnabled = function(e) {
        this._depthWriteEnabled = e
    }
    ,
    a.prototype.setDepthCompare = function(e) {
        this._depthCompare = (e != null ? e : 519) - 512
    }
    ,
    a.prototype.setStencilEnabled = function(e) {
        this._stencilEnabled = e
    }
    ,
    a.prototype.setStencilCompare = function(e) {
        this._stencilFrontCompare = (e != null ? e : 519) - 512
    }
    ,
    a.prototype.setStencilDepthFailOp = function(e) {
        this._stencilFrontDepthFailOp = e === null ? 1 : stencilOpToIndex[e]
    }
    ,
    a.prototype.setStencilPassOp = function(e) {
        this._stencilFrontPassOp = e === null ? 2 : stencilOpToIndex[e]
    }
    ,
    a.prototype.setStencilFailOp = function(e) {
        this._stencilFrontFailOp = e === null ? 1 : stencilOpToIndex[e]
    }
    ,
    a.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))
    }
    ,
    a.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))
    }
    ,
    a.prototype.resetStencilState = function() {
        this.setStencilState(!1, 519, 7680, 7681, 7680, 255, 255)
    }
    ,
    a.prototype.setStencilState = function(e, i, o, s, c, d, _) {
        this._stencilEnabled = e,
        this._stencilFrontCompare = (i != null ? i : 519) - 512,
        this._stencilFrontDepthFailOp = o === null ? 1 : stencilOpToIndex[o],
        this._stencilFrontPassOp = s === null ? 2 : stencilOpToIndex[s],
        this._stencilFrontFailOp = c === null ? 1 : stencilOpToIndex[c],
        this.setStencilReadMask(d),
        this.setStencilWriteMask(_)
    }
    ,
    a.prototype.setBuffers = function(e, i, o) {
        this._vertexBuffers = e,
        this._overrideVertexBuffers = o,
        this._indexBuffer = i
    }
    ,
    a._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
        }
    }
    ,
    a._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
        }
    }
    ,
    a._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
        }
    }
    ,
    a._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
    }
    ,
    a._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
    }
    ,
    a._GetVertexInputDescriptorFormat = function(e) {
        var i = e.type
          , o = e.normalized
          , s = e.getSize();
        switch (i) {
        case VertexBuffer.BYTE:
            switch (s) {
            case 1:
            case 2:
                return o ? VertexFormat.Snorm8x2 : VertexFormat.Sint8x2;
            case 3:
            case 4:
                return o ? VertexFormat.Snorm8x4 : VertexFormat.Sint8x4
            }
            break;
        case VertexBuffer.UNSIGNED_BYTE:
            switch (s) {
            case 1:
            case 2:
                return o ? VertexFormat.Unorm8x2 : VertexFormat.Uint8x2;
            case 3:
            case 4:
                return o ? VertexFormat.Unorm8x4 : VertexFormat.Uint8x4
            }
            break;
        case VertexBuffer.SHORT:
            switch (s) {
            case 1:
            case 2:
                return o ? VertexFormat.Snorm16x2 : VertexFormat.Sint16x2;
            case 3:
            case 4:
                return o ? VertexFormat.Snorm16x4 : VertexFormat.Sint16x4
            }
            break;
        case VertexBuffer.UNSIGNED_SHORT:
            switch (s) {
            case 1:
            case 2:
                return o ? VertexFormat.Unorm16x2 : VertexFormat.Uint16x2;
            case 3:
            case 4:
                return o ? VertexFormat.Unorm16x4 : VertexFormat.Uint16x4
            }
            break;
        case VertexBuffer.INT:
            switch (s) {
            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 (s) {
            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 (s) {
            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=" + i + ", normalized=" + o + ", size=" + s)
    }
    ,
    a.prototype._getAphaBlendState = function() {
        return this._alphaBlendEnabled ? {
            srcFactor: a._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),
            dstFactor: a._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),
            operation: a._GetAphaBlendOperation(this._alphaBlendEqParams[1])
        } : null
    }
    ,
    a.prototype._getColorBlendState = function() {
        return this._alphaBlendEnabled ? {
            srcFactor: a._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),
            dstFactor: a._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),
            operation: a._GetAphaBlendOperation(this._alphaBlendEqParams[0])
        } : null
    }
    ,
    a.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))
    }
    ,
    a.prototype._setRasterizationState = function(e, i) {
        var o = this._frontFace
          , s = this._cullEnabled ? this._cullFace : 0
          , c = this._clampDepth ? 1 : 0
          , d = this._alphaToCoverageEnabled ? 1 : 0
          , _ = o - 1 + (s << 1) + (c << 3) + (d << 4) + (e << 5) + (i << 8);
        this._rasterizationState !== _ && (this._rasterizationState = _,
        this._states[StatePosition.RasterizationState] = this._rasterizationState,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.RasterizationState))
    }
    ,
    a.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))
    }
    ,
    a.prototype._setDepthStencilState = function() {
        var e = this._stencilEnabled ? this._stencilFrontCompare + (this._stencilFrontDepthFailOp << 3) + (this._stencilFrontPassOp << 6) + (this._stencilFrontFailOp << 9) : 591
          , i = this._depthStencilFormat + ((this._depthTestEnabled ? this._depthCompare : 7) << 6) + (e << 10);
        this._depthStencilState !== i && (this._depthStencilState = i,
        this._states[StatePosition.DepthStencilState] = this._depthStencilState,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthStencilState))
    }
    ,
    a.prototype._setVertexState = function(e) {
        for (var i, o, s = this._statesLength, c = StatePosition.VertexState, d = e._pipelineContext, _ = d.shaderProcessingContext.attributeNamesFromEffect, b = d.shaderProcessingContext.attributeLocationsFromEffect, k, j = 0, $ = 0; $ < _.length; $++) {
            var _e = b[$]
              , et = (i = this._overrideVertexBuffers && this._overrideVertexBuffers[_[$]]) !== null && i !== void 0 ? i : this._vertexBuffers[_[$]];
            et || (et = this._emptyVertexBuffer);
            var tt = (o = et.getBuffer()) === null || o === void 0 ? void 0 : o.underlyingResource;
            if (et._validOffsetRange === void 0) {
                var rt = et.byteOffset
                  , it = et.getSize(!0)
                  , nt = et.byteStride;
                et._validOffsetRange = rt <= this._kMaxVertexBufferStride - it && (nt === 0 || rt + it <= nt)
            }
            k && k === tt && et._validOffsetRange || (this.vertexBuffers[j++] = et,
            k = et._validOffsetRange ? tt : null);
            var ot = et.hashCode + (_e << 7);
            this._isDirty = this._isDirty || this._states[c] !== ot,
            this._states[c++] = ot
        }
        this.vertexBuffers.length = j,
        this._statesLength = c,
        this._isDirty = this._isDirty || c !== s,
        this._isDirty && (this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.VertexState))
    }
    ,
    a.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))
    }
    ,
    a.prototype._createPipelineLayout = function(e) {
        if (this._useTextureStage)
            return this._createPipelineLayoutWithTextureStage(e);
        for (var i = [], o = e.shaderProcessingContext.bindGroupLayoutEntries, s = 0; s < o.length; s++) {
            var c = o[s];
            i[s] = this._device.createBindGroupLayout({
                entries: c
            })
        }
        return e.bindGroupLayouts = i,
        this._device.createPipelineLayout({
            bindGroupLayouts: i
        })
    }
    ,
    a.prototype._createPipelineLayoutWithTextureStage = function(e) {
        for (var i, o = e.shaderProcessingContext, s = o.bindGroupLayoutEntries, c = 1, d = 0; d < s.length; d++)
            for (var _ = s[d], b = 0; b < _.length; b++) {
                var k = s[d][b];
                if (k.texture) {
                    var j = o.bindGroupLayoutEntryInfo[d][k.binding].name
                      , $ = o.availableTextures[j]
                      , _e = $.autoBindSampler ? o.availableSamplers[j + WebGPUShaderProcessor.AutoSamplerSuffix] : null
                      , et = $.sampleType
                      , tt = (i = _e == null ? void 0 : _e.type) !== null && i !== void 0 ? i : SamplerBindingType.Filtering;
                    if (this._textureState & c && et !== TextureSampleType.Depth && ($.autoBindSampler && (tt = SamplerBindingType.NonFiltering),
                    et = TextureSampleType.UnfilterableFloat),
                    k.texture.sampleType = et,
                    _e) {
                        var rt = o.bindGroupLayoutEntryInfo[_e.binding.groupIndex][_e.binding.bindingIndex].index;
                        s[_e.binding.groupIndex][rt].sampler.type = tt
                    }
                    c = c << 1
                }
            }
        for (var it = [], d = 0; d < s.length; ++d)
            it[d] = this._device.createBindGroupLayout({
                entries: s[d]
            });
        return e.bindGroupLayouts = it,
        this._device.createPipelineLayout({
            bindGroupLayouts: it
        })
    }
    ,
    a.prototype._getVertexInputDescriptor = function(e, i) {
        for (var o, s, c = [], d = e._pipelineContext, _ = d.shaderProcessingContext.attributeNamesFromEffect, b = d.shaderProcessingContext.attributeLocationsFromEffect, k, j, $ = 0; $ < _.length; $++) {
            var _e = b[$]
              , et = (o = this._overrideVertexBuffers && this._overrideVertexBuffers[_[$]]) !== null && o !== void 0 ? o : this._vertexBuffers[_[$]];
            et || (et = this._emptyVertexBuffer);
            var tt = (s = et.getBuffer()) === null || s === void 0 ? void 0 : s.underlyingResource
              , rt = et.byteOffset
              , it = !et._validOffsetRange;
            if (!(k && j && k === tt) || it) {
                var nt = {
                    arrayStride: et.byteStride,
                    stepMode: et.getIsInstanced() ? InputStepMode.Instance : InputStepMode.Vertex,
                    attributes: []
                };
                c.push(nt),
                j = nt.attributes,
                it && (rt = 0,
                tt = null)
            }
            j.push({
                shaderLocation: _e,
                offset: rt,
                format: a._GetVertexInputDescriptorFormat(et)
            }),
            k = tt
        }
        return c
    }
    ,
    a.prototype._createRenderPipeline = function(e, i, o) {
        var s = e._pipelineContext
          , c = this._getVertexInputDescriptor(e, i)
          , d = this._createPipelineLayout(s)
          , _ = []
          , b = this._getAphaBlendState()
          , k = this._getColorBlendState();
        if (this._mrtAttachments1 > 0)
            for (var j = 0; j < this._mrtFormats.length; ++j) {
                var $ = {
                    format: this._mrtFormats[j],
                    writeMask: this._writeMask
                };
                b && k && ($.blend = {
                    alpha: b,
                    color: k
                }),
                _.push($)
            }
        else {
            var $ = {
                format: this._webgpuColorFormat[0],
                writeMask: this._writeMask
            };
            b && k && ($.blend = {
                alpha: b,
                color: k
            }),
            _.push($)
        }
        var _e = {
            compare: a._GetCompareFunction(this._stencilEnabled ? this._stencilFrontCompare : 7),
            depthFailOp: a._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontDepthFailOp : 1),
            failOp: a._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontFailOp : 1),
            passOp: a._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontPassOp : 1)
        }
          , et = void 0;
        return (i === PrimitiveTopology.LineStrip || i === PrimitiveTopology.TriangleStrip) && (et = !this._indexBuffer || this._indexBuffer.is32Bits ? IndexFormat.Uint32 : IndexFormat.Uint16),
        this._device.createRenderPipeline({
            layout: d,
            vertex: {
                module: s.stages.vertexStage.module,
                entryPoint: s.stages.vertexStage.entryPoint,
                buffers: c
            },
            primitive: {
                topology: i,
                stripIndexFormat: et,
                frontFace: this._frontFace === 1 ? FrontFace.CCW : FrontFace.CW,
                cullMode: this._cullEnabled ? this._cullFace === 2 ? CullMode.Front : CullMode.Back : CullMode.None
            },
            fragment: s.stages.fragmentStage ? {
                module: s.stages.fragmentStage.module,
                entryPoint: s.stages.fragmentStage.entryPoint,
                targets: _
            } : void 0,
            multisample: {
                count: o
            },
            depthStencil: this._webgpuDepthStencilFormat === void 0 ? void 0 : {
                depthWriteEnabled: this._depthWriteEnabled,
                depthCompare: this._depthTestEnabled ? a._GetCompareFunction(this._depthCompare) : CompareFunction.Always,
                format: this._webgpuDepthStencilFormat,
                stencilFront: _e,
                stencilBack: _e,
                stencilReadMask: this._stencilReadMask,
                stencilWriteMask: this._stencilWriteMask,
                depthBias: this._depthBias,
                depthBiasClamp: this._depthBiasClamp,
                depthBiasSlopeScale: this._depthBiasSlopeScale
            }
        })
    }
    ,
    a.NumCacheHitWithoutHash = 0,
    a.NumCacheHitWithHash = 0,
    a.NumCacheMiss = 0,
    a.NumPipelineCreationLastFrame = 0,
    a._NumPipelineCreationCurrentFrame = 0,
    a
}()
  , NodeState = function() {
    function a() {
        this.values = {}
    }
    return a.prototype.count = function() {
        var e = 0
          , i = this.pipeline ? 1 : 0;
        for (var o in this.values) {
            var s = this.values[o]
              , c = s.count()
              , d = c[0]
              , _ = c[1];
            e += d,
            i += _,
            e++
        }
        return [e, i]
    }
    ,
    a
}()
  , WebGPUCacheRenderPipelineTree = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, o, s) || this;
        return c._nodeStack = [],
        c._nodeStack[0] = e._Cache,
        c
    }
    return e.GetNodeCounts = function() {
        var i = e._Cache.count();
        return {
            nodeCount: i[0],
            pipelineCount: i[1]
        }
    }
    ,
    e._GetPipelines = function(i, o, s, c) {
        if (i.pipeline) {
            var d = s.slice();
            d.length = c,
            o.push(d)
        }
        for (var _ in i.values) {
            var b = i.values[_];
            s[c] = parseInt(_),
            e._GetPipelines(b, o, s, c + 1)
        }
    }
    ,
    e.GetPipelines = function() {
        var i = [];
        return e._GetPipelines(e._Cache, i, [], 0),
        i
    }
    ,
    e.prototype._getRenderPipeline = function(i) {
        for (var o = this._nodeStack[this._stateDirtyLowestIndex], s = this._stateDirtyLowestIndex; s < this._statesLength; ++s) {
            var c = o.values[this._states[s]];
            c || (c = new NodeState,
            o.values[this._states[s]] = c),
            o = c,
            this._nodeStack[s + 1] = o
        }
        i.token = o,
        i.pipeline = o.pipeline
    }
    ,
    e.prototype._setRenderPipeline = function(i) {
        i.token.pipeline = i.pipeline
    }
    ,
    e._Cache = new NodeState,
    e
}(WebGPUCacheRenderPipeline)
  , WebGPUStencilStateComposer = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, !1) || this;
        return o._cache = i,
        o.reset(),
        o
    }
    return Object.defineProperty(e.prototype, "func", {
        get: function() {
            return this._func
        },
        set: function(i) {
            this._func !== i && (this._func = i,
            this._cache.setStencilCompare(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "funcMask", {
        get: function() {
            return this._funcMask
        },
        set: function(i) {
            this._funcMask !== i && (this._funcMask = i,
            this._cache.setStencilReadMask(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "opStencilFail", {
        get: function() {
            return this._opStencilFail
        },
        set: function(i) {
            this._opStencilFail !== i && (this._opStencilFail = i,
            this._cache.setStencilFailOp(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "opDepthFail", {
        get: function() {
            return this._opDepthFail
        },
        set: function(i) {
            this._opDepthFail !== i && (this._opDepthFail = i,
            this._cache.setStencilDepthFailOp(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "opStencilDepthPass", {
        get: function() {
            return this._opStencilDepthPass
        },
        set: function(i) {
            this._opStencilDepthPass !== i && (this._opStencilDepthPass = i,
            this._cache.setStencilPassOp(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "mask", {
        get: function() {
            return this._mask
        },
        set: function(i) {
            this._mask !== i && (this._mask = i,
            this._cache.setStencilWriteMask(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "enabled", {
        get: function() {
            return this._enabled
        },
        set: function(i) {
            this._enabled !== i && (this._enabled = i,
            this._cache.setStencilEnabled(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.reset = function() {
        a.prototype.reset.call(this),
        this._cache.resetStencilState()
    }
    ,
    e.prototype.apply = function(i) {
        var o, s = (o = this.stencilMaterial) === null || o === void 0 ? void 0 : o.enabled;
        this.enabled = s ? this.stencilMaterial.enabled : this.stencilGlobal.enabled,
        this.enabled && (this.func = s ? this.stencilMaterial.func : this.stencilGlobal.func,
        this.funcRef = s ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef,
        this.funcMask = s ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask,
        this.opStencilFail = s ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail,
        this.opDepthFail = s ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail,
        this.opStencilDepthPass = s ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass,
        this.mask = s ? this.stencilMaterial.mask : this.stencilGlobal.mask)
    }
    ,
    e
}(StencilStateComposer)
  , WebGPUDepthCullingState = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, !1) || this;
        return o._cache = i,
        o.reset(),
        o
    }
    return Object.defineProperty(e.prototype, "zOffset", {
        get: function() {
            return this._zOffset
        },
        set: function(i) {
            this._zOffset !== i && (this._zOffset = i,
            this._isZOffsetDirty = !0,
            this._cache.setDepthBiasSlopeScale(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "zOffsetUnits", {
        get: function() {
            return this._zOffsetUnits
        },
        set: function(i) {
            this._zOffsetUnits !== i && (this._zOffsetUnits = i,
            this._isZOffsetDirty = !0,
            this._cache.setDepthBias(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cullFace", {
        get: function() {
            return this._cullFace
        },
        set: function(i) {
            this._cullFace !== i && (this._cullFace = i,
            this._isCullFaceDirty = !0,
            this._cache.setCullFace(i != null ? i : 1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cull", {
        get: function() {
            return this._cull
        },
        set: function(i) {
            this._cull !== i && (this._cull = i,
            this._isCullDirty = !0,
            this._cache.setCullEnabled(!!i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthFunc", {
        get: function() {
            return this._depthFunc
        },
        set: function(i) {
            this._depthFunc !== i && (this._depthFunc = i,
            this._isDepthFuncDirty = !0,
            this._cache.setDepthCompare(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthMask", {
        get: function() {
            return this._depthMask
        },
        set: function(i) {
            this._depthMask !== i && (this._depthMask = i,
            this._isDepthMaskDirty = !0,
            this._cache.setDepthWriteEnabled(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthTest", {
        get: function() {
            return this._depthTest
        },
        set: function(i) {
            this._depthTest !== i && (this._depthTest = i,
            this._isDepthTestDirty = !0,
            this._cache.setDepthTestEnabled(i))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "frontFace", {
        get: function() {
            return this._frontFace
        },
        set: function(i) {
            this._frontFace !== i && (this._frontFace = i,
            this._isFrontFaceDirty = !0,
            this._cache.setFrontFace(i != null ? i : 2))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.reset = function() {
        a.prototype.reset.call(this),
        this._cache.resetDepthCullingState()
    }
    ,
    e.prototype.apply = function(i) {}
    ,
    e
}(DepthCullingState)
  , ExternalTexture = function() {
    function a(e) {
        this.useMipMaps = !1,
        this.type = 16,
        this._video = e,
        this.uniqueId = InternalTexture._Counter++
    }
    return a.IsExternalTexture = function(e) {
        return e.underlyingResource !== void 0
    }
    ,
    a.prototype.getClassName = function() {
        return "ExternalTexture"
    }
    ,
    Object.defineProperty(a.prototype, "underlyingResource", {
        get: function() {
            return this._video
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.isReady = function() {
        return this._video.readyState >= this._video.HAVE_CURRENT_DATA
    }
    ,
    a.prototype.dispose = function() {}
    ,
    a
}()
  , WebGPUMaterialContext = function() {
    function a() {
        this.uniqueId = a._Counter++,
        this.updateId = 0,
        this.reset()
    }
    return Object.defineProperty(a.prototype, "forceBindGroupCreation", {
        get: function() {
            return this._numExternalTextures > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasFloatTextures", {
        get: function() {
            return this._numFloatTextures > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.reset = function() {
        this.samplers = {},
        this.textures = {},
        this.isDirty = !0,
        this._numFloatTextures = 0,
        this._numExternalTextures = 0
    }
    ,
    a.prototype.setSampler = function(e, i) {
        var o = this.samplers[e]
          , s = -1;
        o ? s = o.hashCode : this.samplers[e] = o = {
            sampler: i,
            hashCode: 0
        },
        o.sampler = i,
        o.hashCode = i ? WebGPUCacheSampler.GetSamplerHashCode(i) : 0;
        var c = s !== o.hashCode;
        c && this.updateId++,
        this.isDirty || (this.isDirty = c)
    }
    ,
    a.prototype.setTexture = function(e, i) {
        var o, s, c, d = this.textures[e], _ = -1;
        d ? _ = (s = (o = d.texture) === null || o === void 0 ? void 0 : o.uniqueId) !== null && s !== void 0 ? s : -1 : this.textures[e] = d = {
            texture: i,
            isFloatTexture: !1,
            isExternalTexture: !1
        },
        d.isExternalTexture && this._numExternalTextures--,
        d.isFloatTexture && this._numFloatTextures--,
        i ? (d.isFloatTexture = i.type === 1,
        d.isExternalTexture = ExternalTexture.IsExternalTexture(i),
        d.isFloatTexture && this._numFloatTextures++,
        d.isExternalTexture && this._numExternalTextures++) : (d.isFloatTexture = !1,
        d.isExternalTexture = !1),
        d.texture = i;
        var b = _ !== ((c = i == null ? void 0 : i.uniqueId) !== null && c !== void 0 ? c : -1);
        b && this.updateId++,
        this.isDirty || (this.isDirty = b)
    }
    ,
    a._Counter = 0,
    a
}()
  , WebGPUDrawContext = function() {
    function a(e) {
        this._bufferManager = e,
        this.uniqueId = a._Counter++,
        this._useInstancing = !1,
        this._currentInstanceCount = 0,
        this.reset()
    }
    return a.prototype.isDirty = function(e) {
        return this._isDirty || this.materialContextUpdateId !== e
    }
    ,
    a.prototype.resetIsDirty = function(e) {
        this._isDirty = !1,
        this.materialContextUpdateId = e
    }
    ,
    Object.defineProperty(a.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
    }),
    a.prototype.reset = function() {
        this.buffers = {},
        this._isDirty = !0,
        this.materialContextUpdateId = 0,
        this.fastBundle = void 0,
        this.bindGroups = void 0
    }
    ,
    a.prototype.setBuffer = function(e, i) {
        var o;
        this._isDirty || (this._isDirty = (i == null ? void 0 : i.uniqueId) !== ((o = this.buffers[e]) === null || o === void 0 ? void 0 : o.uniqueId)),
        this.buffers[e] = i
    }
    ,
    a.prototype.setIndirectData = function(e, i, o) {
        i === this._currentInstanceCount || !this.indirectDrawBuffer || !this._indirectDrawData || (this._currentInstanceCount = i,
        this._indirectDrawData[0] = e,
        this._indirectDrawData[1] = i,
        this._indirectDrawData[2] = o,
        this._bufferManager.setRawData(this.indirectDrawBuffer, 0, this._indirectDrawData, 0, 20))
    }
    ,
    a.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
    }
    ,
    a._Counter = 0,
    a
}()
  , WebGPUBindGroupCacheNode = function() {
    function a() {
        this.values = {}
    }
    return a
}()
  , WebGPUCacheBindGroups = function() {
    function a(e, i, o) {
        this.disabled = !1,
        this._device = e,
        this._cacheSampler = i,
        this._engine = o
    }
    return Object.defineProperty(a, "Statistics", {
        get: function() {
            return {
                totalCreated: a.NumBindGroupsCreatedTotal,
                lastFrameCreated: a.NumBindGroupsCreatedLastFrame,
                lookupLastFrame: a.NumBindGroupsLookupLastFrame,
                noLookupLastFrame: a.NumBindGroupsNoLookupLastFrame
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.endFrame = function() {
        a.NumBindGroupsCreatedLastFrame = a._NumBindGroupsCreatedCurrentFrame,
        a.NumBindGroupsLookupLastFrame = a._NumBindGroupsLookupCurrentFrame,
        a.NumBindGroupsNoLookupLastFrame = a._NumBindGroupsNoLookupCurrentFrame,
        a._NumBindGroupsCreatedCurrentFrame = 0,
        a._NumBindGroupsLookupCurrentFrame = 0,
        a._NumBindGroupsNoLookupCurrentFrame = 0
    }
    ,
    a.prototype.getBindGroups = function(e, i, o) {
        var s, c, d, _, b, k, j, $, _e, et, tt = void 0, rt = a._Cache, it = this.disabled || o.forceBindGroupCreation;
        if (!it) {
            if (!i.isDirty(o.updateId) && !o.isDirty)
                return a._NumBindGroupsNoLookupCurrentFrame++,
                i.bindGroups;
            for (var nt = 0, ot = e.shaderProcessingContext.bufferNames; nt < ot.length; nt++) {
                var at = ot[nt]
                  , st = (c = (s = i.buffers[at]) === null || s === void 0 ? void 0 : s.uniqueId) !== null && c !== void 0 ? c : 0
                  , ut = rt.values[st];
                ut || (ut = new WebGPUBindGroupCacheNode,
                rt.values[st] = ut),
                rt = ut
            }
            for (var ct = 0, lt = e.shaderProcessingContext.samplerNames; ct < lt.length; ct++) {
                var ft = lt[ct]
                  , ht = (_ = (d = o.samplers[ft]) === null || d === void 0 ? void 0 : d.hashCode) !== null && _ !== void 0 ? _ : 0
                  , ut = rt.values[ht];
                ut || (ut = new WebGPUBindGroupCacheNode,
                rt.values[ht] = ut),
                rt = ut
            }
            for (var pt = 0, dt = e.shaderProcessingContext.textureNames; pt < dt.length; pt++) {
                var _t = dt[pt]
                  , mt = (j = (k = (b = o.textures[_t]) === null || b === void 0 ? void 0 : b.texture) === null || k === void 0 ? void 0 : k.uniqueId) !== null && j !== void 0 ? j : 0
                  , ut = rt.values[mt];
                ut || (ut = new WebGPUBindGroupCacheNode,
                rt.values[mt] = ut),
                rt = ut
            }
            tt = rt.bindGroups
        }
        if (i.resetIsDirty(o.updateId),
        o.isDirty = !1,
        tt)
            return i.bindGroups = tt,
            a._NumBindGroupsLookupCurrentFrame++,
            tt;
        tt = [],
        i.bindGroups = tt,
        it || (rt.bindGroups = tt),
        a.NumBindGroupsCreatedTotal++,
        a._NumBindGroupsCreatedCurrentFrame++;
        for (var vt = e.bindGroupLayouts, yt = 0; yt < e.shaderProcessingContext.bindGroupLayoutEntries.length; yt++) {
            for (var Et = e.shaderProcessingContext.bindGroupLayoutEntries[yt], At = e.shaderProcessingContext.bindGroupEntries[yt], gt = 0; gt < Et.length; gt++) {
                var St = e.shaderProcessingContext.bindGroupLayoutEntries[yt][gt]
                  , xt = e.shaderProcessingContext.bindGroupLayoutEntryInfo[yt][St.binding]
                  , bt = ($ = xt.nameInArrayOfTexture) !== null && $ !== void 0 ? $ : xt.name;
                if (St.sampler) {
                    var Rt = o.samplers[bt];
                    if (Rt) {
                        var Mt = Rt.sampler;
                        if (!Mt) {
                            this._engine.dbgSanityChecks && Logger$2.Error("Trying to bind a null sampler! entry=" + JSON.stringify(St) + ", name=" + bt + ", bindingInfo=" + JSON.stringify(Rt, function(wt, Nt) {
                                return wt === "texture" ? "<no dump>" : Nt
                            }) + ", materialContext.uniqueId=" + o.uniqueId, 50);
                            continue
                        }
                        At[gt].resource = this._cacheSampler.getSampler(Mt, !1, Rt.hashCode)
                    } else
                        Logger$2.Error('Sampler "' + bt + '" could not be bound. entry=' + JSON.stringify(St) + ", materialContext=" + JSON.stringify(o, function(wt, Nt) {
                            return wt === "texture" || wt === "sampler" ? "<no dump>" : Nt
                        }), 50)
                } else if (St.texture || St.storageTexture) {
                    var Rt = o.textures[bt];
                    if (Rt) {
                        if (this._engine.dbgSanityChecks && Rt.texture === null) {
                            Logger$2.Error("Trying to bind a null texture! entry=" + JSON.stringify(St) + ", bindingInfo=" + JSON.stringify(Rt, function(Nt, Ft) {
                                return Nt === "texture" ? "<no dump>" : Ft
                            }) + ", materialContext.uniqueId=" + o.uniqueId, 50);
                            continue
                        }
                        var Pt = Rt.texture._hardwareTexture;
                        if (this._engine.dbgSanityChecks && (!Pt || !Pt.view)) {
                            Logger$2.Error("Trying to bind a null gpu texture! entry=" + JSON.stringify(St) + ", name=" + bt + ", bindingInfo=" + JSON.stringify(Rt, function(Nt, Ft) {
                                return Nt === "texture" ? "<no dump>" : Ft
                            }) + ", isReady=" + ((_e = Rt.texture) === null || _e === void 0 ? void 0 : _e.isReady) + ", materialContext.uniqueId=" + o.uniqueId, 50);
                            continue
                        }
                        At[gt].resource = Pt.view
                    } else
                        Logger$2.Error('Texture "' + bt + '" could not be bound. entry=' + JSON.stringify(St) + ", materialContext=" + JSON.stringify(o, function(Nt, Ft) {
                            return Nt === "texture" || Nt === "sampler" ? "<no dump>" : Ft
                        }), 50)
                } else if (St.externalTexture) {
                    var Rt = o.textures[bt];
                    if (Rt) {
                        if (this._engine.dbgSanityChecks && Rt.texture === null) {
                            Logger$2.Error("Trying to bind a null external texture! entry=" + JSON.stringify(St) + ", name=" + bt + ", bindingInfo=" + JSON.stringify(Rt, function(Nt, Ft) {
                                return Nt === "texture" ? "<no dump>" : Ft
                            }) + ", materialContext.uniqueId=" + o.uniqueId, 50);
                            continue
                        }
                        var It = Rt.texture.underlyingResource;
                        if (this._engine.dbgSanityChecks && !It) {
                            Logger$2.Error("Trying to bind a null gpu external texture! entry=" + JSON.stringify(St) + ", name=" + bt + ", bindingInfo=" + JSON.stringify(Rt, function(Nt, Ft) {
                                return Nt === "texture" ? "<no dump>" : Ft
                            }) + ", isReady=" + ((et = Rt.texture) === null || et === void 0 ? void 0 : et.isReady) + ", materialContext.uniqueId=" + o.uniqueId, 50);
                            continue
                        }
                        At[gt].resource = this._device.importExternalTexture({
                            source: It
                        })
                    } else
                        Logger$2.Error('Texture "' + bt + '" could not be bound. entry=' + JSON.stringify(St) + ", materialContext=" + JSON.stringify(o, function(Nt, Ft) {
                            return Nt === "texture" || Nt === "sampler" ? "<no dump>" : Ft
                        }), 50)
                } else if (St.buffer) {
                    var Dt = i.buffers[bt];
                    if (Dt) {
                        var Ct = Dt.underlyingResource;
                        At[gt].resource.buffer = Ct,
                        At[gt].resource.size = Dt.capacity
                    } else
                        Logger$2.Error(`Can't find buffer "` + bt + '". entry=' + JSON.stringify(St) + ", buffers=" + JSON.stringify(i.buffers) + ", drawContext.uniqueId=" + i.uniqueId, 50)
                }
            }
            var Ot = vt[yt];
            tt[yt] = this._device.createBindGroup({
                layout: Ot,
                entries: At
            })
        }
        return tt
    }
    ,
    a.NumBindGroupsCreatedTotal = 0,
    a.NumBindGroupsCreatedLastFrame = 0,
    a.NumBindGroupsLookupLastFrame = 0,
    a.NumBindGroupsNoLookupLastFrame = 0,
    a._Cache = new WebGPUBindGroupCacheNode,
    a._NumBindGroupsCreatedCurrentFrame = 0,
    a._NumBindGroupsLookupCurrentFrame = 0,
    a._NumBindGroupsNoLookupCurrentFrame = 0,
    a
}()
  , name$2F = "clearQuadVertexShader"
  , shader$2F = `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$2F] = shader$2F;
var name$2E = "clearQuadPixelShader"
  , shader$2E = `uniform vec4 color;
void main() {
gl_FragColor=color;
}
`;
ShaderStore.ShadersStore[name$2E] = shader$2E;
var WebGPUClearQuad = function() {
    function a(e, i, o) {
        this._bindGroups = {},
        this._bundleCache = {},
        this._device = e,
        this._engine = i,
        this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device,o,!i._caps.textureFloatLinearFiltering),
        this._cacheRenderPipeline.setDepthTestEnabled(!1),
        this._cacheRenderPipeline.setStencilReadMask(255),
        this._effect = i.createEffect("clearQuad", [], ["color", "depthValue"])
    }
    return a.prototype.setDepthStencilFormat = function(e) {
        this._depthTextureFormat = e,
        this._cacheRenderPipeline.setDepthStencilFormat(e)
    }
    ,
    a.prototype.setColorFormat = function(e) {
        this._cacheRenderPipeline.setColorFormat(e)
    }
    ,
    a.prototype.setMRTAttachments = function(e, i) {
        this._cacheRenderPipeline.setMRTAttachments(e, i)
    }
    ,
    a.prototype.clear = function(e, i, o, s, c) {
        var d, _;
        c === void 0 && (c = 1);
        var b, k = null, j = 0;
        if (e)
            b = e;
        else {
            if (j = (i ? i.r + i.g * 256 + i.b * 256 * 256 + i.a * 256 * 256 * 256 : 0) + (o ? Math.pow(2, 32) : 0) + (s ? Math.pow(2, 33) : 0) + (this._engine.useReverseDepthBuffer ? Math.pow(2, 34) : 0) + c * Math.pow(2, 35),
            k = this._bundleCache[j],
            k)
                return k;
            b = this._device.createRenderBundleEncoder({
                colorFormats: this._cacheRenderPipeline.colorFormats,
                depthStencilFormat: this._depthTextureFormat,
                sampleCount: c
            })
        }
        this._cacheRenderPipeline.setDepthWriteEnabled(!!o),
        this._cacheRenderPipeline.setStencilEnabled(!!s),
        this._cacheRenderPipeline.setStencilWriteMask(s ? 255 : 0),
        this._cacheRenderPipeline.setStencilCompare(s ? 519 : 512),
        this._cacheRenderPipeline.setStencilPassOp(s ? 7681 : 7680),
        this._cacheRenderPipeline.setWriteMask(i ? 15 : 0);
        var $ = this._cacheRenderPipeline.getRenderPipeline(7, this._effect, c)
          , _e = this._effect._pipelineContext;
        i && this._effect.setDirectColor4("color", i),
        this._effect.setFloat("depthValue", this._engine.useReverseDepthBuffer ? this._engine._clearReverseDepthValue : this._engine._clearDepthValue),
        (d = _e.uniformBuffer) === null || d === void 0 || d.update();
        var et = (_ = _e.uniformBuffer) === null || _ === void 0 ? void 0 : _.getBuffer()
          , tt = this._bindGroups[et.uniqueId];
        if (!tt) {
            var rt = _e.bindGroupLayouts;
            tt = this._bindGroups[et.uniqueId] = [],
            tt.push(this._device.createBindGroup({
                layout: rt[0],
                entries: []
            })),
            WebGPUShaderProcessingContext._SimplifiedKnownBindings || tt.push(this._device.createBindGroup({
                layout: rt[1],
                entries: []
            })),
            tt.push(this._device.createBindGroup({
                layout: rt[WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2],
                entries: [{
                    binding: 0,
                    resource: {
                        buffer: et.underlyingResource,
                        size: et.capacity
                    }
                }]
            }))
        }
        b.setPipeline($);
        for (var it = 0; it < tt.length; ++it)
            b.setBindGroup(it, tt[it]);
        return b.draw(4, 1, 0, 0),
        e || (k = b.finish(),
        this._bundleCache[j] = k),
        k
    }
    ,
    a
}()
  , WebGPURenderItemViewport = function() {
    function a(e, i, o, s) {
        this.x = Math.floor(e),
        this.y = Math.floor(i),
        this.w = Math.floor(o),
        this.h = Math.floor(s)
    }
    return a.prototype.run = function(e) {
        e.setViewport(this.x, this.y, this.w, this.h, 0, 1)
    }
    ,
    a.prototype.clone = function() {
        return new a(this.x,this.y,this.w,this.h)
    }
    ,
    a
}()
  , WebGPURenderItemScissor = function() {
    function a(e, i, o, s) {
        this.x = e,
        this.y = i,
        this.w = o,
        this.h = s
    }
    return a.prototype.run = function(e) {
        e.setScissorRect(this.x, this.y, this.w, this.h)
    }
    ,
    a.prototype.clone = function() {
        return new a(this.x,this.y,this.w,this.h)
    }
    ,
    a
}()
  , WebGPURenderItemStencilRef = function() {
    function a(e) {
        this.ref = e
    }
    return a.prototype.run = function(e) {
        e.setStencilReference(this.ref)
    }
    ,
    a.prototype.clone = function() {
        return new a(this.ref)
    }
    ,
    a
}()
  , WebGPURenderItemBlendColor = function() {
    function a(e) {
        this.color = e
    }
    return a.prototype.run = function(e) {
        e.setBlendConstant(this.color)
    }
    ,
    a.prototype.clone = function() {
        return new a(this.color)
    }
    ,
    a
}()
  , WebGPURenderItemBeginOcclusionQuery = function() {
    function a(e) {
        this.query = e
    }
    return a.prototype.run = function(e) {
        e.beginOcclusionQuery(this.query)
    }
    ,
    a.prototype.clone = function() {
        return new a(this.query)
    }
    ,
    a
}()
  , WebGPURenderItemEndOcclusionQuery = function() {
    function a() {}
    return a.prototype.run = function(e) {
        e.endOcclusionQuery()
    }
    ,
    a.prototype.clone = function() {
        return new a
    }
    ,
    a
}()
  , WebGPURenderItemBundles = function() {
    function a() {
        this.bundles = []
    }
    return a.prototype.run = function(e) {
        e.executeBundles(this.bundles)
    }
    ,
    a.prototype.clone = function() {
        var e = new a;
        return e.bundles = this.bundles,
        e
    }
    ,
    a
}()
  , WebGPUBundleList = function() {
    function a(e) {
        this.numDrawCalls = 0,
        this._device = e,
        this._list = new Array(10),
        this._listLength = 0
    }
    return a.prototype.addBundle = function(e) {
        if (!this._currentItemIsBundle) {
            var i = new WebGPURenderItemBundles;
            this._list[this._listLength++] = i,
            this._currentBundleList = i.bundles,
            this._currentItemIsBundle = !0
        }
        e && this._currentBundleList.push(e)
    }
    ,
    a.prototype._finishBundle = function() {
        this._currentItemIsBundle && this._bundleEncoder && (this._currentBundleList.push(this._bundleEncoder.finish()),
        this._bundleEncoder = void 0,
        this._currentItemIsBundle = !1)
    }
    ,
    a.prototype.addItem = function(e) {
        this._finishBundle(),
        this._list[this._listLength++] = e,
        this._currentItemIsBundle = !1
    }
    ,
    a.prototype.getBundleEncoder = function(e, i, o) {
        return this._currentItemIsBundle || (this.addBundle(),
        this._bundleEncoder = this._device.createRenderBundleEncoder({
            colorFormats: e,
            depthStencilFormat: i,
            sampleCount: o
        })),
        this._bundleEncoder
    }
    ,
    a.prototype.close = function() {
        this._finishBundle()
    }
    ,
    a.prototype.run = function(e) {
        this.close();
        for (var i = 0; i < this._listLength; ++i)
            this._list[i].run(e)
    }
    ,
    a.prototype.reset = function() {
        this._listLength = 0,
        this._currentItemIsBundle = !1,
        this.numDrawCalls = 0
    }
    ,
    a.prototype.clone = function() {
        this.close();
        var e = new a(this._device);
        e._list = new Array(this._listLength),
        e._listLength = this._listLength,
        e.numDrawCalls = this.numDrawCalls;
        for (var i = 0; i < this._listLength; ++i)
            e._list[i] = this._list[i].clone();
        return e
    }
    ,
    a
}()
  , WebGPUQuerySet = function() {
    function a(e, i, o, s, c) {
        c === void 0 && (c = !0),
        this._dstBuffers = [],
        this._device = o,
        this._bufferManager = s,
        this._count = e,
        this._canUseMultipleBuffers = c,
        this._querySet = o.createQuerySet({
            type: i,
            count: e
        }),
        this._queryBuffer = s.createRawBuffer(8 * e, BufferUsage.QueryResolve | BufferUsage.CopySrc),
        c || this._dstBuffers.push(this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst))
    }
    return Object.defineProperty(a.prototype, "querySet", {
        get: function() {
            return this._querySet
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._getBuffer = function(e, i) {
        if (!this._canUseMultipleBuffers && this._dstBuffers.length === 0)
            return null;
        var o = this._device.createCommandEncoder(), s;
        return this._dstBuffers.length === 0 ? s = this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst) : (s = this._dstBuffers[this._dstBuffers.length - 1],
        this._dstBuffers.length--),
        o.resolveQuerySet(this._querySet, e, i, this._queryBuffer, 0),
        o.copyBufferToBuffer(this._queryBuffer, 0, s, 0, 8 * i),
        this._device.queue.submit([o.finish()]),
        s
    }
    ,
    a.prototype.readValues = function(e, i) {
        return e === void 0 && (e = 0),
        i === void 0 && (i = 1),
        __awaiter(this, void 0, void 0, function() {
            var o, s;
            return __generator(this, function(c) {
                switch (c.label) {
                case 0:
                    return o = this._getBuffer(e, i),
                    o === null ? [2, null] : [4, o.mapAsync(MapMode.Read)];
                case 1:
                    return c.sent(),
                    s = new BigUint64Array(o.getMappedRange()).slice(),
                    o.unmap(),
                    this._dstBuffers[this._dstBuffers.length] = o,
                    [2, s]
                }
            })
        })
    }
    ,
    a.prototype.readValue = function(e) {
        return e === void 0 && (e = 0),
        __awaiter(this, void 0, void 0, function() {
            var i, o, s;
            return __generator(this, function(c) {
                switch (c.label) {
                case 0:
                    return i = this._getBuffer(e, 1),
                    i === null ? [2, null] : [4, i.mapAsync(MapMode.Read)];
                case 1:
                    return c.sent(),
                    o = new BigUint64Array(i.getMappedRange()),
                    s = Number(o[0]),
                    i.unmap(),
                    this._dstBuffers[this._dstBuffers.length] = i,
                    [2, s]
                }
            })
        })
    }
    ,
    a.prototype.readTwoValuesAndSubtract = function(e) {
        return e === void 0 && (e = 0),
        __awaiter(this, void 0, void 0, function() {
            var i, o, s;
            return __generator(this, function(c) {
                switch (c.label) {
                case 0:
                    return i = this._getBuffer(e, 2),
                    i === null ? [2, null] : [4, i.mapAsync(MapMode.Read)];
                case 1:
                    return c.sent(),
                    o = new BigUint64Array(i.getMappedRange()),
                    s = Number(o[1] - o[0]),
                    i.unmap(),
                    this._dstBuffers[this._dstBuffers.length] = i,
                    [2, s]
                }
            })
        })
    }
    ,
    a.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])
    }
    ,
    a
}()
  , WebGPUTimestampQuery = function() {
    function a(e, i) {
        this._enabled = !1,
        this._gpuFrameTimeCounter = new PerfCounter,
        this._measureDurationState = 0,
        this._device = e,
        this._bufferManager = i
    }
    return Object.defineProperty(a.prototype, "gpuFrameTimeCounter", {
        get: function() {
            return this._gpuFrameTimeCounter
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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
    }),
    a.prototype.startFrame = function(e) {
        this._enabled && this._measureDurationState === 0 && (this._measureDuration.start(e),
        this._measureDurationState = 1)
    }
    ,
    a.prototype.endFrame = function(e) {
        var i = this;
        this._measureDurationState === 1 && (this._measureDurationState = 2,
        this._measureDuration.stop(e).then(function(o) {
            o !== null && o >= 0 && (i._gpuFrameTimeCounter.fetchNewFrame(),
            i._gpuFrameTimeCounter.addCount(o, !0)),
            i._measureDurationState = 0
        }))
    }
    ,
    a
}()
  , WebGPUDurationMeasure = function() {
    function a(e, i) {
        this._querySet = new WebGPUQuerySet(2,QueryType.Timestamp,e,i)
    }
    return a.prototype.start = function(e) {
        e.writeTimestamp(this._querySet.querySet, 0)
    }
    ,
    a.prototype.stop = function(e) {
        return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(i) {
                return e.writeTimestamp(this._querySet.querySet, 1),
                [2, this._querySet.readTwoValuesAndSubtract(0)]
            })
        })
    }
    ,
    a.prototype.dispose = function() {
        this._querySet.dispose()
    }
    ,
    a
}()
  , WebGPUOcclusionQuery = function() {
    function a(e, i, o, s, c) {
        s === void 0 && (s = 50),
        c === void 0 && (c = 100),
        this._availableIndices = [],
        this._engine = e,
        this._device = i,
        this._bufferManager = o,
        this._frameLastBuffer = -1,
        this._currentTotalIndices = 0,
        this._countIncrement = c,
        this._allocateNewIndices(s)
    }
    return Object.defineProperty(a.prototype, "querySet", {
        get: function() {
            return this._querySet.querySet
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasQueries", {
        get: function() {
            return this._currentTotalIndices !== this._availableIndices.length
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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
    }),
    a.prototype.createQuery = function() {
        this._availableIndices.length === 0 && this._allocateNewIndices();
        var e = this._availableIndices[this._availableIndices.length - 1];
        return this._availableIndices.length--,
        e
    }
    ,
    a.prototype.deleteQuery = function(e) {
        this._availableIndices[this._availableIndices.length - 1] = e
    }
    ,
    a.prototype.isQueryResultAvailable = function(e) {
        return this._retrieveQueryBuffer(),
        !!this._lastBuffer && e < this._lastBuffer.length
    }
    ,
    a.prototype.getQueryResult = function(e) {
        var i, o;
        return Number((o = (i = this._lastBuffer) === null || i === void 0 ? void 0 : i[e]) !== null && o !== void 0 ? o : -1)
    }
    ,
    a.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(i) {
            e._lastBuffer = i
        }))
    }
    ,
    a.prototype._allocateNewIndices = function(e) {
        e = e != null ? e : this._countIncrement,
        this._delayQuerySetDispose();
        for (var i = 0; i < e; ++i)
            this._availableIndices.push(this._currentTotalIndices + i);
        this._currentTotalIndices += e,
        this._querySet = new WebGPUQuerySet(this._currentTotalIndices,QueryType.Occlusion,this._device,this._bufferManager,!1)
    }
    ,
    a.prototype._delayQuerySetDispose = function() {
        var e = this._querySet;
        e && setTimeout(function() {
            return e.dispose
        }, 1e3)
    }
    ,
    a.prototype.dispose = function() {
        var e;
        (e = this._querySet) === null || e === void 0 || e.dispose(),
        this._availableIndices = []
    }
    ,
    a
}()
  , WebGPUTintWASM = function() {
    function a() {
        this._twgsl = null
    }
    return a.prototype.initTwgsl = function(e) {
        return __awaiter(this, void 0, void 0, function() {
            var i;
            return __generator(this, function(o) {
                switch (o.label) {
                case 0:
                    return e = e || {},
                    e = __assign(__assign({}, a._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 o.sent(),
                    [3, 3];
                case 2:
                    importScripts(e.jsPath),
                    o.label = 3;
                case 3:
                    return self.twgsl ? (i = this,
                    [4, self.twgsl(e.wasmPath)]) : [3, 5];
                case 4:
                    return i._twgsl = o.sent(),
                    [2, Promise.resolve()];
                case 5:
                    return [2, Promise.reject("twgsl is not available.")]
                }
            })
        })
    }
    ,
    a.prototype.convertSpirV2WGSL = function(e) {
        return this._twgsl.convertSpirV2WGSL(e)
    }
    ,
    a._twgslDefaultOptions = {
        jsPath: "https://preview.babylonjs.com/twgsl/twgsl.js",
        wasmPath: "https://preview.babylonjs.com/twgsl/twgsl.wasm"
    },
    a
}()
  , WebGPUSnapshotRendering = function() {
    function a(e, i, o, s) {
        this._record = !1,
        this._play = !1,
        this._mainPassBundleList = [],
        this._enabled = !1,
        this._engine = e,
        this._mode = i,
        this._bundleList = o,
        this._bundleListRenderTarget = s
    }
    return Object.defineProperty(a.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(a.prototype, "play", {
        get: function() {
            return this._play
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "record", {
        get: function() {
            return this._record
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "mode", {
        get: function() {
            return this._mode
        },
        set: function(e) {
            this._record ? this._modeSaved = e : this._mode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.endMainRenderPass = function() {
        this._record && this._mainPassBundleList.push(this._bundleList.clone())
    }
    ,
    a.prototype.endRenderTargetPass = function(e, i) {
        var o, s, c, d;
        if (this._play)
            (s = (o = i._bundleLists) === null || o === void 0 ? void 0 : o[i._currentLayer]) === null || s === void 0 || s.run(e),
            this._mode === 1 && this._engine._reportDrawCall((d = (c = i._bundleLists) === null || c === void 0 ? void 0 : c[i._currentLayer]) === null || d === void 0 ? void 0 : d.numDrawCalls);
        else if (this._record)
            i._bundleLists || (i._bundleLists = []),
            i._bundleLists[i._currentLayer] = this._bundleListRenderTarget.clone(),
            i._bundleLists[i._currentLayer].run(e),
            this._bundleListRenderTarget.reset();
        else
            return !1;
        return !0
    }
    ,
    a.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 i = 0; i < this._mainPassBundleList.length; ++i)
                this._mainPassBundleList[i].run(e),
                this._mode === 1 && this._engine._reportDrawCall(this._mainPassBundleList[i].numDrawCalls)
    }
    ,
    a.prototype.reset = function() {
        this.enabled = !1,
        this.enabled = !0
    }
    ,
    a
}()
  , WebGPUEngine = function(a) {
    __extends(e, a);
    function e(i, o) {
        o === void 0 && (o = {});
        var s, c, d, _, b = a.call(this, null) || this;
        if (b._uploadEncoderDescriptor = {
            label: "upload"
        },
        b._renderEncoderDescriptor = {
            label: "render"
        },
        b._renderTargetEncoderDescriptor = {
            label: "renderTarget"
        },
        b._clearDepthValue = 1,
        b._clearReverseDepthValue = 0,
        b._clearStencilValue = 0,
        b._defaultSampleCount = 4,
        b._glslang = null,
        b._tintWASM = null,
        b._compiledComputeEffects = {},
        b._counters = {
            numEnableEffects: 0,
            numEnableDrawWrapper: 0,
            numBundleCreationNonCompatMode: 0,
            numBundleReuseNonCompatMode: 0
        },
        b.countersLastFrame = {
            numEnableEffects: 0,
            numEnableDrawWrapper: 0,
            numBundleCreationNonCompatMode: 0,
            numBundleReuseNonCompatMode: 0
        },
        b.numMaxUncapturedErrors = 20,
        b._commandBuffers = [null, null, null],
        b._currentRenderPass = null,
        b._mainRenderPassWrapper = new WebGPURenderPassWrapper,
        b._mainRenderPassCopyWrapper = new WebGPURenderPassWrapper,
        b._rttRenderPassWrapper = new WebGPURenderPassWrapper,
        b._pendingDebugCommands = [],
        b._onAfterUnbindFrameBufferObservable = new Observable,
        b._currentOverrideVertexBuffers = null,
        b._currentIndexBuffer = null,
        b.__colorWrite = !0,
        b._forceEnableEffect = !1,
        b.dbgShowShaderCode = !1,
        b.dbgSanityChecks = !0,
        b.dbgVerboseLogsForFirstFrames = !1,
        b.dbgVerboseLogsNumFrames = 10,
        b.dbgLogIfNotDrawWrapper = !0,
        b.dbgShowEmptyEnableEffectCalls = !0,
        b._viewportsCurrent = [{
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }, {
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }],
        b._scissorsCurrent = [{
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }, {
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }],
        b._scissorCached = {
            x: 0,
            y: 0,
            z: 0,
            w: 0
        },
        b._stencilRefsCurrent = [-1, -1],
        b._blendColorsCurrent = [[null, null, null, null], [null, null, null, null]],
        b.isNDCHalfZRange = !0,
        b.hasOriginBottomLeft = !1,
        o.deviceDescriptor = o.deviceDescriptor || {},
        o.swapChainFormat = o.swapChainFormat || TextureFormat.BGRA8Unorm,
        o.antialiasing = o.antialiasing === void 0 ? !0 : o.antialiasing,
        o.stencil = (s = o.stencil) !== null && s !== void 0 ? s : !0,
        o.enableGPUDebugMarkers = (c = o.enableGPUDebugMarkers) !== null && c !== void 0 ? c : !1,
        Logger$2.Log("Babylon.js v" + Engine.Version + " - " + b.description + " engine"),
        !navigator.gpu)
            return Logger$2.Error("WebGPU is not supported by your browser."),
            b;
        b._isWebGPU = !0,
        b._shaderPlatformName = "WEBGPU",
        o.deterministicLockstep === void 0 && (o.deterministicLockstep = !1),
        o.lockstepMaxSteps === void 0 && (o.lockstepMaxSteps = 4),
        o.audioEngine === void 0 && (o.audioEngine = !0),
        b._deterministicLockstep = o.deterministicLockstep,
        b._lockstepMaxSteps = o.lockstepMaxSteps,
        b._timeStep = o.timeStep || 1 / 60,
        b._doNotHandleContextLost = !!o.doNotHandleContextLost,
        b._canvas = i,
        b._options = o,
        b.premultipliedAlpha = (d = o.premultipliedAlpha) !== null && d !== void 0 ? d : !0;
        var k = IsWindowObjectExist() && window.devicePixelRatio || 1
          , j = o.limitDeviceRatio || k
          , $ = (_ = o.adaptToDeviceRatio) !== null && _ !== void 0 ? _ : !1;
        return b._hardwareScalingLevel = $ ? 1 / Math.min(j, k) : 1,
        b._mainPassSampleCount = o.antialiasing ? b._defaultSampleCount : 1,
        b._isStencilEnable = o.stencil,
        b._sharedInit(i, !!o.doNotHandleTouchAction, o.audioEngine),
        b._shaderProcessor = new WebGPUShaderProcessorGLSL,
        b._shaderProcessorWGSL = new WebGPUShaderProcessorWGSL,
        b._invertYFinalFramebuffer = (!!b._options.forceCopyForInvertYFinalFramebuffer || !b._canvas.style) && !b._options.disableCopyForInvertYFinalFramebuffer,
        b._invertYFinalFramebuffer || b._canvas.style && (b._canvas.style.transform = "scaleY(-1)"),
        b
    }
    return Object.defineProperty(e.prototype, "snapshotRenderingMode", {
        get: function() {
            return this._snapshotRendering.mode
        },
        set: function(i) {
            this._snapshotRendering.mode = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.snapshotRenderingReset = function() {
        this._snapshotRendering.reset()
    }
    ,
    Object.defineProperty(e.prototype, "snapshotRendering", {
        get: function() {
            return this._snapshotRendering.enabled
        },
        set: function(i) {
            this._snapshotRendering.enabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "disableCacheSamplers", {
        get: function() {
            return this._cacheSampler ? this._cacheSampler.disabled : !1
        },
        set: function(i) {
            this._cacheSampler && (this._cacheSampler.disabled = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "disableCacheRenderPipelines", {
        get: function() {
            return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : !1
        },
        set: function(i) {
            this._cacheRenderPipeline && (this._cacheRenderPipeline.disabled = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "disableCacheBindGroups", {
        get: function() {
            return this._cacheBindGroups ? this._cacheBindGroups.disabled : !1
        },
        set: function(i) {
            this._cacheBindGroups && (this._cacheBindGroups.disabled = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "IsSupportedAsync", {
        get: function() {
            return navigator.gpu ? navigator.gpu.requestAdapter().then(function(i) {
                return !!i
            }, function(i) {
                return !1
            }).catch(function(i) {
                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 i = this.name + this.version;
            return i
        },
        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(i) {
            this._compatibilityMode = i
        },
        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(i, o) {
        o === void 0 && (o = {});
        var s = new e(i,o);
        return new Promise(function(c) {
            s.initAsync(o.glslangOptions, o.twgslOptions).then(function() {
                return c(s)
            })
        }
        )
    }
    ,
    e.prototype.initAsync = function(i, o) {
        var s = this, c;
        return this._initGlslang(i != null ? i : (c = this._options) === null || c === void 0 ? void 0 : c.glslangOptions).then(function(d) {
            var _;
            return s._glslang = d,
            s._tintWASM = e.UseTWGSL ? new WebGPUTintWASM : null,
            s._tintWASM ? s._tintWASM.initTwgsl(o != null ? o : (_ = s._options) === null || _ === void 0 ? void 0 : _.twgslOptions).then(function() {
                return navigator.gpu.requestAdapter(s._options)
            }, function(b) {
                throw Logger$2.Error("Can not initialize twgsl!"),
                Logger$2.Error(b),
                Error("WebGPU initializations stopped.")
            }) : navigator.gpu.requestAdapter(s._options)
        }, function(d) {
            throw Logger$2.Error("Can not initialize glslang!"),
            Logger$2.Error(d),
            Error("WebGPU initializations stopped.")
        }).then(function(d) {
            var _;
            if (d) {
                s._adapter = d,
                s._adapterSupportedExtensions = [],
                (_ = s._adapter.features) === null || _ === void 0 || _.forEach(function(tt) {
                    return s._adapterSupportedExtensions.push(tt)
                });
                var b = s._options.deviceDescriptor;
                if (b != null && b.requiredFeatures) {
                    for (var k = b.requiredFeatures, j = [], $ = 0, _e = k; $ < _e.length; $++) {
                        var et = _e[$];
                        s._adapterSupportedExtensions.indexOf(et) !== -1 && j.push(et)
                    }
                    b.requiredFeatures = j
                }
                return s._adapter.requestDevice(s._options.deviceDescriptor)
            } else
                throw "Could not retrieve a WebGPU adapter (adapter is null)."
        }).then(function(d) {
            var _, b;
            s._device = d,
            s._deviceEnabledExtensions = [],
            (_ = s._device.features) === null || _ === void 0 || _.forEach(function(j) {
                return s._deviceEnabledExtensions.push(j)
            });
            var k = -1;
            s._device.addEventListener("uncapturederror", function(j) {
                ++k < s.numMaxUncapturedErrors ? Logger$2.Warn("WebGPU uncaptured error (" + (k + 1) + "): " + j.error + " - " + j.error.message) : k++ === s.numMaxUncapturedErrors && Logger$2.Warn("WebGPU uncaptured error: too many warnings (" + s.numMaxUncapturedErrors + "), no more warnings will be reported to the console for this engine.")
            }),
            s._doNotHandleContextLost || (b = s._device.lost) === null || b === void 0 || b.then(function(j) {
                s._contextWasLost = !0,
                Logger$2.Warn("WebGPU context lost. " + j),
                s.onContextLostObservable.notifyObservers(s),
                s._restoreEngineAfterContextLost(s.initAsync.bind(s))
            })
        }, function(d) {
            Logger$2.Error("Could not retrieve a WebGPU device."),
            Logger$2.Error(d)
        }).then(function() {
            s._bufferManager = new WebGPUBufferManager(s._device),
            s._textureHelper = new WebGPUTextureHelper(s._device,s._glslang,s._tintWASM,s._bufferManager),
            s._cacheSampler = new WebGPUCacheSampler(s._device),
            s._cacheBindGroups = new WebGPUCacheBindGroups(s._device,s._cacheSampler,s),
            s._timestampQuery = new WebGPUTimestampQuery(s._device,s._bufferManager),
            s._occlusionQuery = s._device.createQuerySet ? new WebGPUOcclusionQuery(s,s._device,s._bufferManager) : void 0,
            s._bundleList = new WebGPUBundleList(s._device),
            s._bundleListRenderTarget = new WebGPUBundleList(s._device),
            s._snapshotRendering = new WebGPUSnapshotRendering(s,s._snapshotRenderingMode,s._bundleList,s._bundleListRenderTarget),
            s.dbgVerboseLogsForFirstFrames && s._count === void 0 && (s._count = 0,
            console.log("%c frame #" + s._count + " - begin", "background: #ffff00")),
            s._uploadEncoder = s._device.createCommandEncoder(s._uploadEncoderDescriptor),
            s._renderEncoder = s._device.createCommandEncoder(s._renderEncoderDescriptor),
            s._renderTargetEncoder = s._device.createCommandEncoder(s._renderTargetEncoderDescriptor),
            s._emptyVertexBuffer = new VertexBuffer(s,[0],"",!1,!1,1,!1,0,1),
            s._initializeLimits(),
            s._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(s._device,s._emptyVertexBuffer,!s._caps.textureFloatLinearFiltering),
            s._depthCullingState = new WebGPUDepthCullingState(s._cacheRenderPipeline),
            s._stencilStateComposer = new WebGPUStencilStateComposer(s._cacheRenderPipeline),
            s._stencilStateComposer.stencilGlobal = s._stencilState,
            s._depthCullingState.depthTest = !0,
            s._depthCullingState.depthFunc = 515,
            s._depthCullingState.depthMask = !0,
            s._textureHelper.setCommandEncoder(s._uploadEncoder),
            s._clearQuad = new WebGPUClearQuad(s._device,s,s._emptyVertexBuffer),
            s._defaultDrawContext = s.createDrawContext(),
            s._currentDrawContext = s._defaultDrawContext,
            s._defaultMaterialContext = s.createMaterialContext(),
            s._currentMaterialContext = s._defaultMaterialContext,
            s._initializeContextAndSwapChain(),
            s._initializeMainAttachments(),
            s.resize()
        }).catch(function(d) {
            Logger$2.Error("Can not create WebGPU Device and/or context."),
            Logger$2.Error(d),
            console.trace && console.trace()
        })
    }
    ,
    e.prototype._initGlslang = function(i) {
        return i = i || {},
        i = __assign(__assign({}, e._glslangDefaultOptions), i),
        i.glslang ? Promise.resolve(i.glslang) : self.glslang ? self.glslang(i.wasmPath) : i.jsPath && i.wasmPath ? IsWindowObjectExist() ? Tools.LoadScriptAsync(i.jsPath).then(function() {
            return self.glslang(i.wasmPath)
        }) : (importScripts(i.jsPath),
        self.glslang(i.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 i, o;
        this._mainTextureExtends = {
            width: this.getRenderWidth(),
            height: this.getRenderHeight(),
            depthOrArrayLayers: 1
        };
        var s;
        if (this._options.antialiasing) {
            var c = {
                size: this._mainTextureExtends,
                mipLevelCount: 1,
                sampleCount: this._mainPassSampleCount,
                dimension: TextureDimension.E2d,
                format: this._options.swapChainFormat,
                usage: TextureUsage.RenderAttachment
            };
            (i = this._mainTexture) === null || i === void 0 || i.destroy(),
            this._mainTexture = this._device.createTexture(c),
            s = [{
                view: this._mainTexture.createView(),
                loadValue: new Color4(0,0,0,1),
                storeOp: StoreOp.Store
            }]
        } else
            s = [{
                view: void 0,
                loadValue: new Color4(0,0,0,1),
                storeOp: StoreOp.Store
            }];
        if (this._invertYFinalFramebuffer) {
            var d = {
                size: this._mainTextureExtends,
                mipLevelCount: 1,
                sampleCount: 1,
                dimension: TextureDimension.E2d,
                format: this._options.swapChainFormat,
                usage: TextureUsage.RenderAttachment | TextureUsage.TextureBinding
            };
            (o = this._mainTextureLastCopy) === null || o === void 0 || o.destroy(),
            this._mainTextureLastCopy = this._device.createTexture(d),
            this._options.antialiasing ? s[0].resolveTarget = this._mainTextureLastCopy.createView() : s[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 _ = {
            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(_);
        var b = {
            view: this._depthTexture.createView(),
            depthLoadValue: this._clearDepthValue,
            depthStoreOp: StoreOp.Store,
            stencilLoadValue: this._clearStencilValue,
            stencilStoreOp: StoreOp.Store
        };
        this._mainRenderPassWrapper.renderPassDescriptor = {
            colorAttachments: s,
            depthStencilAttachment: b
        },
        this._mainRenderPassWrapper.renderPass !== null && this._endMainRenderPass()
    }
    ,
    e.prototype._configureContext = function(i, o) {
        this._context.configure({
            device: this._device,
            format: this._options.swapChainFormat,
            usage: TextureUsage.RenderAttachment | TextureUsage.CopySrc,
            compositingAlphaMode: this.premultipliedAlpha ? CanvasCompositingAlphaMode.Premultiplied : CanvasCompositingAlphaMode.Opaque,
            size: {
                width: i,
                height: o,
                depthOrArrayLayers: 1
            }
        })
    }
    ,
    e.prototype.setSize = function(i, o, s) {
        return s === void 0 && (s = !1),
        a.prototype.setSize.call(this, i, o, s) ? (this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - setSize called -", i, o)),
        this._configureContext(i, o),
        this._initializeMainAttachments(),
        this.snapshotRendering && this.snapshotRenderingReset(),
        !0) : !1
    }
    ,
    e.prototype._getShaderProcessor = function(i) {
        return i === ShaderLanguage.WGSL ? this._shaderProcessorWGSL : this._shaderProcessor
    }
    ,
    e.prototype._getShaderProcessingContext = function(i) {
        return new WebGPUShaderProcessingContext(i)
    }
    ,
    e.prototype.applyStates = function() {
        this._stencilStateComposer.apply(),
        this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)
    }
    ,
    e.prototype.wipeCaches = function(i) {
        this.preventCacheWipeBetweenFrames && !i || (this._forceEnableEffect = !0,
        this._currentIndexBuffer = null,
        this._currentOverrideVertexBuffers = null,
        this._cacheRenderPipeline.setBuffers(null, null, null),
        i && (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(i) {
        this.__colorWrite = i,
        this._cacheRenderPipeline.setWriteMask(i ? 15 : 0)
    }
    ,
    e.prototype.getColorWrite = function() {
        return this.__colorWrite
    }
    ,
    e.prototype._resetCurrentViewport = function(i) {
        this._viewportsCurrent[i].x = 0,
        this._viewportsCurrent[i].y = 0,
        this._viewportsCurrent[i].w = 0,
        this._viewportsCurrent[i].h = 0,
        i === 1 && (this._viewportCached.x = 0,
        this._viewportCached.y = 0,
        this._viewportCached.z = 0,
        this._viewportCached.w = 0)
    }
    ,
    e.prototype._mustUpdateViewport = function(i) {
        var o = i === this._mainRenderPassWrapper.renderPass ? 0 : 1
          , s = this._viewportCached.x
          , c = this._viewportCached.y
          , d = this._viewportCached.z
          , _ = this._viewportCached.w
          , b = this._viewportsCurrent[o].x !== s || this._viewportsCurrent[o].y !== c || this._viewportsCurrent[o].w !== d || this._viewportsCurrent[o].h !== _;
        return b && (this._viewportsCurrent[o].x = this._viewportCached.x,
        this._viewportsCurrent[o].y = this._viewportCached.y,
        this._viewportsCurrent[o].w = this._viewportCached.z,
        this._viewportsCurrent[o].h = this._viewportCached.w),
        b
    }
    ,
    e.prototype._applyViewport = function(i) {
        i.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=" + (i === this._mainRenderPassWrapper.renderPass)))
    }
    ,
    e.prototype._viewport = function(i, o, s, c) {
        this._viewportCached.x = i,
        this._viewportCached.y = o,
        this._viewportCached.z = s,
        this._viewportCached.w = c
    }
    ,
    e.prototype._resetCurrentScissor = function(i) {
        this._scissorsCurrent[i].x = 0,
        this._scissorsCurrent[i].y = 0,
        this._scissorsCurrent[i].w = 0,
        this._scissorsCurrent[i].h = 0
    }
    ,
    e.prototype._mustUpdateScissor = function(i) {
        var o = i === this._mainRenderPassWrapper.renderPass ? 0 : 1
          , s = this._scissorCached.x
          , c = this._scissorCached.y
          , d = this._scissorCached.z
          , _ = this._scissorCached.w
          , b = this._scissorsCurrent[o].x !== s || this._scissorsCurrent[o].y !== c || this._scissorsCurrent[o].w !== d || this._scissorsCurrent[o].h !== _;
        return b && (this._scissorsCurrent[o].x = this._scissorCached.x,
        this._scissorsCurrent[o].y = this._scissorCached.y,
        this._scissorsCurrent[o].w = this._scissorCached.z,
        this._scissorsCurrent[o].h = this._scissorCached.w),
        b
    }
    ,
    e.prototype._applyScissor = function(i) {
        i.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=" + (i === 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(i, o, s, c) {
        this._scissorCached.x = i,
        this._scissorCached.y = o,
        this._scissorCached.z = s,
        this._scissorCached.w = c
    }
    ,
    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(i) {
        this._stencilRefsCurrent[i] = -1
    }
    ,
    e.prototype._mustUpdateStencilRef = function(i) {
        var o = i === this._mainRenderPassWrapper.renderPass ? 0 : 1
          , s = this._stencilStateComposer.funcRef !== this._stencilRefsCurrent[o];
        return s && (this._stencilRefsCurrent[o] = this._stencilStateComposer.funcRef),
        s
    }
    ,
    e.prototype._applyStencilRef = function(i) {
        var o;
        i.setStencilReference((o = this._stencilStateComposer.funcRef) !== null && o !== void 0 ? o : 0)
    }
    ,
    e.prototype._resetCurrentColorBlend = function(i) {
        this._blendColorsCurrent[i][0] = this._blendColorsCurrent[i][1] = this._blendColorsCurrent[i][2] = this._blendColorsCurrent[i][3] = null
    }
    ,
    e.prototype._mustUpdateBlendColor = function(i) {
        var o = i === this._mainRenderPassWrapper.renderPass ? 0 : 1
          , s = this._alphaState._blendConstants
          , c = s[0] !== this._blendColorsCurrent[o][0] || s[1] !== this._blendColorsCurrent[o][1] || s[2] !== this._blendColorsCurrent[o][2] || s[3] !== this._blendColorsCurrent[o][3];
        return c && (this._blendColorsCurrent[o][0] = s[0],
        this._blendColorsCurrent[o][1] = s[1],
        this._blendColorsCurrent[o][2] = s[2],
        this._blendColorsCurrent[o][3] = s[3]),
        c
    }
    ,
    e.prototype._applyBlendColor = function(i) {
        i.setBlendConstant(this._alphaState._blendConstants)
    }
    ,
    e.prototype.clear = function(i, o, s, c) {
        c === void 0 && (c = !1),
        i && i.a === void 0 && (i.a = 1);
        var d = 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=", o, " depth=", s, " stencil=", c, " scissor is active=", d)),
        this._currentRenderTarget ? d ? (this._rttRenderPassWrapper.renderPass || this._startRenderTargetRenderPass(this._currentRenderTarget, !1, o ? i : null, s, c),
        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(o ? i : null, s, c)) : (this._currentRenderPass && this._endRenderTargetRenderPass(),
        this._startRenderTargetRenderPass(this._currentRenderTarget, !0, o ? i : null, s, c)) : ((!this._mainRenderPassWrapper.renderPass || !d) && this._startMainRenderPass(!d, o ? i : null, s, c),
        d && (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(o ? i : null, s, c)))
    }
    ,
    e.prototype._clearFullQuad = function(i, o, s) {
        var c, d, _, b = this.compatibilityMode ? this._getCurrentRenderPass() : null, k = this._getCurrentRenderPassIndex(), j = k === 0 ? this._bundleList : this._bundleListRenderTarget;
        this._clearQuad.setColorFormat(this._colorFormat),
        this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),
        this._clearQuad.setMRTAttachments((c = this._cacheRenderPipeline.mrtAttachments) !== null && c !== void 0 ? c : [], (d = this._cacheRenderPipeline.mrtTextureArray) !== null && d !== void 0 ? d : []),
        this.compatibilityMode ? b.setStencilReference(this._clearStencilValue) : j.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue));
        var $ = this._clearQuad.clear(b, i, o, s, this.currentSampleCount);
        this.compatibilityMode ? this._applyStencilRef(b) : (j.addBundle($),
        j.addItem(new WebGPURenderItemStencilRef((_ = this._stencilStateComposer.funcRef) !== null && _ !== void 0 ? _ : 0)),
        this._reportDrawCall())
    }
    ,
    e.prototype.createVertexBuffer = function(i) {
        var o;
        i instanceof Array ? o = new Float32Array(i) : i instanceof ArrayBuffer ? o = new Uint8Array(i) : o = i;
        var s = this._bufferManager.createBuffer(o, BufferUsage.Vertex | BufferUsage.CopyDst);
        return s
    }
    ,
    e.prototype.createDynamicVertexBuffer = function(i) {
        return this.createVertexBuffer(i)
    }
    ,
    e.prototype.createIndexBuffer = function(i, o) {
        var s = !0, c;
        i instanceof Uint32Array || i instanceof Int32Array ? c = i : i instanceof Uint16Array ? (c = i,
        s = !1) : i.length > 65535 ? c = new Uint32Array(i) : (c = new Uint16Array(i),
        s = !1);
        var d = this._bufferManager.createBuffer(c, BufferUsage.Index | BufferUsage.CopyDst);
        return d.is32Bits = s,
        d
    }
    ,
    e.prototype._createBuffer = function(i, o) {
        var s;
        i instanceof Array ? s = new Float32Array(i) : i instanceof ArrayBuffer ? s = new Uint8Array(i) : s = i;
        var c = 0;
        return o & 1 && (c |= BufferUsage.CopySrc),
        o & 2 && (c |= BufferUsage.CopyDst),
        o & 4 && (c |= BufferUsage.Uniform),
        o & 8 && (c |= BufferUsage.Vertex),
        o & 16 && (c |= BufferUsage.Index),
        o & 32 && (c |= BufferUsage.Storage),
        this._bufferManager.createBuffer(s, c)
    }
    ,
    e.prototype.bindBuffersDirectly = function(i, o, s, c, d) {
        throw "Not implemented on WebGPU"
    }
    ,
    e.prototype.updateAndBindInstancesBuffer = function(i, o, s) {
        throw "Not implemented on WebGPU"
    }
    ,
    e.prototype.bindBuffers = function(i, o, s, c) {
        this._currentIndexBuffer = o,
        this._currentOverrideVertexBuffers = c != null ? c : null,
        this._cacheRenderPipeline.setBuffers(i, o, this._currentOverrideVertexBuffers)
    }
    ,
    e.prototype._releaseBuffer = function(i) {
        return this._bufferManager.releaseBuffer(i)
    }
    ,
    e.prototype.createEffect = function(i, o, s, c, d, _, b, k, j, $) {
        var _e;
        $ === void 0 && ($ = ShaderLanguage.GLSL);
        var et = i.vertexElement || i.vertex || i.vertexToken || i.vertexSource || i
          , tt = i.fragmentElement || i.fragment || i.fragmentToken || i.fragmentSource || i
          , rt = this._getGlobalDefines()
          , it = (_e = d != null ? d : o.defines) !== null && _e !== void 0 ? _e : "";
        rt && (it += `
` + rt);
        var nt = et + "+" + tt + "@" + it;
        if (this._compiledEffects[nt]) {
            var ot = this._compiledEffects[nt];
            return b && ot.isReady() && b(ot),
            ot
        }
        var at = new Effect(i,o,s,c,this,d,_,b,k,j,nt,$);
        return this._compiledEffects[nt] = at,
        at
    }
    ,
    e.prototype._compileRawShaderToSpirV = function(i, o) {
        return this._glslang.compileGLSL(i, o)
    }
    ,
    e.prototype._compileShaderToSpirV = function(i, o, s, c) {
        return this._compileRawShaderToSpirV(c + (s ? s + `
` : "") + i, o)
    }
    ,
    e.prototype._getWGSLShader = function(i, o, s, c) {
        return s ? s = "//" + s.split(`
`).join(`
//`) + `
` : s = "",
        s + i
    }
    ,
    e.prototype._createPipelineStageDescriptor = function(i, o, s) {
        return this._tintWASM && s === ShaderLanguage.GLSL && (i = this._tintWASM.convertSpirV2WGSL(i),
        o = this._tintWASM.convertSpirV2WGSL(o)),
        {
            vertexStage: {
                module: this._device.createShaderModule({
                    code: i
                }),
                entryPoint: "main"
            },
            fragmentStage: {
                module: this._device.createShaderModule({
                    code: o
                }),
                entryPoint: "main"
            }
        }
    }
    ,
    e.prototype._compileRawPipelineStageDescriptor = function(i, o, s) {
        var c = s === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(i, "vertex") : i
          , d = s === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(o, "fragment") : o;
        return this._createPipelineStageDescriptor(c, d, s)
    }
    ,
    e.prototype._compilePipelineStageDescriptor = function(i, o, s, c) {
        this.onBeforeShaderCompilationObservable.notifyObservers(this);
        var d = `#version 450
`
          , _ = c === ShaderLanguage.GLSL ? this._compileShaderToSpirV(i, "vertex", s, d) : this._getWGSLShader(i, "vertex", s, d)
          , b = c === ShaderLanguage.GLSL ? this._compileShaderToSpirV(o, "fragment", s, d) : this._getWGSLShader(o, "fragment", s, d)
          , k = this._createPipelineStageDescriptor(_, b, c);
        return this.onAfterShaderCompilationObservable.notifyObservers(this),
        k
    }
    ,
    e.prototype.createRawShaderProgram = function(i, o, s, c, d) {
        throw "Not available on WebGPU"
    }
    ,
    e.prototype.createShaderProgram = function(i, o, s, c, d, _) {
        throw "Not available on WebGPU"
    }
    ,
    e.prototype.inlineShaderCode = function(i) {
        var o = new ShaderCodeInliner(i);
        return o.debug = !1,
        o.processCode(),
        o.code
    }
    ,
    e.prototype.createPipelineContext = function(i) {
        return new WebGPUPipelineContext(i,this)
    }
    ,
    e.prototype.createMaterialContext = function() {
        return new WebGPUMaterialContext
    }
    ,
    e.prototype.createDrawContext = function() {
        return new WebGPUDrawContext(this._bufferManager)
    }
    ,
    e.prototype._preparePipelineContext = function(i, o, s, c, d, _, b, k, j, $) {
        var _e = i
          , et = _e.shaderProcessingContext.shaderLanguage;
        this.dbgShowShaderCode && (console.log(k),
        console.log(o),
        console.log(s)),
        _e.sources = {
            fragment: s,
            vertex: o,
            rawVertex: d,
            rawFragment: _
        },
        c ? _e.stages = this._compileRawPipelineStageDescriptor(o, s, et) : _e.stages = this._compilePipelineStageDescriptor(o, s, k, et)
    }
    ,
    e.prototype.getAttributes = function(i, o) {
        for (var s = new Array(o.length), c = i, d = 0; d < o.length; d++) {
            var _ = o[d]
              , b = c.shaderProcessingContext.availableAttributes[_];
            b !== void 0 && (s[d] = b)
        }
        return s
    }
    ,
    e.prototype.enableEffect = function(i) {
        if (!!i) {
            var o = !0;
            if (!DrawWrapper.IsWrapper(i))
                o = i !== this._currentEffect,
                this._currentEffect = i,
                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=" + i.uniqueId + ", effect.name=" + i.name + ", effect.name.vertex=" + i.name.vertex + ", effect.name.fragment=" + i.name.fragment, 10);
            else if (!i.effect || i.effect === this._currentEffect && i.materialContext === this._currentMaterialContext && i.drawContext === this._currentDrawContext && !this._forceEnableEffect) {
                if (!i.effect && this.dbgShowEmptyEnableEffectCalls)
                    throw console.error("drawWrapper=", i),
                    "Invalid call to enableEffect: the effect property is empty!";
                return
            } else if (o = i.effect !== this._currentEffect,
            this._currentEffect = i.effect,
            this._currentMaterialContext = i.materialContext,
            this._currentDrawContext = i.drawContext,
            this._counters.numEnableDrawWrapper++,
            !this._currentMaterialContext)
                throw console.error("drawWrapper=", i),
                "Invalid call to enableEffect: the materialContext property is empty!";
            this._stencilStateComposer.stencilMaterial = void 0,
            this._forceEnableEffect = o || this._forceEnableEffect ? !1 : this._forceEnableEffect,
            o && (this._currentEffect.onBind && this._currentEffect.onBind(this._currentEffect),
            this._currentEffect._onBindObservable && this._currentEffect._onBindObservable.notifyObservers(this._currentEffect))
        }
    }
    ,
    e.prototype._releaseEffect = function(i) {
        this._compiledEffects[i._key] && (delete this._compiledEffects[i._key],
        this._deletePipelineContext(i.getPipelineContext()))
    }
    ,
    e.prototype.releaseEffects = function() {
        for (var i in this._compiledEffects) {
            var o = this._compiledEffects[i].getPipelineContext();
            this._deletePipelineContext(o)
        }
        this._compiledEffects = {}
    }
    ,
    e.prototype._deletePipelineContext = function(i) {
        var o = i;
        o && i.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(i) {
        var o = this._internalTexturesCache.indexOf(i);
        o !== -1 && this._internalTexturesCache.splice(o, 1),
        this._textureHelper.releaseTexture(i)
    }
    ,
    e.prototype._getRGBABufferInternalSizedFormat = function(i, o) {
        return 5
    }
    ,
    e.prototype.updateTextureComparisonFunction = function(i, o) {
        i._comparisonFunction = o
    }
    ,
    e.prototype._createInternalTexture = function(i, o, s, c) {
        var d, _;
        s === void 0 && (s = !0),
        c === void 0 && (c = InternalTextureSource.Unknown);
        var b = {};
        o !== void 0 && typeof o == "object" ? (b.generateMipMaps = o.generateMipMaps,
        b.type = o.type === void 0 ? 0 : o.type,
        b.samplingMode = o.samplingMode === void 0 ? 3 : o.samplingMode,
        b.format = o.format === void 0 ? 5 : o.format,
        b.samples = (d = o.samples) !== null && d !== void 0 ? d : 1,
        b.creationFlags = (_ = o.creationFlags) !== null && _ !== void 0 ? _ : 0) : (b.generateMipMaps = o,
        b.type = 0,
        b.samplingMode = 3,
        b.format = 5,
        b.samples = 1,
        b.creationFlags = 0),
        (b.type === 1 && !this._caps.textureFloatLinearFiltering || b.type === 2 && !this._caps.textureHalfFloatLinearFiltering) && (b.samplingMode = 1),
        b.type === 1 && !this._caps.textureFloat && (b.type = 0,
        Logger$2.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));
        var k = new InternalTexture(this,c)
          , j = i.width || i
          , $ = i.height || i
          , _e = i.layers || 0;
        return k.baseWidth = j,
        k.baseHeight = $,
        k.width = j,
        k.height = $,
        k.depth = _e,
        k.isReady = !0,
        k.samples = b.samples,
        k.generateMipMaps = !!b.generateMipMaps,
        k.samplingMode = b.samplingMode,
        k.type = b.type,
        k.format = b.format,
        k.is2DArray = _e > 0,
        k._cachedWrapU = 0,
        k._cachedWrapV = 0,
        this._internalTexturesCache.push(k),
        s || this._textureHelper.createGPUTextureForInternalTexture(k, j, $, _e || 1, b.creationFlags),
        k
    }
    ,
    e.prototype.createTexture = function(i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it) {
        var nt = this;
        return d === void 0 && (d = 3),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null),
        k === void 0 && (k = null),
        j === void 0 && (j = null),
        $ === void 0 && ($ = null),
        _e === void 0 && (_e = null),
        this._createTextureBase(i, o, s, c, d, _, b, function(ot, at, st, ut, ct, lt, ft, ht, pt) {
            var dt, _t = ut;
            if (ot.baseWidth = _t.width,
            ot.baseHeight = _t.height,
            ot.width = _t.width,
            ot.height = _t.height,
            ot.format = $ != null ? $ : -1,
            ht(ot.width, ot.height, _t, at, ot, function() {}),
            !((dt = ot._hardwareTexture) === null || dt === void 0) && dt.underlyingResource)
                !lt && !ft && nt._generateMipmaps(ot, nt._uploadEncoder);
            else {
                var mt = nt._textureHelper.createGPUTextureForInternalTexture(ot, _t.width, _t.height, void 0, rt);
                WebGPUTextureHelper.IsImageBitmap(_t) && (nt._textureHelper.updateTexture(_t, ot, _t.width, _t.height, ot.depth, mt.format, 0, 0, ct, !1, 0, 0, nt._uploadEncoder),
                !lt && !ft && nt._generateMipmaps(ot, nt._uploadEncoder))
            }
            st && st._removePendingData(ot),
            ot.isReady = !0,
            ot.onLoadedObservable.notifyObservers(ot),
            ot.onLoadedObservable.clear()
        }, function() {
            return !1
        }, k, j, $, _e, et, tt, it)
    }
    ,
    e.prototype.generateMipMapsForCubemap = function(i, o) {
        var s;
        if (i.generateMipMaps) {
            var c = (s = i._hardwareTexture) === null || s === void 0 ? void 0 : s.underlyingResource;
            c || this._textureHelper.createGPUTextureForInternalTexture(i),
            this._generateMipmaps(i, i.source === InternalTextureSource.RenderTarget || i.source === InternalTextureSource.MultiRenderTarget ? this._renderTargetEncoder : void 0)
        }
    }
    ,
    e.prototype.updateTextureSamplingMode = function(i, o, s) {
        s === void 0 && (s = !1),
        s && (o.generateMipMaps = !0,
        this._generateMipmaps(o)),
        o.samplingMode = i
    }
    ,
    e.prototype.updateTextureWrappingMode = function(i, o, s, c) {
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        o !== null && (i._cachedWrapU = o),
        s !== null && (i._cachedWrapV = s),
        (i.is2DArray || i.is3D) && c !== null && (i._cachedWrapR = c)
    }
    ,
    e.prototype.updateTextureDimensions = function(i, o, s, c) {
        if (c === void 0 && (c = 1),
        !!i._hardwareTexture && !(i.width === o && i.height === s && i.depth === c)) {
            var d = i._hardwareTexture.textureAdditionalUsages;
            i._hardwareTexture.release(),
            this._textureHelper.createGPUTextureForInternalTexture(i, o, s, c, d)
        }
    }
    ,
    e.prototype._setInternalTexture = function(i, o, s, c) {
        if (s = s != null ? s : i,
        this._currentEffect) {
            var d = this._currentEffect._pipelineContext
              , _ = d.shaderProcessingContext.availableTextures[s];
            if (this._currentMaterialContext.setTexture(i, o),
            _ && _.autoBindSampler) {
                var b = s + WebGPUShaderProcessor.AutoSamplerSuffix;
                this._currentMaterialContext.setSampler(b, o)
            }
        }
    }
    ,
    e.prototype.setTexture = function(i, o, s, c) {
        this._setTexture(i, s, !1, !1, c, c)
    }
    ,
    e.prototype.setTextureArray = function(i, o, s, c) {
        for (var d = 0; d < s.length; d++)
            this._setTexture(-1, s[d], !0, !1, c + d.toString(), c, d)
    }
    ,
    e.prototype._setTexture = function(i, o, s, c, d, _, b) {
        if (c === void 0 && (c = !1),
        d === void 0 && (d = ""),
        b === void 0 && (b = 0),
        _ = _ != null ? _ : d,
        this._currentEffect) {
            if (!o)
                return this._currentMaterialContext.setTexture(d, null),
                !1;
            if (o.video)
                o.update();
            else if (o.delayLoadState === 4)
                return o.delayLoad(),
                !1;
            var k = null;
            if (c ? k = o.depthStencilTexture : o.isReady() ? k = o.getInternalTexture() : o.isCube ? k = this.emptyCubeTexture : o.is3D ? k = this.emptyTexture3D : o.is2DArray ? k = this.emptyTexture2DArray : k = this.emptyTexture,
            k && !k.isMultiview) {
                if (k.isCube && k._cachedCoordinatesMode !== o.coordinatesMode) {
                    k._cachedCoordinatesMode = o.coordinatesMode;
                    var j = o.coordinatesMode !== 3 && o.coordinatesMode !== 5 ? 1 : 0;
                    o.wrapU = j,
                    o.wrapV = j
                }
                k._cachedWrapU = o.wrapU,
                k._cachedWrapV = o.wrapV,
                k.is3D && (k._cachedWrapR = o.wrapR),
                this._setAnisotropicLevel(0, k, o.anisotropicFilteringLevel)
            }
            this._setInternalTexture(d, k, _, b)
        } 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=", o));
        return !0
    }
    ,
    e.prototype._setAnisotropicLevel = function(i, o, s) {
        o._cachedAnisotropicFilteringLevel !== s && (o._cachedAnisotropicFilteringLevel = Math.min(s, this._caps.maxAnisotropy))
    }
    ,
    e.prototype._bindTexture = function(i, o, s) {
        i !== void 0 && this._setInternalTexture(s, o)
    }
    ,
    e.prototype.generateMipmaps = function(i) {
        this._generateMipmaps(i, this._renderTargetEncoder)
    }
    ,
    e.prototype._generateMipmaps = function(i, o) {
        var s = i._hardwareTexture;
        if (!!s) {
            o = o != null ? o : this._currentRenderTarget && !this._currentRenderPass ? this._renderTargetEncoder : this._currentRenderPass ? this._uploadEncoder : this._renderEncoder;
            var c = i._hardwareTexture.format
              , d = WebGPUTextureHelper.ComputeNumMipmapLevels(i.width, i.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=", i.width, "height=", i.height, "isCube=", i.isCube)),
            i.isCube ? this._textureHelper.generateCubeMipmaps(s, c, d, o) : this._textureHelper.generateMipmaps(s, c, d, 0, o)
        }
    }
    ,
    e.prototype.updateTextureData = function(i, o, s, c, d, _, b, k) {
        var j;
        b === void 0 && (b = 0),
        k === void 0 && (k = 0);
        var $ = i._hardwareTexture;
        !((j = i._hardwareTexture) === null || j === void 0) && j.underlyingResource || ($ = this._textureHelper.createGPUTextureForInternalTexture(i));
        var _e = new Uint8Array(o.buffer,o.byteOffset,o.byteLength);
        this._textureHelper.updateTexture(_e, i, d, _, i.depth, $.format, b, k, i.invertY, !1, s, c, this._uploadEncoder)
    }
    ,
    e.prototype._uploadCompressedDataToTextureDirectly = function(i, o, s, c, d, _, b) {
        var k;
        _ === void 0 && (_ = 0),
        b === void 0 && (b = 0);
        var j = i._hardwareTexture;
        !((k = i._hardwareTexture) === null || k === void 0) && k.underlyingResource || (i.format = o,
        j = this._textureHelper.createGPUTextureForInternalTexture(i, s, c));
        var $ = new Uint8Array(d.buffer,d.byteOffset,d.byteLength);
        this._textureHelper.updateTexture($, i, s, c, i.depth, j.format, _, b, !1, !1, 0, 0, this._uploadEncoder)
    }
    ,
    e.prototype._uploadDataToTextureDirectly = function(i, o, s, c, d, _) {
        var b;
        s === void 0 && (s = 0),
        c === void 0 && (c = 0),
        _ === void 0 && (_ = !1);
        var k = Math.round(Math.log(i.width) * Math.LOG2E)
          , j = Math.round(Math.log(i.height) * Math.LOG2E)
          , $ = _ ? i.width : Math.pow(2, Math.max(k - c, 0))
          , _e = _ ? i.height : Math.pow(2, Math.max(j - c, 0))
          , et = i._hardwareTexture;
        !((b = i._hardwareTexture) === null || b === void 0) && b.underlyingResource || (et = this._textureHelper.createGPUTextureForInternalTexture(i, $, _e));
        var tt = new Uint8Array(o.buffer,o.byteOffset,o.byteLength);
        this._textureHelper.updateTexture(tt, i, $, _e, i.depth, et.format, s, c, i.invertY, !1, 0, 0, this._uploadEncoder)
    }
    ,
    e.prototype._uploadArrayBufferViewToTexture = function(i, o, s, c) {
        s === void 0 && (s = 0),
        c === void 0 && (c = 0),
        this._uploadDataToTextureDirectly(i, o, s, c)
    }
    ,
    e.prototype._uploadImageToTexture = function(i, o, s, c) {
        var d;
        s === void 0 && (s = 0),
        c === void 0 && (c = 0);
        var _ = i._hardwareTexture;
        !((d = i._hardwareTexture) === null || d === void 0) && d.underlyingResource || (_ = this._textureHelper.createGPUTextureForInternalTexture(i));
        var b = o
          , k = Math.ceil(i.width / (1 << c))
          , j = Math.ceil(i.height / (1 << c));
        this._textureHelper.updateTexture(b, i, k, j, i.depth, _.format, s, c, i.invertY, !1, 0, 0, this._uploadEncoder)
    }
    ,
    e.prototype.readPixels = function(i, o, s, c, d, _) {
        _ === void 0 && (_ = !0);
        var b = this._rttRenderPassWrapper.renderPass ? this._rttRenderPassWrapper : this._mainRenderPassWrapper
          , k = b.colorAttachmentGPUTextures[0].underlyingResource
          , j = b.colorAttachmentGPUTextures[0].format;
        return k ? (_ && this.flushFramebuffer(),
        this._textureHelper.readPixels(k, i, o, s, c, j)) : Promise.resolve(new Uint8Array(0))
    }
    ,
    e.prototype.beginFrame = function() {
        a.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 i = [];
                for (var o in UniformBuffer._updatedUbosInFrame)
                    i.push(o + ":" + UniformBuffer._updatedUbosInFrame[o]);
                console.log("frame #" + this._count + " - updated ubos -", i.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,
        a.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(i) {
        i === void 0 && (i = !0);
        var o = !this._currentRenderPass
          , s = 0;
        this._currentRenderPass && this._currentRenderTarget && (s |= 1,
        this._endRenderTargetRenderPass()),
        this._mainRenderPassWrapper.renderPass && (s |= 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(),
        i && (s & 2 && this._startMainRenderPass(!1),
        s & 1 && this._startRenderTargetRenderPass(this._currentRenderTarget, !1, null, !1, !1),
        o && this._currentRenderTarget && (this._currentRenderPass = null))
    }
    ,
    e.prototype._currentFrameBufferIsDefaultFrameBuffer = function() {
        return this._currentRenderTarget === null
    }
    ,
    e.prototype._startRenderTargetRenderPass = function(i, o, s, c, d) {
        var _, b, k, j = i._depthStencilTexture, $ = j == null ? void 0 : j._hardwareTexture, _e = $ == null ? void 0 : $.underlyingResource, et = $ == null ? void 0 : $.msaaTexture, tt = _e == null ? void 0 : _e.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor), rt = et == null ? void 0 : et.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor), it = [];
        this.useReverseDepthBuffer && this.setDepthFunctionToGreaterOrEqual();
        var nt = o && s || LoadOp.Load
          , ot = o && c ? this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue : LoadOp.Load
          , at = o && d ? this._clearStencilValue : LoadOp.Load;
        if (i._attachments && i.isMulti) {
            (!this._mrtAttachments || this._mrtAttachments.length === 0) && (this._mrtAttachments = i._attachments);
            for (var st = 0; st < this._mrtAttachments.length; ++st) {
                var ut = this._mrtAttachments[st];
                if (ut !== 0) {
                    var ct = i.textures[ut - 1]
                      , lt = ct == null ? void 0 : ct._hardwareTexture
                      , ft = lt == null ? void 0 : lt.underlyingResource;
                    if (lt && ft) {
                        var ht = __assign(__assign({}, this._rttRenderPassWrapper.colorAttachmentViewDescriptor), {
                            format: lt.format
                        })
                          , pt = lt.msaaTexture
                          , dt = ft.createView(ht)
                          , _t = pt == null ? void 0 : pt.createView(ht);
                        it.push({
                            view: _t || dt,
                            resolveTarget: pt ? dt : void 0,
                            loadValue: nt,
                            storeOp: StoreOp.Store
                        })
                    }
                }
            }
            this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments, i.textures)
        } else {
            var mt = i.texture
              , vt = mt._hardwareTexture
              , yt = vt.underlyingResource
              , pt = vt.msaaTexture
              , dt = yt.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor)
              , _t = pt == null ? void 0 : pt.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);
            it.push({
                view: _t || dt,
                resolveTarget: pt ? dt : void 0,
                loadValue: nt,
                storeOp: StoreOp.Store
            })
        }
        if ((_ = this._debugPushGroup) === null || _ === void 0 || _.call(this, "render target pass", 1),
        this._rttRenderPassWrapper.renderPassDescriptor = {
            colorAttachments: it,
            depthStencilAttachment: j && _e ? {
                view: rt || tt,
                depthLoadValue: ot,
                depthStoreOp: StoreOp.Store,
                stencilLoadValue: i._depthStencilTextureWithStencil ? at : LoadOp.Load,
                stencilStoreOp: StoreOp.Store
            } : void 0,
            occlusionQuerySet: !((b = this._occlusionQuery) === null || b === void 0) && b.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 mt = i.texture;
            console.log("frame #" + this._count + " - render target begin pass - internalTexture.uniqueId=", mt.uniqueId, "width=", mt.width, "height=", mt.height, this._rttRenderPassWrapper.renderPassDescriptor)
        }
        this._currentRenderPass = this._rttRenderPassWrapper.renderPass,
        (k = this._debugFlushPendingCommands) === null || k === void 0 || k.call(this),
        this._resetCurrentViewport(1),
        this._resetCurrentScissor(1),
        this._resetCurrentStencilRef(1),
        this._resetCurrentColorBlend(1)
    }
    ,
    e.prototype._endRenderTargetRenderPass = function() {
        var i, o, s;
        if (this._currentRenderPass) {
            var c = this._currentRenderTarget.texture._hardwareTexture;
            !this._snapshotRendering.endRenderTargetPass(this._currentRenderPass, c) && !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=", (o = (i = this._currentRenderTarget) === null || i === void 0 ? void 0 : i.texture) === null || o === void 0 ? void 0 : o.uniqueId)),
            (s = this._debugPopGroup) === null || s === void 0 || s.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(i, o, s, c) {
        var d, _, b;
        this._mainRenderPassWrapper.renderPass && this._endMainRenderPass(),
        this.useReverseDepthBuffer && this.setDepthFunctionToGreaterOrEqual();
        var k = i && o || LoadOp.Load
          , j = i && s ? this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue : LoadOp.Load
          , $ = i && c ? this._clearStencilValue : LoadOp.Load;
        this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadValue = k,
        this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadValue = j,
        this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadValue = $,
        this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet = !((d = this._occlusionQuery) === null || d === void 0) && d.hasQueries ? this._occlusionQuery.querySet : void 0;
        var _e = this._invertYFinalFramebuffer ? this._mainRenderPassCopyWrapper : this._mainRenderPassWrapper;
        this._swapChainTexture = this._context.getCurrentTexture(),
        _e.colorAttachmentGPUTextures[0].set(this._swapChainTexture),
        this._options.antialiasing ? this._invertYFinalFramebuffer ? _e.renderPassDescriptor.colorAttachments[0].view = this._swapChainTexture.createView() : _e.renderPassDescriptor.colorAttachments[0].resolveTarget = this._swapChainTexture.createView() : _e.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)),
        (_ = this._debugPushGroup) === null || _ === void 0 || _.call(this, "main pass", 0),
        this._currentRenderPass = this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),
        this._mainRenderPassWrapper.renderPass = this._currentRenderPass,
        (b = this._debugFlushPendingCommands) === null || b === void 0 || b.call(this),
        this._resetCurrentViewport(0),
        this._resetCurrentScissor(0),
        this._resetCurrentStencilRef(0),
        this._resetCurrentColorBlend(0)
    }
    ,
    e.prototype._endMainRenderPass = function() {
        var i;
        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")),
        (i = this._debugPopGroup) === null || i === void 0 || i.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(i, o, s, c, d, _, b) {
        var k, j;
        o === void 0 && (o = 0),
        _ === void 0 && (_ = 0),
        b === void 0 && (b = 0);
        var $ = (k = i.texture) === null || k === void 0 ? void 0 : k._hardwareTexture;
        if (!$) {
            this.dbgSanityChecks && console.error("bindFramebuffer: Trying to bind a texture that does not have a hardware texture!", i, $);
            return
        }
        this._currentRenderTarget && this.unBindFramebuffer(this._currentRenderTarget),
        this._currentRenderTarget = i,
        $._currentLayer = i.isCube ? b * 6 + o : b,
        this._rttRenderPassWrapper.colorAttachmentGPUTextures[0] = $,
        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: i.isCube ? b * 6 + o : b,
            baseMipLevel: _,
            arrayLayerCount: 1,
            aspect: TextureAspect.All
        },
        this._rttRenderPassWrapper.depthAttachmentViewDescriptor = {
            format: this._depthTextureFormat,
            dimension: TextureViewDimension.E2d,
            mipLevelCount: 1,
            baseArrayLayer: i.isCube ? b * 6 + o : b,
            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=", (j = i.texture) === null || j === void 0 ? void 0 : j.uniqueId, "face=", o, "lodLevel=", _, "layer=", b, this._rttRenderPassWrapper.colorAttachmentViewDescriptor, this._rttRenderPassWrapper.depthAttachmentViewDescriptor)),
        this._currentRenderPass = null,
        this.snapshotRendering && this.snapshotRenderingMode === 1 && this._getCurrentRenderPass(),
        this._cachedViewport && !d ? this.setViewport(this._cachedViewport, s, c) : (s || (s = i.width,
        _ && (s = s / Math.pow(2, _))),
        c || (c = i.height,
        _ && (c = c / Math.pow(2, _))),
        this._viewport(0, 0, s, c)),
        this.wipeCaches()
    }
    ,
    e.prototype.unBindFramebuffer = function(i, o, s) {
        var c, d;
        o === void 0 && (o = !1);
        var _ = this._currentRenderTarget;
        this._currentRenderTarget = null,
        s && s(),
        this._currentRenderTarget = _,
        this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass && this._endRenderTargetRenderPass(),
        ((c = i.texture) === null || c === void 0 ? void 0 : c.generateMipMaps) && !o && !i.isCube && this._generateMipmaps(i.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=", (d = i.texture) === null || d === void 0 ? void 0 : d.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(i) {
        var o = i.colorAttachmentGPUTextures[0].format;
        this._cacheRenderPipeline.setColorFormat(o),
        this._colorFormat !== o && (this._colorFormat = o)
    }
    ,
    e.prototype._setDepthTextureFormat = function(i) {
        this._cacheRenderPipeline.setDepthStencilFormat(i.depthTextureFormat),
        this._depthTextureFormat !== i.depthTextureFormat && (this._depthTextureFormat = i.depthTextureFormat)
    }
    ,
    e.prototype.setDitheringState = function(i) {}
    ,
    e.prototype.setRasterizerState = function(i) {}
    ,
    e.prototype.setState = function(i, o, s, c, d, _, b) {
        var k, j;
        o === void 0 && (o = 0),
        c === void 0 && (c = !1),
        b === void 0 && (b = 0),
        (this._depthCullingState.cull !== i || s) && (this._depthCullingState.cull = i);
        var $ = !((j = (k = this.cullBackFaces) !== null && k !== void 0 ? k : d) !== null && j !== void 0) || j ? 1 : 2;
        (this._depthCullingState.cullFace !== $ || s) && (this._depthCullingState.cullFace = $),
        this.setZOffset(o),
        this.setZOffsetUnits(b);
        var _e = c ? 1 : 2;
        (this._depthCullingState.frontFace !== _e || s) && (this._depthCullingState.frontFace = _e),
        this._stencilStateComposer.stencilMaterial = _
    }
    ,
    e.prototype._applyRenderPassChanges = function(i, o) {
        var s, c = this._mustUpdateViewport(i), d = this._mustUpdateScissor(i), _ = this._stencilStateComposer.enabled ? this._mustUpdateStencilRef(i) : !1, b = this._alphaState.alphaBlend ? this._mustUpdateBlendColor(i) : !1;
        o ? (c && o.addItem(new WebGPURenderItemViewport(this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w)),
        d && o.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),
        _ && o.addItem(new WebGPURenderItemStencilRef((s = this._stencilStateComposer.funcRef) !== null && s !== void 0 ? s : 0)),
        b && o.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice()))) : (c && this._applyViewport(i),
        d && this._applyScissor(i),
        _ && this._applyStencilRef(i),
        b && this._applyBlendColor(i))
    }
    ,
    e.prototype._draw = function(i, o, s, c, d) {
        var _, b = this._getCurrentRenderPass(), k = this._getCurrentRenderPassIndex(), j = k === 0 ? this._bundleList : this._bundleListRenderTarget;
        this.applyStates();
        var $ = this._currentEffect._pipelineContext;
        if ($.uniformBuffer && ($.uniformBuffer.update(),
        this.bindUniformBufferBase($.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 _e = !this.compatibilityMode && this._currentDrawContext.fastBundle
          , et = b;
        if (_e || this._snapshotRendering.record) {
            if (this._applyRenderPassChanges(b, j),
            !this._snapshotRendering.record) {
                this._counters.numBundleReuseNonCompatMode++,
                this._currentDrawContext.indirectDrawBuffer && this._currentDrawContext.setIndirectData(c, d || 1, s),
                j.addBundle(this._currentDrawContext.fastBundle),
                this._reportDrawCall();
                return
            }
            et = j.getBundleEncoder(this._cacheRenderPipeline.colorFormats, this._depthTextureFormat, this.currentSampleCount),
            j.numDrawCalls++
        }
        var tt = 0;
        if (!this._caps.textureFloatLinearFiltering && this._currentMaterialContext.hasFloatTextures)
            for (var rt = 1, it = 0; it < $.shaderProcessingContext.textureNames.length; ++it) {
                var nt = $.shaderProcessingContext.textureNames[it]
                  , ot = (_ = this._currentMaterialContext.textures[nt]) === null || _ === void 0 ? void 0 : _.texture;
                (ot == null ? void 0 : ot.type) === 1 && (tt |= rt),
                rt = rt << 1
            }
        var at = this._cacheRenderPipeline.getRenderPipeline(o, this._currentEffect, this.currentSampleCount, tt)
          , st = this._cacheBindGroups.getBindGroups($, this._currentDrawContext, this._currentMaterialContext);
        this._snapshotRendering.record || (this._applyRenderPassChanges(b, this.compatibilityMode ? null : j),
        this.compatibilityMode || (this._counters.numBundleCreationNonCompatMode++,
        et = this._device.createRenderBundleEncoder({
            colorFormats: this._cacheRenderPipeline.colorFormats,
            depthStencilFormat: this._depthTextureFormat,
            sampleCount: this.currentSampleCount
        }))),
        et.setPipeline(at),
        this._currentIndexBuffer && et.setIndexBuffer(this._currentIndexBuffer.underlyingResource, this._currentIndexBuffer.is32Bits ? IndexFormat.Uint32 : IndexFormat.Uint16, 0);
        for (var ut = this._cacheRenderPipeline.vertexBuffers, ct = 0; ct < ut.length; ct++) {
            var lt = ut[ct]
              , ft = lt.getBuffer();
            ft && et.setVertexBuffer(ct, ft.underlyingResource, lt._validOffsetRange ? 0 : lt.byteOffset)
        }
        for (var it = 0; it < st.length; it++)
            et.setBindGroup(it, st[it]);
        var ht = !this.compatibilityMode && !this._snapshotRendering.record;
        ht && this._currentDrawContext.indirectDrawBuffer ? (this._currentDrawContext.setIndirectData(c, d || 1, s),
        i === 0 ? et.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer, 0) : et.drawIndirect(this._currentDrawContext.indirectDrawBuffer, 0)) : i === 0 ? et.drawIndexed(c, d || 1, s, 0, 0) : et.draw(c, d || 1, s, 0),
        ht && (this._currentDrawContext.fastBundle = et.finish(),
        j.addBundle(this._currentDrawContext.fastBundle)),
        this._reportDrawCall()
    }
    ,
    e.prototype.drawElementsType = function(i, o, s, c) {
        c === void 0 && (c = 1),
        this._draw(0, i, o, s, c)
    }
    ,
    e.prototype.drawArraysType = function(i, o, s, c) {
        c === void 0 && (c = 1),
        this._currentIndexBuffer = null,
        this._draw(1, i, o, s, c)
    }
    ,
    e.prototype.dispose = function() {
        var i, o, s;
        (i = this._mainTexture) === null || i === void 0 || i.destroy(),
        (o = this._mainTextureLastCopy) === null || o === void 0 || o.destroy(),
        (s = this._depthTexture) === null || s === void 0 || s.destroy(),
        a.prototype.dispose.call(this)
    }
    ,
    e.prototype.getRenderWidth = function(i) {
        return i === void 0 && (i = !1),
        !i && this._currentRenderTarget ? this._currentRenderTarget.width : this._canvas.width
    }
    ,
    e.prototype.getRenderHeight = function(i) {
        return i === void 0 && (i = !1),
        !i && 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(i) {}
    ,
    e.prototype._bindTextureDirectly = function(i, o, s, c) {
        return !1
    }
    ,
    e.prototype.areAllEffectsReady = function() {
        return !0
    }
    ,
    e.prototype._executeWhenRenderingStateIsCompiled = function(i, o) {
        o()
    }
    ,
    e.prototype._isRenderingStateCompiled = function(i) {
        return !0
    }
    ,
    e.prototype._getUnpackAlignement = function() {
        return 1
    }
    ,
    e.prototype._unpackFlipY = function(i) {}
    ,
    e.prototype._bindUnboundFramebuffer = function(i) {
        throw "_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"
    }
    ,
    e.prototype._getSamplingParameters = function(i, o) {
        throw "_getSamplingParameters is not available in WebGPU"
    }
    ,
    e.prototype.getUniforms = function(i, o) {
        return []
    }
    ,
    e.prototype.setIntArray = function(i, o) {
        return !1
    }
    ,
    e.prototype.setIntArray2 = function(i, o) {
        return !1
    }
    ,
    e.prototype.setIntArray3 = function(i, o) {
        return !1
    }
    ,
    e.prototype.setIntArray4 = function(i, o) {
        return !1
    }
    ,
    e.prototype.setArray = function(i, o) {
        return !1
    }
    ,
    e.prototype.setArray2 = function(i, o) {
        return !1
    }
    ,
    e.prototype.setArray3 = function(i, o) {
        return !1
    }
    ,
    e.prototype.setArray4 = function(i, o) {
        return !1
    }
    ,
    e.prototype.setMatrices = function(i, o) {
        return !1
    }
    ,
    e.prototype.setMatrix3x3 = function(i, o) {
        return !1
    }
    ,
    e.prototype.setMatrix2x2 = function(i, o) {
        return !1
    }
    ,
    e.prototype.setFloat = function(i, o) {
        return !1
    }
    ,
    e.prototype.setFloat2 = function(i, o, s) {
        return !1
    }
    ,
    e.prototype.setFloat3 = function(i, o, s, c) {
        return !1
    }
    ,
    e.prototype.setFloat4 = function(i, o, s, c, d) {
        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(a, e) {
    if (e === void 0 && (e = !1),
    !(this._alphaMode === a && (a === 0 && !this._alphaState.alphaBlend || a !== 0 && this._alphaState.alphaBlend))) {
        switch (a) {
        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(a === Engine.ALPHA_DISABLE),
        this._cacheRenderPipeline.setDepthWriteEnabled(a === Engine.ALPHA_DISABLE)),
        this._alphaMode = a,
        this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),
        this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters)
    }
}
;
WebGPUEngine.prototype.setAlphaEquation = function(a) {
    Engine.prototype.setAlphaEquation.call(this, a),
    this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters)
}
;
var ComputeEffect = function() {
    function a(e, i, o, s) {
        var c = this;
        s === void 0 && (s = "");
        var d, _;
        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 = s,
        this._engine = o,
        this.uniqueId = a._uniqueIdSeed++,
        this.defines = (d = i.defines) !== null && d !== void 0 ? d : "",
        this.onError = i.onError,
        this.onCompiled = i.onCompiled,
        this._entryPoint = (_ = i.entryPoint) !== null && _ !== void 0 ? _ : "main",
        this._shaderStore = ShaderStore.GetShadersStore(this._shaderLanguage),
        this._shaderRepository = ShaderStore.GetShadersRepository(this._shaderLanguage),
        this._includeShaderStore = ShaderStore.GetIncludesShadersStore(this._shaderLanguage);
        var b, k = IsWindowObjectExist() ? this._engine.getHostDocument() : null;
        e.computeSource ? b = "source:" + e.computeSource : e.computeElement ? (b = k ? k.getElementById(e.computeElement) : null,
        b || (b = e.computeElement)) : b = e.compute || e;
        var j = {
            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(b, "Compute", "", function($) {
            ShaderProcessor.Initialize(j),
            ShaderProcessor.PreProcess($, j, function(_e) {
                c._rawComputeSourceCode = $,
                i.processFinalCode && (_e = i.processFinalCode(_e));
                var et = ShaderProcessor.Finalize(_e, "", j);
                c._useFinalCode(et.vertexCode, e)
            }, c._engine)
        })
    }
    return a.prototype._useFinalCode = function(e, i) {
        if (i) {
            var o = i.computeElement || i.compute || i.spectorName || i;
            this._computeSourceCode = "//#define SHADER_NAME compute:" + o + `
` + e
        } else
            this._computeSourceCode = e;
        this._prepareEffect()
    }
    ,
    Object.defineProperty(a.prototype, "key", {
        get: function() {
            return this._key
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.isReady = function() {
        try {
            return this._isReadyInternal()
        } catch {
            return !1
        }
    }
    ,
    a.prototype._isReadyInternal = function() {
        return this._isReady ? !0 : this._pipelineContext ? this._pipelineContext.isReady : !1
    }
    ,
    a.prototype.getEngine = function() {
        return this._engine
    }
    ,
    a.prototype.getPipelineContext = function() {
        return this._pipelineContext
    }
    ,
    a.prototype.getCompilationError = function() {
        return this._compilationError
    }
    ,
    a.prototype.executeWhenCompiled = function(e) {
        var i = this;
        if (this.isReady()) {
            e(this);
            return
        }
        this.onCompileObservable.add(function(o) {
            e(o)
        }),
        (!this._pipelineContext || this._pipelineContext.isAsync) && setTimeout(function() {
            i._checkIsReady(null)
        }, 16)
    }
    ,
    a.prototype._checkIsReady = function(e) {
        var i = this;
        try {
            if (this._isReadyInternal())
                return
        } catch (o) {
            this._processCompilationErrors(o, e);
            return
        }
        setTimeout(function() {
            i._checkIsReady(e)
        }, 16)
    }
    ,
    a.prototype._loadShader = function(e, i, o, s) {
        if (typeof HTMLElement != "undefined" && e instanceof HTMLElement) {
            var c = GetDOMTextContent(e);
            s(c);
            return
        }
        if (e.substr(0, 7) === "source:") {
            s(e.substr(7));
            return
        }
        if (e.substr(0, 7) === "base64:") {
            var d = window.atob(e.substr(7));
            s(d);
            return
        }
        if (this._shaderStore[e + i + "Shader"]) {
            s(this._shaderStore[e + i + "Shader"]);
            return
        }
        if (o && this._shaderStore[e + o + "Shader"]) {
            s(this._shaderStore[e + o + "Shader"]);
            return
        }
        var _;
        e[0] === "." || e[0] === "/" || e.indexOf("http") > -1 ? _ = e : _ = this._shaderRepository + e,
        this._engine._loadFile(_ + "." + i.toLowerCase() + ".fx", s)
    }
    ,
    Object.defineProperty(a.prototype, "computeSourceCode", {
        get: function() {
            var e, i;
            return this._computeSourceCodeOverride ? this._computeSourceCodeOverride : (i = (e = this._pipelineContext) === null || e === void 0 ? void 0 : e._getComputeShaderCode()) !== null && i !== void 0 ? i : this._computeSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rawComputeSourceCode", {
        get: function() {
            return this._rawComputeSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._prepareEffect = function() {
        var e = this
          , i = this.defines
          , o = this._pipelineContext;
        this._isReady = !1;
        try {
            var s = this._engine;
            this._pipelineContext = s.createComputePipelineContext(),
            this._pipelineContext._name = this._key,
            s._prepareComputePipelineContext(this._pipelineContext, this._computeSourceCodeOverride ? this._computeSourceCodeOverride : this._computeSourceCode, this._rawComputeSourceCode, this._computeSourceCodeOverride ? null : i, this._entryPoint),
            s._executeWhenComputeStateIsCompiled(this._pipelineContext, function() {
                e._compilationError = "",
                e._isReady = !0,
                e.onCompiled && e.onCompiled(e),
                e.onCompileObservable.notifyObservers(e),
                e.onCompileObservable.clear(),
                o && e.getEngine()._deleteComputePipelineContext(o)
            }),
            this._pipelineContext.isAsync && this._checkIsReady(o)
        } catch (c) {
            this._processCompilationErrors(c, o)
        }
    }
    ,
    a.prototype._getShaderCodeAndErrorLine = function(e, i) {
        var o = /COMPUTE SHADER ERROR: 0:(\d+?):/
          , s = null;
        if (i && e) {
            var c = i.match(o);
            if (c && c.length === 2) {
                var d = parseInt(c[1])
                  , _ = e.split(`
`, -1);
                _.length >= d && (s = "Offending line [" + d + "] in compute code: " + _[d - 1])
            }
        }
        return [e, s]
    }
    ,
    a.prototype._processCompilationErrors = function(e, i) {
        var o, s;
        if (i === void 0 && (i = null),
        this._compilationError = e.message,
        Logger$2.Error("Unable to compile compute effect:"),
        Logger$2.Error(`Defines:\r
` + this.defines),
        a.LogShaderCodeOnCompilationError) {
            var c = null
              , d = null;
            !((s = this._pipelineContext) === null || s === void 0) && s._getComputeShaderCode() && (o = this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(), this._compilationError),
            d = o[0],
            c = o[1],
            d && (Logger$2.Error("Compute code:"),
            Logger$2.Error(d))),
            c && Logger$2.Error(c)
        }
        Logger$2.Error("Error: " + this._compilationError),
        i && (this._pipelineContext = i,
        this._isReady = !0,
        this.onError && this.onError(this, this._compilationError),
        this.onErrorObservable.notifyObservers(this))
    }
    ,
    a.prototype.dispose = function() {
        this._pipelineContext && this._pipelineContext.dispose(),
        this._engine._releaseComputeEffect(this)
    }
    ,
    a.RegisterShader = function(e, i) {
        ShaderStore.GetShadersStore(ShaderLanguage.WGSL)[e + "ComputeShader"] = i
    }
    ,
    a._uniqueIdSeed = 0,
    a.LogShaderCodeOnCompilationError = !0,
    a
}()
  , WebGPUComputeContext = function() {
    function a(e, i) {
        this._device = e,
        this._cacheSampler = i,
        this.uniqueId = a._Counter++,
        this._bindGroupEntries = [],
        this.clear()
    }
    return a.prototype.getBindGroups = function(e, i, o) {
        if (!o)
            throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");
        if (this._bindGroups.length === 0) {
            var s = this._bindGroupEntries.length > 0;
            for (var c in e) {
                var d = e[c]
                  , _ = o[c]
                  , b = _.group
                  , k = _.binding
                  , j = d.type
                  , $ = d.object
                  , _e = d.indexInGroupEntries
                  , et = this._bindGroupEntries[b];
                switch (et || (et = this._bindGroupEntries[b] = []),
                j) {
                case ComputeBindingType.Sampler:
                    {
                        var tt = $;
                        _e !== void 0 && s ? et[_e].resource = this._cacheSampler.getSampler(tt) : (d.indexInGroupEntries = et.length,
                        et.push({
                            binding: k,
                            resource: this._cacheSampler.getSampler(tt)
                        }));
                        break
                    }
                case ComputeBindingType.Texture:
                case ComputeBindingType.TextureWithoutSampler:
                    {
                        var rt = $
                          , it = rt._texture._hardwareTexture;
                        _e !== void 0 && s ? (j === ComputeBindingType.Texture && (et[_e++].resource = this._cacheSampler.getSampler(rt._texture)),
                        et[_e].resource = it.view) : (d.indexInGroupEntries = et.length,
                        j === ComputeBindingType.Texture && et.push({
                            binding: k - 1,
                            resource: this._cacheSampler.getSampler(rt._texture)
                        }),
                        et.push({
                            binding: k,
                            resource: it.view
                        }));
                        break
                    }
                case ComputeBindingType.StorageTexture:
                    {
                        var rt = $
                          , it = rt._texture._hardwareTexture;
                        (it.textureAdditionalUsages & TextureUsage.StorageBinding) === 0 && Logger$2.Error("computeDispatch: The texture (name=" + rt.name + ", uniqueId=" + rt.uniqueId + ") is not a storage texture!", 50),
                        _e !== void 0 && s ? et[_e].resource = it.view : (d.indexInGroupEntries = et.length,
                        et.push({
                            binding: k,
                            resource: it.view
                        }));
                        break
                    }
                case ComputeBindingType.UniformBuffer:
                case ComputeBindingType.StorageBuffer:
                    {
                        var nt = (j === ComputeBindingType.UniformBuffer,
                        $)
                          , ot = nt.getBuffer()
                          , at = ot.underlyingResource;
                        _e !== void 0 && s ? (et[_e].resource.buffer = at,
                        et[_e].resource.size = ot.capacity) : (d.indexInGroupEntries = et.length,
                        et.push({
                            binding: k,
                            resource: {
                                buffer: at,
                                offset: 0,
                                size: ot.capacity
                            }
                        }));
                        break
                    }
                }
            }
            for (var st = 0; st < this._bindGroupEntries.length; ++st) {
                var et = this._bindGroupEntries[st];
                if (!et) {
                    this._bindGroups[st] = void 0;
                    continue
                }
                this._bindGroups[st] = this._device.createBindGroup({
                    layout: i.getBindGroupLayout(st),
                    entries: et
                })
            }
            this._bindGroups.length = this._bindGroupEntries.length
        }
        return this._bindGroups
    }
    ,
    a.prototype.clear = function() {
        this._bindGroups = []
    }
    ,
    a._Counter = 0,
    a
}()
  , WebGPUComputePipelineContext = function() {
    function a(e) {
        this._name = "unnamed",
        this.engine = e
    }
    return Object.defineProperty(a.prototype, "isAsync", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isReady", {
        get: function() {
            return !!this.stage
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._getComputeShaderCode = function() {
        var e;
        return (e = this.sources) === null || e === void 0 ? void 0 : e.compute
    }
    ,
    a.prototype.dispose = function() {}
    ,
    a
}();
WebGPUEngine.prototype.createComputeContext = function() {
    return new WebGPUComputeContext(this._device,this._cacheSampler)
}
;
WebGPUEngine.prototype.createComputeEffect = function(a, e) {
    var i = a.computeElement || a.compute || a.computeToken || a.computeSource || a
      , o = i + "@" + e.defines;
    if (this._compiledComputeEffects[o]) {
        var s = this._compiledComputeEffects[o];
        return e.onCompiled && s.isReady() && e.onCompiled(s),
        s
    }
    var c = new ComputeEffect(a,e,this,o);
    return this._compiledComputeEffects[o] = c,
    c
}
;
WebGPUEngine.prototype.createComputePipelineContext = function() {
    return new WebGPUComputePipelineContext(this)
}
;
WebGPUEngine.prototype.areAllComputeEffectsReady = function() {
    for (var a in this._compiledComputeEffects) {
        var e = this._compiledComputeEffects[a];
        if (!e.isReady())
            return !1
    }
    return !0
}
;
WebGPUEngine.prototype.computeDispatch = function(a, e, i, o, s, c, d) {
    var _ = this;
    if (this._currentRenderTarget) {
        this._onAfterUnbindFrameBufferObservable.addOnce(function() {
            _.computeDispatch(a, e, i, o, s, c, d)
        });
        return
    }
    var b = a._pipelineContext
      , k = e;
    b.computePipeline || (b.computePipeline = this._device.createComputePipeline({
        compute: b.stage
    }));
    var j = this._renderTargetEncoder
      , $ = j.beginComputePass();
    $.setPipeline(b.computePipeline);
    for (var _e = k.getBindGroups(i, b.computePipeline, d), et = 0; et < _e.length; ++et) {
        var tt = _e[et];
        !tt || $.setBindGroup(et, tt)
    }
    $.dispatch(o, s, c),
    $.endPass()
}
;
WebGPUEngine.prototype.releaseComputeEffects = function() {
    for (var a in this._compiledComputeEffects) {
        var e = this._compiledComputeEffects[a].getPipelineContext();
        this._deleteComputePipelineContext(e)
    }
    this._compiledComputeEffects = {}
}
;
WebGPUEngine.prototype._prepareComputePipelineContext = function(a, e, i, o, s) {
    var c = a;
    this.dbgShowShaderCode && (console.log(o),
    console.log(e)),
    c.sources = {
        compute: e,
        rawCompute: i
    },
    c.stage = this._createComputePipelineStageDescriptor(e, o, s)
}
;
WebGPUEngine.prototype._releaseComputeEffect = function(a) {
    this._compiledComputeEffects[a._key] && (delete this._compiledComputeEffects[a._key],
    this._deleteComputePipelineContext(a.getPipelineContext()))
}
;
WebGPUEngine.prototype._rebuildComputeEffects = function() {
    for (var a in this._compiledComputeEffects) {
        var e = this._compiledComputeEffects[a];
        e._pipelineContext = null,
        e._wasPreviouslyReady = !1,
        e._prepareEffect()
    }
}
;
WebGPUEngine.prototype._deleteComputePipelineContext = function(a) {
    var e = a;
    e && a.dispose()
}
;
WebGPUEngine.prototype._createComputePipelineStageDescriptor = function(a, e, i) {
    return e ? e = "//" + e.split(`
`).join(`
//`) + `
` : e = "",
    {
        module: this._device.createShaderModule({
            code: e + a
        }),
        entryPoint: i
    }
}
;
WebGPUEngine.prototype._createDepthStencilCubeTexture = function(a, e) {
    var i = new InternalTexture(this,InternalTextureSource.DepthStencil);
    i.isCube = !0;
    var o = __assign({
        bilinearFiltering: !1,
        comparisonFunction: 0,
        generateStencil: !1,
        samples: 1
    }, e);
    return i.format = o.generateStencil ? 13 : 14,
    this._setupDepthStencilTexture(i, a, o.generateStencil, o.bilinearFiltering, o.comparisonFunction, o.samples),
    this._textureHelper.createGPUTextureForInternalTexture(i),
    this._internalTexturesCache.push(i),
    i
}
;
WebGPUEngine.prototype.createCubeTexture = function(a, e, i, o, s, c, d, _, b, k, j, $, _e) {
    var et = this;
    return s === void 0 && (s = null),
    c === void 0 && (c = null),
    _ === void 0 && (_ = null),
    b === void 0 && (b = !1),
    k === void 0 && (k = 0),
    j === void 0 && (j = 0),
    $ === void 0 && ($ = null),
    _e === void 0 && (_e = !1),
    this.createCubeTextureBase(a, e, i, !!o, s, c, d, _, b, k, j, $, null, function(tt, rt) {
        var it = rt
          , nt = it[0].width
          , ot = nt;
        et._setCubeMapTextureParams(tt, !o),
        tt.format = d != null ? d : -1;
        var at = et._textureHelper.createGPUTextureForInternalTexture(tt, nt, ot);
        et._textureHelper.updateCubeTextures(it, at.underlyingResource, nt, ot, at.format, !1, !1, 0, 0, et._uploadEncoder),
        o || et._generateMipmaps(tt, et._uploadEncoder),
        tt.isReady = !0,
        tt.onLoadedObservable.notifyObservers(tt),
        tt.onLoadedObservable.clear(),
        s && s()
    }, !!_e)
}
;
WebGPUEngine.prototype._setCubeMapTextureParams = function(a, e) {
    a.samplingMode = e ? 3 : 2,
    a._cachedWrapU = 0,
    a._cachedWrapV = 0
}
;
WebGPUEngine.prototype._debugPushGroup = function(a, e) {
    if (!!this._options.enableGPUDebugMarkers)
        if (e === 0 || e === 1) {
            var i = e === 0 ? this._renderEncoder : this._renderTargetEncoder;
            i.pushDebugGroup(a)
        } else
            this._currentRenderPass ? this._currentRenderPass.pushDebugGroup(a) : this._pendingDebugCommands.push(["push", a])
}
;
WebGPUEngine.prototype._debugPopGroup = function(a) {
    if (!!this._options.enableGPUDebugMarkers)
        if (a === 0 || a === 1) {
            var e = a === 0 ? this._renderEncoder : this._renderTargetEncoder;
            e.popDebugGroup()
        } else
            this._currentRenderPass ? this._currentRenderPass.popDebugGroup() : this._pendingDebugCommands.push(["pop", null])
}
;
WebGPUEngine.prototype._debugInsertMarker = function(a, e) {
    if (!!this._options.enableGPUDebugMarkers)
        if (e === 0 || e === 1) {
            var i = e === 0 ? this._renderEncoder : this._renderTargetEncoder;
            i.insertDebugMarker(a)
        } else
            this._currentRenderPass ? this._currentRenderPass.insertDebugMarker(a) : this._pendingDebugCommands.push(["insert", a])
}
;
WebGPUEngine.prototype._debugFlushPendingCommands = function() {
    for (var a = 0; a < this._pendingDebugCommands.length; ++a) {
        var e = this._pendingDebugCommands[a]
          , i = e[0]
          , o = e[1];
        switch (i) {
        case "push":
            this._debugPushGroup(o);
            break;
        case "pop":
            this._debugPopGroup();
            break;
        case "insert":
            this._debugInsertMarker(o);
            break
        }
    }
    this._pendingDebugCommands.length = 0
}
;
WebGPUEngine.prototype.updateDynamicIndexBuffer = function(a, e, i) {
    i === void 0 && (i = 0);
    var o = a, s;
    e instanceof Uint16Array ? a.is32Bits ? s = Uint32Array.from(e) : s = e : e instanceof Uint32Array ? a.is32Bits ? s = e : s = Uint16Array.from(e) : a.is32Bits ? s = new Uint32Array(e) : s = new Uint16Array(e),
    this._bufferManager.setSubData(o, i, s)
}
;
WebGPUEngine.prototype.updateDynamicVertexBuffer = function(a, e, i, o) {
    var s = a;
    i === void 0 && (i = 0);
    var c;
    o === void 0 ? (e instanceof Array ? c = new Float32Array(e) : e instanceof ArrayBuffer ? c = new Uint8Array(e) : c = e,
    o = c.byteLength) : e instanceof Array ? c = new Float32Array(e) : e instanceof ArrayBuffer ? c = new Uint8Array(e) : c = e,
    this._bufferManager.setSubData(s, i, c, 0, o)
}
;
WebGPUEngine.prototype.updateDynamicTexture = function(a, e, i, o, s, c, d) {
    var _;
    if (o === void 0 && (o = !1),
    !!a) {
        var b = e.width
          , k = e.height
          , j = a._hardwareTexture;
        !((_ = a._hardwareTexture) === null || _ === void 0) && _.underlyingResource || (j = this._textureHelper.createGPUTextureForInternalTexture(a, b, k)),
        this._textureHelper.updateTexture(e, a, b, k, a.depth, j.format, 0, 0, i, o, 0, 0, this._uploadEncoder, d),
        a.generateMipMaps && this._generateMipmaps(a, this._uploadEncoder),
        a.isReady = !0
    }
}
;
var WebGPUExternalTexture = function(a) {
    __extends(e, a);
    function e(i) {
        return a.call(this, i) || this
    }
    return e
}(ExternalTexture);
Effect.prototype.setExternalTexture = function(a, e) {
    this._engine.setExternalTexture(a, e)
}
;
WebGPUEngine.prototype.createExternalTexture = function(a) {
    var e = new WebGPUExternalTexture(a);
    return e
}
;
WebGPUEngine.prototype.setExternalTexture = function(a, e) {
    if (!e) {
        this._currentMaterialContext.setTexture(a, null);
        return
    }
    this._setInternalTexture(a, e)
}
;
WebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer = function(a, e, i) {
    e === void 0 && (e = !1),
    i && i();
    var o = a._attachments
      , s = o.length;
    this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass && this._endRenderTargetRenderPass();
    for (var c = 0; c < s; c++) {
        var d = a.textures[c];
        d.generateMipMaps && !e && !d.isCube && this._generateMipmaps(d)
    }
    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(a, e, i) {
    var o, s = !1, c = !0, d = !1, _ = !1, b = 15, k = 1, j = 0, $ = 3, _e = new Array, et = new Array, tt = this._createHardwareRenderTargetWrapper(!0, !1, a);
    e !== void 0 && (s = e.generateMipMaps === void 0 ? !1 : e.generateMipMaps,
    c = e.generateDepthBuffer === void 0 ? !0 : e.generateDepthBuffer,
    d = e.generateStencilBuffer === void 0 ? !1 : e.generateStencilBuffer,
    _ = e.generateDepthTexture === void 0 ? !1 : e.generateDepthTexture,
    k = e.textureCount || 1,
    b = (o = e.depthTextureFormat) !== null && o !== void 0 ? o : 15,
    e.types && (_e = e.types),
    e.samplingModes && (et = e.samplingModes));
    var rt = a.width || a
      , it = a.height || a
      , nt = null;
    (c || d || _) && (nt = tt.createDepthStencilTexture(0, !1, d, 1, b));
    var ot = []
      , at = [];
    tt._generateDepthBuffer = c,
    tt._generateStencilBuffer = d,
    tt._attachments = at;
    for (var st = 0; st < k; st++) {
        var ut = et[st] || $
          , ct = _e[st] || j;
        (ct === 1 && !this._caps.textureFloatLinearFiltering || ct === 2 && !this._caps.textureHalfFloatLinearFiltering) && (ut = 1),
        ct === 1 && !this._caps.textureFloat && (ct = 0,
        Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));
        var lt = new InternalTexture(this,InternalTextureSource.MultiRenderTarget);
        ot.push(lt),
        at.push(st + 1),
        lt.baseWidth = rt,
        lt.baseHeight = it,
        lt.width = rt,
        lt.height = it,
        lt.isReady = !0,
        lt.samples = 1,
        lt.generateMipMaps = s,
        lt.samplingMode = ut,
        lt.type = ct,
        lt._cachedWrapU = 0,
        lt._cachedWrapV = 0,
        this._internalTexturesCache.push(lt),
        this._textureHelper.createGPUTextureForInternalTexture(lt)
    }
    return nt && (nt.incrementReferences(),
    ot.push(nt),
    this._internalTexturesCache.push(nt)),
    tt.setTextures(ot),
    tt
}
;
WebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function(a, e) {
    if (!a || !a.textures || a.textures[0].samples === e)
        return e;
    var i = a._attachments.length;
    if (i === 0)
        return 1;
    e = Math.min(e, this.getCaps().maxMSAASamples);
    for (var o = 0; o < i; ++o) {
        var s = a.textures[o];
        this._textureHelper.createMSAATexture(s, e),
        s.samples = e
    }
    return a._depthStencilTexture && a._depthStencilTexture !== a.textures[a.textures.length - 1] && (this._textureHelper.createMSAATexture(a._depthStencilTexture, e),
    a._depthStencilTexture.samples = e),
    e
}
;
WebGPUEngine.prototype.bindAttachments = function(a) {
    a.length === 0 || !this._currentRenderTarget || (this._mrtAttachments = a)
}
;
WebGPUEngine.prototype.buildTextureLayout = function(a) {
    for (var e = [], i = 0; i < a.length; i++)
        a[i] ? e.push(i + 1) : e.push(0);
    return e
}
;
WebGPUEngine.prototype.restoreSingleAttachment = function() {}
;
WebGPUEngine.prototype.getGPUFrameTimeCounter = function() {
    return this._timestampQuery.gpuFrameTimeCounter
}
;
WebGPUEngine.prototype.captureGPUFrameTime = function(a) {
    this._timestampQuery.enable = a && !!this._caps.timerQuery
}
;
WebGPUEngine.prototype.createQuery = function() {
    return this._occlusionQuery.createQuery()
}
;
WebGPUEngine.prototype.deleteQuery = function(a) {
    return this._occlusionQuery.deleteQuery(a),
    this
}
;
WebGPUEngine.prototype.isQueryResultAvailable = function(a) {
    return this._occlusionQuery.isQueryResultAvailable(a)
}
;
WebGPUEngine.prototype.getQueryResult = function(a) {
    return this._occlusionQuery.getQueryResult(a)
}
;
WebGPUEngine.prototype.beginOcclusionQuery = function(a, e) {
    var i;
    if (this.compatibilityMode) {
        if (this._occlusionQuery.canBeginQuery)
            return (i = this._currentRenderPass) === null || i === void 0 || i.beginOcclusionQuery(e),
            !0
    } else {
        var o = this._getCurrentRenderPassIndex()
          , s = o === 0 ? this._bundleList : this._bundleListRenderTarget;
        return s.addItem(new WebGPURenderItemBeginOcclusionQuery(e)),
        !0
    }
    return !1
}
;
WebGPUEngine.prototype.endOcclusionQuery = function(a) {
    var e;
    if (this.compatibilityMode)
        (e = this._currentRenderPass) === null || e === void 0 || e.endOcclusionQuery();
    else {
        var i = this._getCurrentRenderPassIndex()
          , o = i === 0 ? this._bundleList : this._bundleListRenderTarget;
        o.addItem(new WebGPURenderItemEndOcclusionQuery)
    }
    return this
}
;
WebGPUEngine.prototype.createRawTexture = function(a, e, i, o, s, c, d, _, b, k) {
    _ === void 0 && (_ = null),
    b === void 0 && (b = 0),
    k === void 0 && (k = 0);
    var j = new InternalTexture(this,InternalTextureSource.Raw);
    return j.baseWidth = e,
    j.baseHeight = i,
    j.width = e,
    j.height = i,
    j.format = o,
    j.generateMipMaps = s,
    j.samplingMode = d,
    j.invertY = c,
    j._compression = _,
    j.type = b,
    this._doNotHandleContextLost || (j._bufferView = a),
    this._textureHelper.createGPUTextureForInternalTexture(j, e, i, void 0, k),
    this.updateRawTexture(j, a, o, c, _, b),
    this._internalTexturesCache.push(j),
    j
}
;
WebGPUEngine.prototype.updateRawTexture = function(a, e, i, o, s, c) {
    if (s === void 0 && (s = null),
    c === void 0 && (c = 0),
    !!a) {
        if (this._doNotHandleContextLost || (a._bufferView = e,
        a.invertY = o,
        a._compression = s),
        e) {
            var d = a._hardwareTexture
              , _ = i === 4;
            _ && (e = _convertRGBtoRGBATextureData(e, a.width, a.height, c));
            var b = new Uint8Array(e.buffer,e.byteOffset,e.byteLength);
            this._textureHelper.updateTexture(b, a, a.width, a.height, a.depth, d.format, 0, 0, o, !1, 0, 0, this._uploadEncoder),
            a.generateMipMaps && this._generateMipmaps(a, this._uploadEncoder)
        }
        a.isReady = !0
    }
}
;
WebGPUEngine.prototype.createRawCubeTexture = function(a, e, i, o, s, c, d, _) {
    _ === void 0 && (_ = null);
    var b = new InternalTexture(this,InternalTextureSource.CubeRaw);
    return o === 1 && !this._caps.textureFloatLinearFiltering ? (s = !1,
    d = 1,
    Logger$2.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")) : o === 2 && !this._caps.textureHalfFloatLinearFiltering ? (s = !1,
    d = 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.")) : o === 1 && !this._caps.textureFloatRender ? (s = !1,
    Logger$2.Warn("Render to float textures is not supported. Mipmap generation forced to false.")) : o === 2 && !this._caps.colorBufferFloat && (s = !1,
    Logger$2.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")),
    b.isCube = !0,
    b.format = i === 4 ? 5 : i,
    b.type = o,
    b.generateMipMaps = s,
    b.width = e,
    b.height = e,
    b.samplingMode = d,
    this._doNotHandleContextLost || (b._bufferViewArray = a),
    b._cachedWrapU = 0,
    b._cachedWrapV = 0,
    this._textureHelper.createGPUTextureForInternalTexture(b),
    a && this.updateRawCubeTexture(b, a, i, o, c, _),
    b
}
;
WebGPUEngine.prototype.updateRawCubeTexture = function(a, e, i, o, s, c, d) {
    c === void 0 && (c = null),
    a._bufferViewArray = e,
    a.invertY = s,
    a._compression = c;
    for (var _ = a._hardwareTexture, b = i === 4, k = [], j = 0; j < e.length; ++j) {
        var $ = e[j];
        b && ($ = _convertRGBtoRGBATextureData(e[j], a.width, a.height, o)),
        k.push(new Uint8Array($.buffer,$.byteOffset,$.byteLength))
    }
    this._textureHelper.updateCubeTextures(k, _.underlyingResource, a.width, a.height, _.format, s, !1, 0, 0, this._uploadEncoder),
    a.generateMipMaps && this._generateMipmaps(a, this._uploadEncoder),
    a.isReady = !0
}
;
WebGPUEngine.prototype.createRawCubeTextureFromUrl = function(a, e, i, o, s, c, d, _, b, k, j, $) {
    var _e = this;
    b === void 0 && (b = null),
    k === void 0 && (k = null),
    j === void 0 && (j = 3),
    $ === void 0 && ($ = !1);
    var et = this.createRawCubeTexture(null, i, o, s, !c, $, j, null);
    e == null || e._addPendingData(et),
    et.url = a,
    this._internalTexturesCache.push(et);
    var tt = function(it, nt) {
        e == null || e._removePendingData(et),
        k && it && k(it.status + " " + it.statusText, nt)
    }
      , rt = function(it) {
        var nt = et.width
          , ot = d(it);
        if (!!ot) {
            var at = [0, 2, 4, 1, 3, 5];
            if (_)
                for (var st = o === 4, ut = _(ot), ct = et._hardwareTexture, lt = [0, 1, 2, 3, 4, 5], ft = 0; ft < ut.length; ft++) {
                    for (var ht = nt >> ft, pt = [], dt = 0; dt < 6; dt++) {
                        var _t = ut[ft][lt[dt]];
                        st && (_t = _convertRGBtoRGBATextureData(_t, ht, ht, s)),
                        pt.push(new Uint8Array(_t.buffer,_t.byteOffset,_t.byteLength))
                    }
                    _e._textureHelper.updateCubeTextures(pt, ct.underlyingResource, ht, ht, ct.format, $, !1, 0, 0, _e._uploadEncoder)
                }
            else {
                for (var pt = [], dt = 0; dt < 6; dt++)
                    pt.push(ot[at[dt]]);
                _e.updateRawCubeTexture(et, pt, o, s, $)
            }
            et.isReady = !0,
            e == null || e._removePendingData(et),
            b && b()
        }
    };
    return this._loadFile(a, function(it) {
        rt(it)
    }, void 0, e == null ? void 0 : e.offlineProvider, !0, tt),
    et
}
;
WebGPUEngine.prototype.createRawTexture3D = function(a, e, i, o, s, c, d, _, b, k, j) {
    b === void 0 && (b = null),
    k === void 0 && (k = 0),
    j === void 0 && (j = 0);
    var $ = InternalTextureSource.Raw3D
      , _e = new InternalTexture(this,$);
    return _e.baseWidth = e,
    _e.baseHeight = i,
    _e.baseDepth = o,
    _e.width = e,
    _e.height = i,
    _e.depth = o,
    _e.format = s,
    _e.type = k,
    _e.generateMipMaps = c,
    _e.samplingMode = _,
    _e.is3D = !0,
    this._doNotHandleContextLost || (_e._bufferView = a),
    this._textureHelper.createGPUTextureForInternalTexture(_e, e, i, void 0, j),
    this.updateRawTexture3D(_e, a, s, d, b, k),
    this._internalTexturesCache.push(_e),
    _e
}
;
WebGPUEngine.prototype.updateRawTexture3D = function(a, e, i, o, s, c) {
    if (s === void 0 && (s = null),
    c === void 0 && (c = 0),
    this._doNotHandleContextLost || (a._bufferView = e,
    a.format = i,
    a.invertY = o,
    a._compression = s),
    e) {
        var d = a._hardwareTexture
          , _ = i === 4;
        _ && (e = _convertRGBtoRGBATextureData(e, a.width, a.height, c));
        var b = new Uint8Array(e.buffer,e.byteOffset,e.byteLength);
        this._textureHelper.updateTexture(b, a, a.width, a.height, a.depth, d.format, 0, 0, o, !1, 0, 0, this._uploadEncoder),
        a.generateMipMaps && this._generateMipmaps(a, this._uploadEncoder)
    }
    a.isReady = !0
}
;
WebGPUEngine.prototype.createRawTexture2DArray = function(a, e, i, o, s, c, d, _, b, k, j) {
    b === void 0 && (b = null),
    k === void 0 && (k = 0),
    j === void 0 && (j = 0);
    var $ = InternalTextureSource.Raw2DArray
      , _e = new InternalTexture(this,$);
    return _e.baseWidth = e,
    _e.baseHeight = i,
    _e.baseDepth = o,
    _e.width = e,
    _e.height = i,
    _e.depth = o,
    _e.format = s,
    _e.type = k,
    _e.generateMipMaps = c,
    _e.samplingMode = _,
    _e.is2DArray = !0,
    this._doNotHandleContextLost || (_e._bufferView = a),
    this._textureHelper.createGPUTextureForInternalTexture(_e, e, i, o, j),
    this.updateRawTexture2DArray(_e, a, s, d, b, k),
    this._internalTexturesCache.push(_e),
    _e
}
;
WebGPUEngine.prototype.updateRawTexture2DArray = function(a, e, i, o, s, c) {
    if (s === void 0 && (s = null),
    c === void 0 && (c = 0),
    this._doNotHandleContextLost || (a._bufferView = e,
    a.format = i,
    a.invertY = o,
    a._compression = s),
    e) {
        var d = a._hardwareTexture
          , _ = i === 4;
        _ && (e = _convertRGBtoRGBATextureData(e, a.width, a.height, c));
        var b = new Uint8Array(e.buffer,e.byteOffset,e.byteLength);
        this._textureHelper.updateTexture(b, a, a.width, a.height, a.depth, d.format, 0, 0, o, !1, 0, 0, this._uploadEncoder),
        a.generateMipMaps && this._generateMipmaps(a, this._uploadEncoder)
    }
    a.isReady = !0
}
;
function _convertRGBtoRGBATextureData(a, e, i, o) {
    var s, c = 1;
    o === 1 ? s = new Float32Array(e * i * 4) : o === 2 ? (s = new Uint16Array(e * i * 4),
    c = 15360) : o === 7 ? s = new Uint32Array(e * i * 4) : s = new Uint8Array(e * i * 4);
    for (var d = 0; d < e; d++)
        for (var _ = 0; _ < i; _++) {
            var b = (_ * e + d) * 3
              , k = (_ * e + d) * 4;
            s[k + 0] = a[b + 0],
            s[k + 1] = a[b + 1],
            s[k + 2] = a[b + 2],
            s[k + 3] = c
        }
    return s
}
WebGPUEngine.prototype._readTexturePixels = function(a, e, i, o, s, c, d, _) {
    o === void 0 && (o = -1),
    s === void 0 && (s = 0),
    c === void 0 && (c = null),
    d === void 0 && (d = !0),
    _ === void 0 && (_ = !1);
    var b = a._hardwareTexture;
    return d && this.flushFramebuffer(),
    this._textureHelper.readPixels(b.underlyingResource, 0, 0, e, i, b.format, o, s, c, _)
}
;
WebGPUEngine.prototype._readTexturePixelsSync = function(a, e, i, o, s, c, d, _) {
    throw "_readTexturePixelsSync is unsupported in WebGPU!"
}
;
WebGPUEngine.prototype._createHardwareRenderTargetWrapper = function(a, e, i) {
    var o = new RenderTargetWrapper(a,e,i,this);
    return this._renderTargetWrapperCache.push(o),
    o
}
;
WebGPUEngine.prototype.createRenderTargetTexture = function(a, e) {
    var i = this._createHardwareRenderTargetWrapper(!1, !1, a)
      , o = {};
    e !== void 0 && typeof e == "object" ? (o.generateDepthBuffer = e.generateDepthBuffer === void 0 ? !0 : e.generateDepthBuffer,
    o.generateStencilBuffer = o.generateDepthBuffer && e.generateStencilBuffer) : (o.generateDepthBuffer = !0,
    o.generateStencilBuffer = !1);
    var s = this._createInternalTexture(a, e, !0, InternalTextureSource.RenderTarget);
    return i._generateDepthBuffer = o.generateDepthBuffer,
    i._generateStencilBuffer = !!o.generateStencilBuffer,
    i.setTextures(s),
    (i._generateDepthBuffer || i._generateStencilBuffer) && i.createDepthStencilTexture(0, o.samplingMode === void 0 || o.samplingMode === 2 || o.samplingMode === 2 || o.samplingMode === 3 || o.samplingMode === 3 || o.samplingMode === 5 || o.samplingMode === 6 || o.samplingMode === 7 || o.samplingMode === 11, i._generateStencilBuffer, i.samples),
    e !== void 0 && typeof e == "object" && e.createMipMaps && !o.generateMipMaps && (s.generateMipMaps = !0),
    this._textureHelper.createGPUTextureForInternalTexture(s, void 0, void 0, void 0, o.creationFlags),
    e !== void 0 && typeof e == "object" && e.createMipMaps && !o.generateMipMaps && (s.generateMipMaps = !1),
    i
}
;
WebGPUEngine.prototype._createDepthStencilTexture = function(a, e, i) {
    var o = new InternalTexture(this,InternalTextureSource.DepthStencil)
      , s = __assign({
        bilinearFiltering: !1,
        comparisonFunction: 0,
        generateStencil: !1,
        samples: 1,
        depthTextureFormat: 15
    }, e);
    return o.format = s.generateStencil ? 13 : s.depthTextureFormat === 15 ? 14 : s.depthTextureFormat,
    this._setupDepthStencilTexture(o, a, s.generateStencil, s.bilinearFiltering, s.comparisonFunction, s.samples),
    this._textureHelper.createGPUTextureForInternalTexture(o),
    this._internalTexturesCache.push(o),
    o
}
;
WebGPUEngine.prototype._setupDepthStencilTexture = function(a, e, i, o, s, c) {
    c === void 0 && (c = 1);
    var d = e.width || e
      , _ = e.height || e
      , b = e.layers || 0;
    a.baseWidth = d,
    a.baseHeight = _,
    a.width = d,
    a.height = _,
    a.is2DArray = b > 0,
    a.depth = b,
    a.isReady = !0,
    a.samples = c,
    a.generateMipMaps = !1,
    a.samplingMode = o ? 2 : 1,
    a.type = 1,
    a._comparisonFunction = s,
    a._cachedWrapU = 0,
    a._cachedWrapV = 0
}
;
WebGPUEngine.prototype.updateRenderTargetTextureSampleCount = function(a, e) {
    return !a || !a.texture || a.samples === e || (e = Math.min(e, this.getCaps().maxMSAASamples),
    this._textureHelper.createMSAATexture(a.texture, e),
    a._depthStencilTexture && (this._textureHelper.createMSAATexture(a._depthStencilTexture, e),
    a._depthStencilTexture.samples = e),
    a.texture.samples = e),
    e
}
;
WebGPUEngine.prototype.createRenderTargetCubeTexture = function(a, e) {
    var i = this._createHardwareRenderTargetWrapper(!1, !0, a)
      , o = __assign({
        generateMipMaps: !0,
        generateDepthBuffer: !0,
        generateStencilBuffer: !1,
        type: 0,
        samplingMode: 3,
        format: 5,
        samples: 1
    }, e);
    o.generateStencilBuffer = o.generateDepthBuffer && o.generateStencilBuffer,
    i._generateDepthBuffer = o.generateDepthBuffer,
    i._generateStencilBuffer = o.generateStencilBuffer;
    var s = new InternalTexture(this,InternalTextureSource.RenderTarget);
    return s.width = a,
    s.height = a,
    s.depth = 0,
    s.isReady = !0,
    s.isCube = !0,
    s.samples = o.samples,
    s.generateMipMaps = o.generateMipMaps,
    s.samplingMode = o.samplingMode,
    s.type = o.type,
    s.format = o.format,
    this._internalTexturesCache.push(s),
    i.setTextures(s),
    (i._generateDepthBuffer || i._generateStencilBuffer) && i.createDepthStencilTexture(0, o.samplingMode === void 0 || o.samplingMode === 2 || o.samplingMode === 2 || o.samplingMode === 3 || o.samplingMode === 3 || o.samplingMode === 5 || o.samplingMode === 6 || o.samplingMode === 7 || o.samplingMode === 11, i._generateStencilBuffer, i.samples),
    e && e.createMipMaps && !o.generateMipMaps && (s.generateMipMaps = !0),
    this._textureHelper.createGPUTextureForInternalTexture(s),
    e && e.createMipMaps && !o.generateMipMaps && (s.generateMipMaps = !1),
    i
}
;
Effect.prototype.setTextureSampler = function(a, e) {
    this._engine.setTextureSampler(a, e)
}
;
WebGPUEngine.prototype.setTextureSampler = function(a, e) {
    var i;
    (i = this._currentMaterialContext) === null || i === void 0 || i.setSampler(a, e)
}
;
Effect.prototype.setStorageBuffer = function(a, e) {
    this._engine.setStorageBuffer(a, e)
}
;
WebGPUEngine.prototype.createStorageBuffer = function(a, e) {
    return this._createBuffer(a, e | 32)
}
;
WebGPUEngine.prototype.updateStorageBuffer = function(a, e, i, o) {
    var s = a;
    i === void 0 && (i = 0);
    var c;
    o === void 0 ? (e instanceof Array ? c = new Float32Array(e) : e instanceof ArrayBuffer ? c = new Uint8Array(e) : c = e,
    o = c.byteLength) : e instanceof Array ? c = new Float32Array(e) : e instanceof ArrayBuffer ? c = new Uint8Array(e) : c = e,
    this._bufferManager.setSubData(s, i, c, 0, o)
}
;
WebGPUEngine.prototype.readFromStorageBuffer = function(a, e, i, o) {
    var s = this;
    i = i || a.capacity;
    var c = this._bufferManager.createRawBuffer(i, BufferUsage.MapRead | BufferUsage.CopyDst);
    return this._renderTargetEncoder.copyBufferToBuffer(a.underlyingResource, e != null ? e : 0, c, 0, i),
    new Promise(function(d, _) {
        s.onEndFrameObservable.addOnce(function() {
            c.mapAsync(MapMode.Read, 0, i).then(function() {
                var b = c.getMappedRange(0, i)
                  , k = o;
                if (k === void 0)
                    k = new Uint8Array(i),
                    k.set(new Uint8Array(b));
                else {
                    var j = k.constructor;
                    k = new j(k.buffer),
                    k.set(new j(b))
                }
                c.unmap(),
                s._bufferManager.releaseBuffer(c),
                d(k)
            }, function(b) {
                return _(b)
            })
        })
    }
    )
}
;
WebGPUEngine.prototype.setStorageBuffer = function(a, e) {
    var i, o;
    (i = this._currentDrawContext) === null || i === void 0 || i.setBuffer(a, (o = e == null ? void 0 : e.getBuffer()) !== null && o !== void 0 ? o : null)
}
;
WebGPUEngine.prototype.createUniformBuffer = function(a) {
    var e;
    a instanceof Array ? e = new Float32Array(a) : e = a;
    var i = this._bufferManager.createBuffer(e, BufferUsage.Uniform | BufferUsage.CopyDst);
    return i
}
;
WebGPUEngine.prototype.createDynamicUniformBuffer = function(a) {
    return this.createUniformBuffer(a)
}
;
WebGPUEngine.prototype.updateUniformBuffer = function(a, e, i, o) {
    i === void 0 && (i = 0);
    var s = a, c;
    o === void 0 ? (e instanceof Float32Array ? c = e : c = new Float32Array(e),
    o = c.byteLength) : e instanceof Float32Array ? c = e : c = new Float32Array(e),
    this._bufferManager.setSubData(s, i, c, 0, o)
}
;
WebGPUEngine.prototype.bindUniformBufferBase = function(a, e, i) {
    this._currentDrawContext.setBuffer(i, a)
}
;
WebGPUEngine.prototype.bindUniformBlock = function(a, e, i) {}
;
WebGPUEngine.prototype.updateVideoTexture = function(a, e, i) {
    var o = this, s;
    if (!(!a || a._isDisabled)) {
        this._videoTextureSupported === void 0 && (this._videoTextureSupported = !0);
        var c = a._hardwareTexture;
        !((s = a._hardwareTexture) === null || s === void 0) && s.underlyingResource || (c = this._textureHelper.createGPUTextureForInternalTexture(a)),
        this.createImageBitmap(e).then(function(d) {
            o._textureHelper.updateTexture(d, a, a.width, a.height, a.depth, c.format, 0, 0, !i, !1, 0, 0, o._uploadEncoder),
            a.generateMipMaps && o._generateMipmaps(a, o._uploadEncoder),
            a.isReady = !0
        }).catch(function(d) {
            a.isReady = !0
        })
    }
}
;
var SceneLoaderFlags = function() {
    function a() {}
    return Object.defineProperty(a, "ForceFullSceneLoadingForIncremental", {
        get: function() {
            return a._ForceFullSceneLoadingForIncremental
        },
        set: function(e) {
            a._ForceFullSceneLoadingForIncremental = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ShowLoadingScreen", {
        get: function() {
            return a._ShowLoadingScreen
        },
        set: function(e) {
            a._ShowLoadingScreen = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "loggingLevel", {
        get: function() {
            return a._loggingLevel
        },
        set: function(e) {
            a._loggingLevel = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "CleanBoneMatrixWeights", {
        get: function() {
            return a._CleanBoneMatrixWeights
        },
        set: function(e) {
            a._CleanBoneMatrixWeights = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a._ForceFullSceneLoadingForIncremental = !1,
    a._ShowLoadingScreen = !0,
    a._CleanBoneMatrixWeights = !1,
    a._loggingLevel = 0,
    a
}(), SceneLoaderAnimationGroupLoadingMode;
(function(a) {
    a[a.Clean = 0] = "Clean",
    a[a.Stop = 1] = "Stop",
    a[a.Sync = 2] = "Sync",
    a[a.NoSync = 3] = "NoSync"
}
)(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {}));
var SceneLoader = function() {
    function a() {}
    return Object.defineProperty(a, "ForceFullSceneLoadingForIncremental", {
        get: function() {
            return SceneLoaderFlags.ForceFullSceneLoadingForIncremental
        },
        set: function(e) {
            SceneLoaderFlags.ForceFullSceneLoadingForIncremental = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ShowLoadingScreen", {
        get: function() {
            return SceneLoaderFlags.ShowLoadingScreen
        },
        set: function(e) {
            SceneLoaderFlags.ShowLoadingScreen = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "loggingLevel", {
        get: function() {
            return SceneLoaderFlags.loggingLevel
        },
        set: function(e) {
            SceneLoaderFlags.loggingLevel = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "CleanBoneMatrixWeights", {
        get: function() {
            return SceneLoaderFlags.CleanBoneMatrixWeights
        },
        set: function(e) {
            SceneLoaderFlags.CleanBoneMatrixWeights = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.GetDefaultPlugin = function() {
        return a._registeredPlugins[".babylon"]
    }
    ,
    a._GetPluginForExtension = function(e) {
        var i = a._registeredPlugins[e];
        return i || (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"),
        a.GetDefaultPlugin())
    }
    ,
    a._GetPluginForDirectLoad = function(e) {
        for (var i in a._registeredPlugins) {
            var o = a._registeredPlugins[i].plugin;
            if (o.canDirectLoad && o.canDirectLoad(e))
                return a._registeredPlugins[i]
        }
        return a.GetDefaultPlugin()
    }
    ,
    a._GetPluginForFilename = function(e) {
        var i = e.indexOf("?");
        i !== -1 && (e = e.substring(0, i));
        var o = e.lastIndexOf(".")
          , s = e.substring(o, e.length).toLowerCase();
        return a._GetPluginForExtension(s)
    }
    ,
    a._GetDirectLoad = function(e) {
        return e.substr(0, 5) === "data:" ? e.substr(5) : null
    }
    ,
    a._FormatErrorMessage = function(e, i, o) {
        var s = "Unable to load from " + e.url;
        return i ? s += ": " + i : o && (s += ": " + o),
        s
    }
    ,
    a._LoadData = function(e, i, o, s, c, d, _) {
        var b = a._GetDirectLoad(e.url), k = _ ? a._GetPluginForExtension(_) : b ? a._GetPluginForDirectLoad(e.url) : a._GetPluginForFilename(e.url), j;
        if (k.plugin.createPlugin !== void 0 ? j = k.plugin.createPlugin() : j = k.plugin,
        !j)
            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 (a.OnPluginActivatedObservable.notifyObservers(j),
        b && (j.canDirectLoad && j.canDirectLoad(e.url) || !IsBase64DataUrl(e.url))) {
            if (j.directLoad) {
                var $ = j.directLoad(i, b);
                $.then ? $.then(function(ft) {
                    o(j, ft)
                }).catch(function(ft) {
                    c("Error in directLoad of _loadData: " + ft, ft)
                }) : o(j, $)
            } else
                o(j, b);
            return j
        }
        var _e = k.isBinary
          , et = function(ft, ht) {
            if (i.isDisposed) {
                c("Scene has been disposed");
                return
            }
            o(j, ft, ht)
        }
          , tt = null
          , rt = !1
          , it = j.onDisposeObservable;
        it && it.add(function() {
            rt = !0,
            tt && (tt.abort(),
            tt = null),
            d()
        });
        var nt = function() {
            if (!rt) {
                var ft = function(pt, dt) {
                    c(pt == null ? void 0 : pt.statusText, dt)
                }
                  , ht = e.file || e.url;
                tt = j.loadFile ? j.loadFile(i, ht, et, s, _e, ft) : i._loadFile(ht, et, s, !0, _e, ft)
            }
        }
          , ot = i.getEngine()
          , at = ot.enableOfflineSupport;
        if (at) {
            for (var st = !1, ut = 0, ct = i.disableOfflineSupportExceptionRules; ut < ct.length; ut++) {
                var lt = ct[ut];
                if (lt.test(e.url)) {
                    st = !0;
                    break
                }
            }
            at = !st
        }
        return at && Engine.OfflineProviderFactory ? i.offlineProvider = Engine.OfflineProviderFactory(e.url, nt, ot.disableManifestCheck) : nt(),
        j
    }
    ,
    a._GetFileInfo = function(e, i) {
        var o, s, c = null;
        if (!i)
            o = e,
            s = Tools.GetFilename(e),
            e = Tools.GetFolderPath(e);
        else if (i.name) {
            var d = i;
            o = "file:" + d.name,
            s = d.name,
            c = d
        } else if (typeof i == "string" && StartsWith(i, "data:"))
            o = i,
            s = "";
        else {
            var _ = i;
            if (_.substr(0, 1) === "/")
                return Tools.Error("Wrong sceneFilename parameter"),
                null;
            o = e + _,
            s = _
        }
        return {
            url: o,
            rootUrl: e,
            name: s,
            file: c
        }
    }
    ,
    a.GetPluginForExtension = function(e) {
        return a._GetPluginForExtension(e).plugin
    }
    ,
    a.IsPluginForExtensionAvailable = function(e) {
        return !!a._registeredPlugins[e]
    }
    ,
    a.RegisterPlugin = function(e) {
        if (typeof e.extensions == "string") {
            var i = e.extensions;
            a._registeredPlugins[i.toLowerCase()] = {
                plugin: e,
                isBinary: !1
            }
        } else {
            var o = e.extensions;
            Object.keys(o).forEach(function(s) {
                a._registeredPlugins[s.toLowerCase()] = {
                    plugin: e,
                    isBinary: o[s].isBinary
                }
            })
        }
    }
    ,
    a.ImportMesh = function(e, i, o, s, c, d, _, b) {
        if (o === void 0 && (o = ""),
        s === void 0 && (s = EngineStore.LastCreatedScene),
        c === void 0 && (c = null),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null),
        !s)
            return Logger$2.Error("No scene available to import mesh to"),
            null;
        var k = a._GetFileInfo(i, o);
        if (!k)
            return null;
        var j = {};
        s._addPendingData(j);
        var $ = function() {
            s._removePendingData(j)
        }
          , _e = function(rt, it) {
            var nt = a._FormatErrorMessage(k, rt, it);
            _ ? _(s, nt, new Error(nt)) : Logger$2.Error(nt),
            $()
        }
          , et = d ? function(rt) {
            try {
                d(rt)
            } catch (it) {
                _e("Error in onProgress callback: " + it, it)
            }
        }
        : void 0
          , tt = function(rt, it, nt, ot, at, st, ut) {
            if (s.importedMeshesFiles.push(k.url),
            c)
                try {
                    c(rt, it, nt, ot, at, st, ut)
                } catch (ct) {
                    _e("Error in onSuccess callback: " + ct, ct)
                }
            s._removePendingData(j)
        };
        return a._LoadData(k, s, function(rt, it, nt) {
            if (rt.rewriteRootURL && (k.rootUrl = rt.rewriteRootURL(k.rootUrl, nt)),
            rt.importMesh) {
                var ot = rt
                  , at = new Array
                  , st = new Array
                  , ut = new Array;
                if (!ot.importMesh(e, s, it, k.rootUrl, at, st, ut, _e))
                    return;
                s.loadingPluginName = rt.name,
                tt(at, st, ut, [], [], [], [])
            } else {
                var ct = rt;
                ct.importMeshAsync(e, s, it, k.rootUrl, et, k.name).then(function(lt) {
                    s.loadingPluginName = rt.name,
                    tt(lt.meshes, lt.particleSystems, lt.skeletons, lt.animationGroups, lt.transformNodes, lt.geometries, lt.lights)
                }).catch(function(lt) {
                    _e(lt.message, lt)
                })
            }
        }, et, _e, $, b)
    }
    ,
    a.ImportMeshAsync = function(e, i, o, s, c, d) {
        return o === void 0 && (o = ""),
        s === void 0 && (s = EngineStore.LastCreatedScene),
        c === void 0 && (c = null),
        d === void 0 && (d = null),
        new Promise(function(_, b) {
            a.ImportMesh(e, i, o, s, function(k, j, $, _e, et, tt, rt) {
                _({
                    meshes: k,
                    particleSystems: j,
                    skeletons: $,
                    animationGroups: _e,
                    transformNodes: et,
                    geometries: tt,
                    lights: rt
                })
            }, c, function(k, j, $) {
                b($ || new Error(j))
            }, d)
        }
        )
    }
    ,
    a.Load = function(e, i, o, s, c, d, _) {
        return i === void 0 && (i = ""),
        o === void 0 && (o = EngineStore.LastCreatedEngine),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        o ? a.Append(e, i, new Scene(o), s, c, d, _) : (Tools.Error("No engine available"),
        null)
    }
    ,
    a.LoadAsync = function(e, i, o, s, c) {
        return i === void 0 && (i = ""),
        o === void 0 && (o = EngineStore.LastCreatedEngine),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        new Promise(function(d, _) {
            a.Load(e, i, o, function(b) {
                d(b)
            }, s, function(b, k, j) {
                _(j || new Error(k))
            }, c)
        }
        )
    }
    ,
    a.Append = function(e, i, o, s, c, d, _) {
        var b = this;
        if (i === void 0 && (i = ""),
        o === void 0 && (o = EngineStore.LastCreatedScene),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        !o)
            return Logger$2.Error("No scene available to append to"),
            null;
        var k = a._GetFileInfo(e, i);
        if (!k)
            return null;
        a.ShowLoadingScreen && !this._showingLoadingScreen && (this._showingLoadingScreen = !0,
        o.getEngine().displayLoadingUI(),
        o.executeWhenReady(function() {
            o.getEngine().hideLoadingUI(),
            b._showingLoadingScreen = !1
        }));
        var j = {};
        o._addPendingData(j);
        var $ = function() {
            o._removePendingData(j)
        }
          , _e = function(rt, it) {
            var nt = a._FormatErrorMessage(k, rt, it);
            d ? d(o, nt, new Error(nt)) : Logger$2.Error(nt),
            $()
        }
          , et = c ? function(rt) {
            try {
                c(rt)
            } catch (it) {
                _e("Error in onProgress callback", it)
            }
        }
        : void 0
          , tt = function() {
            if (s)
                try {
                    s(o)
                } catch (rt) {
                    _e("Error in onSuccess callback", rt)
                }
            o._removePendingData(j)
        };
        return a._LoadData(k, o, function(rt, it) {
            if (rt.load) {
                var nt = rt;
                if (!nt.load(o, it, k.rootUrl, _e))
                    return;
                o.loadingPluginName = rt.name,
                tt()
            } else {
                var ot = rt;
                ot.loadAsync(o, it, k.rootUrl, et, k.name).then(function() {
                    o.loadingPluginName = rt.name,
                    tt()
                }).catch(function(at) {
                    _e(at.message, at)
                })
            }
        }, et, _e, $, _)
    }
    ,
    a.AppendAsync = function(e, i, o, s, c) {
        return i === void 0 && (i = ""),
        o === void 0 && (o = EngineStore.LastCreatedScene),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        new Promise(function(d, _) {
            a.Append(e, i, o, function(b) {
                d(b)
            }, s, function(b, k, j) {
                _(j || new Error(k))
            }, c)
        }
        )
    }
    ,
    a.LoadAssetContainer = function(e, i, o, s, c, d, _) {
        if (i === void 0 && (i = ""),
        o === void 0 && (o = EngineStore.LastCreatedScene),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        !o)
            return Logger$2.Error("No scene available to load asset container to"),
            null;
        var b = a._GetFileInfo(e, i);
        if (!b)
            return null;
        var k = {};
        o._addPendingData(k);
        var j = function() {
            o._removePendingData(k)
        }
          , $ = function(tt, rt) {
            var it = a._FormatErrorMessage(b, tt, rt);
            d ? d(o, it, new Error(it)) : Logger$2.Error(it),
            j()
        }
          , _e = c ? function(tt) {
            try {
                c(tt)
            } catch (rt) {
                $("Error in onProgress callback", rt)
            }
        }
        : void 0
          , et = function(tt) {
            if (s)
                try {
                    s(tt)
                } catch (rt) {
                    $("Error in onSuccess callback", rt)
                }
            o._removePendingData(k)
        };
        return a._LoadData(b, o, function(tt, rt) {
            if (tt.loadAssetContainer) {
                var it = tt
                  , nt = it.loadAssetContainer(o, rt, b.rootUrl, $);
                if (!nt)
                    return;
                o.loadingPluginName = tt.name,
                et(nt)
            } else if (tt.loadAssetContainerAsync) {
                var ot = tt;
                ot.loadAssetContainerAsync(o, rt, b.rootUrl, _e, b.name).then(function(at) {
                    o.loadingPluginName = tt.name,
                    et(at)
                }).catch(function(at) {
                    $(at.message, at)
                })
            } else
                $("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")
        }, _e, $, j, _)
    }
    ,
    a.LoadAssetContainerAsync = function(e, i, o, s, c) {
        return i === void 0 && (i = ""),
        o === void 0 && (o = EngineStore.LastCreatedScene),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        new Promise(function(d, _) {
            a.LoadAssetContainer(e, i, o, function(b) {
                d(b)
            }, s, function(b, k, j) {
                _(j || new Error(k))
            }, c)
        }
        )
    }
    ,
    a.ImportAnimations = function(e, i, o, s, c, d, _, b, k, j) {
        if (i === void 0 && (i = ""),
        o === void 0 && (o = EngineStore.LastCreatedScene),
        s === void 0 && (s = !0),
        c === void 0 && (c = SceneLoaderAnimationGroupLoadingMode.Clean),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null),
        k === void 0 && (k = null),
        j === void 0 && (j = null),
        !o) {
            Logger$2.Error("No scene available to load animations to");
            return
        }
        if (s) {
            for (var $ = 0, _e = o.animatables; $ < _e.length; $++) {
                var et = _e[$];
                et.reset()
            }
            o.stopAllAnimations(),
            o.animationGroups.slice().forEach(function(nt) {
                nt.dispose()
            });
            var tt = o.getNodes();
            tt.forEach(function(nt) {
                nt.animations && (nt.animations = [])
            })
        } else
            switch (c) {
            case SceneLoaderAnimationGroupLoadingMode.Clean:
                o.animationGroups.slice().forEach(function(nt) {
                    nt.dispose()
                });
                break;
            case SceneLoaderAnimationGroupLoadingMode.Stop:
                o.animationGroups.forEach(function(nt) {
                    nt.stop()
                });
                break;
            case SceneLoaderAnimationGroupLoadingMode.Sync:
                o.animationGroups.forEach(function(nt) {
                    nt.reset(),
                    nt.restart()
                });
                break;
            case SceneLoaderAnimationGroupLoadingMode.NoSync:
                break;
            default:
                Logger$2.Error("Unknown animation group loading mode value '" + c + "'");
                return
            }
        var rt = o.animatables.length
          , it = function(nt) {
            nt.mergeAnimationsTo(o, o.animatables.slice(rt), d),
            nt.dispose(),
            o.onAnimationFileImportedObservable.notifyObservers(o),
            _ && _(o)
        };
        this.LoadAssetContainer(e, i, o, it, b, k, j)
    }
    ,
    a.ImportAnimationsAsync = function(e, i, o, s, c, d, _, b, k, j) {
        return i === void 0 && (i = ""),
        o === void 0 && (o = EngineStore.LastCreatedScene),
        s === void 0 && (s = !0),
        c === void 0 && (c = SceneLoaderAnimationGroupLoadingMode.Clean),
        d === void 0 && (d = null),
        b === void 0 && (b = null),
        j === void 0 && (j = null),
        new Promise(function($, _e) {
            a.ImportAnimations(e, i, o, s, c, d, function(et) {
                $(et)
            }, b, function(et, tt, rt) {
                _e(rt || new Error(tt))
            }, j)
        }
        )
    }
    ,
    a.NO_LOGGING = 0,
    a.MINIMAL_LOGGING = 1,
    a.SUMMARY_LOGGING = 2,
    a.DETAILED_LOGGING = 3,
    a.OnPluginActivatedObservable = new Observable,
    a._registeredPlugins = {},
    a._showingLoadingScreen = !1,
    a
}(), AnimationKeyInterpolation;
(function(a) {
    a[a.NONE = 0] = "NONE",
    a[a.STEP = 1] = "STEP"
}
)(AnimationKeyInterpolation || (AnimationKeyInterpolation = {}));
var AnimationRange = function() {
    function a(e, i, o) {
        this.name = e,
        this.from = i,
        this.to = o
    }
    return a.prototype.clone = function() {
        return new a(this.name,this.from,this.to)
    }
    ,
    a
}()
  , Animation = function() {
    function a(e, i, o, s, c, d) {
        this.name = e,
        this.targetProperty = i,
        this.framePerSecond = o,
        this.dataType = s,
        this.loopMode = c,
        this.enableBlending = d,
        this._runtimeAnimations = new Array,
        this._events = new Array,
        this.blendingSpeed = .01,
        this._ranges = {},
        this.targetPropertyPath = i.split("."),
        this.dataType = s,
        this.loopMode = c === void 0 ? a.ANIMATIONLOOPMODE_CYCLE : c,
        this.uniqueId = a._UniqueIdGenerator++
    }
    return a._PrepareAnimation = function(e, i, o, s, c, d, _, b) {
        var k = void 0;
        if (!isNaN(parseFloat(c)) && isFinite(c) ? k = a.ANIMATIONTYPE_FLOAT : c instanceof Quaternion ? k = a.ANIMATIONTYPE_QUATERNION : c instanceof Vector3 ? k = a.ANIMATIONTYPE_VECTOR3 : c instanceof Vector2 ? k = a.ANIMATIONTYPE_VECTOR2 : c instanceof Color3 ? k = a.ANIMATIONTYPE_COLOR3 : c instanceof Color4 ? k = a.ANIMATIONTYPE_COLOR4 : c instanceof Size && (k = a.ANIMATIONTYPE_SIZE),
        k == null)
            return null;
        var j = new a(e,i,o,k,_)
          , $ = [{
            frame: 0,
            value: c
        }, {
            frame: s,
            value: d
        }];
        return j.setKeys($),
        b !== void 0 && j.setEasingFunction(b),
        j
    }
    ,
    a.CreateAnimation = function(e, i, o, s) {
        var c = new a(e + "Animation",e,o,i,a.ANIMATIONLOOPMODE_CONSTANT);
        return c.setEasingFunction(s),
        c
    }
    ,
    a.CreateAndStartAnimation = function(e, i, o, s, c, d, _, b, k, j, $) {
        var _e = a._PrepareAnimation(e, o, s, c, d, _, b, k);
        return !_e || (i.getScene && ($ = i.getScene()),
        !$) ? null : $.beginDirectAnimation(i, [_e], 0, c, _e.loopMode === 1, 1, j)
    }
    ,
    a.CreateAndStartHierarchyAnimation = function(e, i, o, s, c, d, _, b, k, j, $) {
        var _e = a._PrepareAnimation(e, s, c, d, _, b, k, j);
        if (!_e)
            return null;
        var et = i.getScene();
        return et.beginDirectHierarchyAnimation(i, o, [_e], 0, d, _e.loopMode === 1, 1, $)
    }
    ,
    a.CreateMergeAndStartAnimation = function(e, i, o, s, c, d, _, b, k, j) {
        var $ = a._PrepareAnimation(e, o, s, c, d, _, b, k);
        return $ ? (i.animations.push($),
        i.getScene().beginAnimation(i, 0, c, $.loopMode === 1, 1, j)) : null
    }
    ,
    a.MakeAnimationAdditive = function(e, i, o, s, c) {
        i === void 0 && (i = 0),
        s === void 0 && (s = !1);
        var d = e;
        if (s && (d = e.clone(),
        d.name = c || d.name),
        !d._keys.length)
            return d;
        i = i >= 0 ? i : 0;
        var _ = 0
          , b = d._keys[0]
          , k = d._keys.length - 1
          , j = d._keys[k]
          , $ = {
            referenceValue: b.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]
        }
          , _e = !1
          , et = b.frame
          , tt = j.frame;
        if (o) {
            var rt = d.getRange(o);
            rt && (et = rt.from,
            tt = rt.to)
        }
        var it = b.frame === et
          , nt = j.frame === tt;
        if (d._keys.length === 1) {
            var ot = d._getKeyValue(d._keys[0]);
            $.referenceValue = ot.clone ? ot.clone() : ot,
            _e = !0
        } else if (i <= b.frame) {
            var ot = d._getKeyValue(b.value);
            $.referenceValue = ot.clone ? ot.clone() : ot,
            _e = !0
        } else if (i >= j.frame) {
            var ot = d._getKeyValue(j.value);
            $.referenceValue = ot.clone ? ot.clone() : ot,
            _e = !0
        }
        for (var at = 0; !_e || !it || !nt && at < d._keys.length - 1; ) {
            var st = d._keys[at]
              , ut = d._keys[at + 1];
            if (!_e && i >= st.frame && i <= ut.frame) {
                var ot = void 0;
                if (i === st.frame)
                    ot = d._getKeyValue(st.value);
                else if (i === ut.frame)
                    ot = d._getKeyValue(ut.value);
                else {
                    var ct = {
                        key: at,
                        repeatCount: 0,
                        loopMode: this.ANIMATIONLOOPMODE_CONSTANT
                    };
                    ot = d._interpolate(i, ct)
                }
                $.referenceValue = ot.clone ? ot.clone() : ot,
                _e = !0
            }
            if (!it && et >= st.frame && et <= ut.frame) {
                if (et === st.frame)
                    _ = at;
                else if (et === ut.frame)
                    _ = at + 1;
                else {
                    var ct = {
                        key: at,
                        repeatCount: 0,
                        loopMode: this.ANIMATIONLOOPMODE_CONSTANT
                    }
                      , ot = d._interpolate(et, ct)
                      , lt = {
                        frame: et,
                        value: ot.clone ? ot.clone() : ot
                    };
                    d._keys.splice(at + 1, 0, lt),
                    _ = at + 1
                }
                it = !0
            }
            if (!nt && tt >= st.frame && tt <= ut.frame) {
                if (tt === st.frame)
                    k = at;
                else if (tt === ut.frame)
                    k = at + 1;
                else {
                    var ct = {
                        key: at,
                        repeatCount: 0,
                        loopMode: this.ANIMATIONLOOPMODE_CONSTANT
                    }
                      , ot = d._interpolate(tt, ct)
                      , lt = {
                        frame: tt,
                        value: ot.clone ? ot.clone() : ot
                    };
                    d._keys.splice(at + 1, 0, lt),
                    k = at + 1
                }
                nt = !0
            }
            at++
        }
        d.dataType === a.ANIMATIONTYPE_QUATERNION ? $.referenceValue.normalize().conjugateInPlace() : d.dataType === a.ANIMATIONTYPE_MATRIX && ($.referenceValue.decompose($.referenceScaling, $.referenceQuaternion, $.referencePosition),
        $.referenceQuaternion.normalize().conjugateInPlace());
        for (var at = _; at <= k; at++) {
            var lt = d._keys[at];
            if (!(at && d.dataType !== a.ANIMATIONTYPE_FLOAT && lt.value === b.value))
                switch (d.dataType) {
                case a.ANIMATIONTYPE_MATRIX:
                    lt.value.decompose($.keyScaling, $.keyQuaternion, $.keyPosition),
                    $.keyPosition.subtractInPlace($.referencePosition),
                    $.keyScaling.divideInPlace($.referenceScaling),
                    $.referenceQuaternion.multiplyToRef($.keyQuaternion, $.keyQuaternion),
                    Matrix.ComposeToRef($.keyScaling, $.keyQuaternion, $.keyPosition, lt.value);
                    break;
                case a.ANIMATIONTYPE_QUATERNION:
                    $.referenceValue.multiplyToRef(lt.value, lt.value);
                    break;
                case a.ANIMATIONTYPE_VECTOR2:
                case a.ANIMATIONTYPE_VECTOR3:
                case a.ANIMATIONTYPE_COLOR3:
                case a.ANIMATIONTYPE_COLOR4:
                    lt.value.subtractToRef($.referenceValue, lt.value);
                    break;
                case a.ANIMATIONTYPE_SIZE:
                    lt.value.width -= $.referenceValue.width,
                    lt.value.height -= $.referenceValue.height;
                    break;
                default:
                    lt.value -= $.referenceValue
                }
        }
        return d
    }
    ,
    a.TransitionTo = function(e, i, o, s, c, d, _, b) {
        if (b === void 0 && (b = null),
        _ <= 0)
            return o[e] = i,
            b && b(),
            null;
        var k = c * (_ / 1e3);
        d.setKeys([{
            frame: 0,
            value: o[e].clone ? o[e].clone() : o[e]
        }, {
            frame: k,
            value: i
        }]),
        o.animations || (o.animations = []),
        o.animations.push(d);
        var j = s.beginAnimation(o, 0, k, !1);
        return j.onAnimationEnd = b,
        j
    }
    ,
    Object.defineProperty(a.prototype, "runtimeAnimations", {
        get: function() {
            return this._runtimeAnimations
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasRunningRuntimeAnimations", {
        get: function() {
            for (var e = 0, i = this._runtimeAnimations; e < i.length; e++) {
                var o = i[e];
                if (!o.isStopped())
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.toString = function(e) {
        var i = "Name: " + this.name + ", property: " + this.targetProperty;
        if (i += ", datatype: " + ["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"][this.dataType],
        i += ", nKeys: " + (this._keys ? this._keys.length : "none"),
        i += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"),
        e) {
            i += ", Ranges: {";
            var o = !0;
            for (var s in this._ranges)
                o && (i += ", ",
                o = !1),
                i += s;
            i += "}"
        }
        return i
    }
    ,
    a.prototype.addEvent = function(e) {
        this._events.push(e),
        this._events.sort(function(i, o) {
            return i.frame - o.frame
        })
    }
    ,
    a.prototype.removeEvents = function(e) {
        for (var i = 0; i < this._events.length; i++)
            this._events[i].frame === e && (this._events.splice(i, 1),
            i--)
    }
    ,
    a.prototype.getEvents = function() {
        return this._events
    }
    ,
    a.prototype.createRange = function(e, i, o) {
        this._ranges[e] || (this._ranges[e] = new AnimationRange(e,i,o))
    }
    ,
    a.prototype.deleteRange = function(e, i) {
        i === void 0 && (i = !0);
        var o = this._ranges[e];
        if (!!o) {
            if (i)
                for (var s = o.from, c = o.to, d = this._keys.length - 1; d >= 0; d--)
                    this._keys[d].frame >= s && this._keys[d].frame <= c && this._keys.splice(d, 1);
            this._ranges[e] = null
        }
    }
    ,
    a.prototype.getRange = function(e) {
        return this._ranges[e]
    }
    ,
    a.prototype.getKeys = function() {
        return this._keys
    }
    ,
    a.prototype.getHighestFrame = function() {
        for (var e = 0, i = 0, o = this._keys.length; i < o; i++)
            e < this._keys[i].frame && (e = this._keys[i].frame);
        return e
    }
    ,
    a.prototype.getEasingFunction = function() {
        return this._easingFunction
    }
    ,
    a.prototype.setEasingFunction = function(e) {
        this._easingFunction = e
    }
    ,
    a.prototype.floatInterpolateFunction = function(e, i, o) {
        return Scalar.Lerp(e, i, o)
    }
    ,
    a.prototype.floatInterpolateFunctionWithTangents = function(e, i, o, s, c) {
        return Scalar.Hermite(e, i, o, s, c)
    }
    ,
    a.prototype.quaternionInterpolateFunction = function(e, i, o) {
        return Quaternion.Slerp(e, i, o)
    }
    ,
    a.prototype.quaternionInterpolateFunctionWithTangents = function(e, i, o, s, c) {
        return Quaternion.Hermite(e, i, o, s, c).normalize()
    }
    ,
    a.prototype.vector3InterpolateFunction = function(e, i, o) {
        return Vector3.Lerp(e, i, o)
    }
    ,
    a.prototype.vector3InterpolateFunctionWithTangents = function(e, i, o, s, c) {
        return Vector3.Hermite(e, i, o, s, c)
    }
    ,
    a.prototype.vector2InterpolateFunction = function(e, i, o) {
        return Vector2.Lerp(e, i, o)
    }
    ,
    a.prototype.vector2InterpolateFunctionWithTangents = function(e, i, o, s, c) {
        return Vector2.Hermite(e, i, o, s, c)
    }
    ,
    a.prototype.sizeInterpolateFunction = function(e, i, o) {
        return Size.Lerp(e, i, o)
    }
    ,
    a.prototype.color3InterpolateFunction = function(e, i, o) {
        return Color3.Lerp(e, i, o)
    }
    ,
    a.prototype.color3InterpolateFunctionWithTangents = function(e, i, o, s, c) {
        return Color3.Hermite(e, i, o, s, c)
    }
    ,
    a.prototype.color4InterpolateFunction = function(e, i, o) {
        return Color4.Lerp(e, i, o)
    }
    ,
    a.prototype.color4InterpolateFunctionWithTangents = function(e, i, o, s, c) {
        return Color4.Hermite(e, i, o, s, c)
    }
    ,
    a.prototype._getKeyValue = function(e) {
        return typeof e == "function" ? e() : e
    }
    ,
    a.prototype.evaluate = function(e) {
        return this._interpolate(e, {
            key: 0,
            repeatCount: 0,
            loopMode: a.ANIMATIONLOOPMODE_CONSTANT
        })
    }
    ,
    a.prototype._interpolate = function(e, i) {
        if (i.loopMode === a.ANIMATIONLOOPMODE_CONSTANT && i.repeatCount > 0)
            return i.highLimitValue.clone ? i.highLimitValue.clone() : i.highLimitValue;
        var o = this._keys;
        if (o.length === 1)
            return this._getKeyValue(o[0].value);
        var s = i.key;
        if (o[s].frame >= e)
            for (; s - 1 >= 0 && o[s].frame >= e; )
                s--;
        for (var c = s; c < o.length - 1; c++) {
            var d = o[c + 1];
            if (d.frame >= e) {
                i.key = c;
                var _ = o[c]
                  , b = this._getKeyValue(_.value)
                  , k = this._getKeyValue(d.value);
                if (_.interpolation === AnimationKeyInterpolation.STEP)
                    return d.frame > e ? b : k;
                var j = _.outTangent !== void 0 && d.inTangent !== void 0
                  , $ = d.frame - _.frame
                  , _e = (e - _.frame) / $
                  , et = this.getEasingFunction();
                switch (et != null && (_e = et.ease(_e)),
                this.dataType) {
                case a.ANIMATIONTYPE_FLOAT:
                    var tt = j ? this.floatInterpolateFunctionWithTangents(b, _.outTangent * $, k, d.inTangent * $, _e) : this.floatInterpolateFunction(b, k, _e);
                    switch (i.loopMode) {
                    case a.ANIMATIONLOOPMODE_CYCLE:
                    case a.ANIMATIONLOOPMODE_CONSTANT:
                        return tt;
                    case a.ANIMATIONLOOPMODE_RELATIVE:
                        return i.offsetValue * i.repeatCount + tt
                    }
                    break;
                case a.ANIMATIONTYPE_QUATERNION:
                    var rt = j ? this.quaternionInterpolateFunctionWithTangents(b, _.outTangent.scale($), k, d.inTangent.scale($), _e) : this.quaternionInterpolateFunction(b, k, _e);
                    switch (i.loopMode) {
                    case a.ANIMATIONLOOPMODE_CYCLE:
                    case a.ANIMATIONLOOPMODE_CONSTANT:
                        return rt;
                    case a.ANIMATIONLOOPMODE_RELATIVE:
                        return rt.addInPlace(i.offsetValue.scale(i.repeatCount))
                    }
                    return rt;
                case a.ANIMATIONTYPE_VECTOR3:
                    var it = j ? this.vector3InterpolateFunctionWithTangents(b, _.outTangent.scale($), k, d.inTangent.scale($), _e) : this.vector3InterpolateFunction(b, k, _e);
                    switch (i.loopMode) {
                    case a.ANIMATIONLOOPMODE_CYCLE:
                    case a.ANIMATIONLOOPMODE_CONSTANT:
                        return it;
                    case a.ANIMATIONLOOPMODE_RELATIVE:
                        return it.add(i.offsetValue.scale(i.repeatCount))
                    }
                case a.ANIMATIONTYPE_VECTOR2:
                    var nt = j ? this.vector2InterpolateFunctionWithTangents(b, _.outTangent.scale($), k, d.inTangent.scale($), _e) : this.vector2InterpolateFunction(b, k, _e);
                    switch (i.loopMode) {
                    case a.ANIMATIONLOOPMODE_CYCLE:
                    case a.ANIMATIONLOOPMODE_CONSTANT:
                        return nt;
                    case a.ANIMATIONLOOPMODE_RELATIVE:
                        return nt.add(i.offsetValue.scale(i.repeatCount))
                    }
                case a.ANIMATIONTYPE_SIZE:
                    switch (i.loopMode) {
                    case a.ANIMATIONLOOPMODE_CYCLE:
                    case a.ANIMATIONLOOPMODE_CONSTANT:
                        return this.sizeInterpolateFunction(b, k, _e);
                    case a.ANIMATIONLOOPMODE_RELATIVE:
                        return this.sizeInterpolateFunction(b, k, _e).add(i.offsetValue.scale(i.repeatCount))
                    }
                case a.ANIMATIONTYPE_COLOR3:
                    var ot = j ? this.color3InterpolateFunctionWithTangents(b, _.outTangent.scale($), k, d.inTangent.scale($), _e) : this.color3InterpolateFunction(b, k, _e);
                    switch (i.loopMode) {
                    case a.ANIMATIONLOOPMODE_CYCLE:
                    case a.ANIMATIONLOOPMODE_CONSTANT:
                        return ot;
                    case a.ANIMATIONLOOPMODE_RELATIVE:
                        return ot.add(i.offsetValue.scale(i.repeatCount))
                    }
                case a.ANIMATIONTYPE_COLOR4:
                    var at = j ? this.color4InterpolateFunctionWithTangents(b, _.outTangent.scale($), k, d.inTangent.scale($), _e) : this.color4InterpolateFunction(b, k, _e);
                    switch (i.loopMode) {
                    case a.ANIMATIONLOOPMODE_CYCLE:
                    case a.ANIMATIONLOOPMODE_CONSTANT:
                        return at;
                    case a.ANIMATIONLOOPMODE_RELATIVE:
                        return at.add(i.offsetValue.scale(i.repeatCount))
                    }
                case a.ANIMATIONTYPE_MATRIX:
                    switch (i.loopMode) {
                    case a.ANIMATIONLOOPMODE_CYCLE:
                    case a.ANIMATIONLOOPMODE_CONSTANT:
                        if (a.AllowMatricesInterpolation)
                            return this.matrixInterpolateFunction(b, k, _e, i.workValue);
                    case a.ANIMATIONLOOPMODE_RELATIVE:
                        return b
                    }
                }
                break
            }
        }
        return this._getKeyValue(o[o.length - 1].value)
    }
    ,
    a.prototype.matrixInterpolateFunction = function(e, i, o, s) {
        return a.AllowMatrixDecomposeForInterpolation ? s ? (Matrix.DecomposeLerpToRef(e, i, o, s),
        s) : Matrix.DecomposeLerp(e, i, o) : s ? (Matrix.LerpToRef(e, i, o, s),
        s) : Matrix.Lerp(e, i, o)
    }
    ,
    a.prototype.clone = function() {
        var e = new a(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 i in this._ranges) {
                var o = this._ranges[i];
                !o || (e._ranges[i] = o.clone())
            }
        }
        return e
    }
    ,
    a.prototype.setKeys = function(e) {
        this._keys = e.slice(0)
    }
    ,
    a.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 i = this.dataType;
        e.keys = [];
        for (var o = this.getKeys(), s = 0; s < o.length; s++) {
            var c = o[s]
              , d = {};
            switch (d.frame = c.frame,
            i) {
            case a.ANIMATIONTYPE_FLOAT:
                d.values = [c.value],
                c.inTangent !== void 0 && d.values.push(c.inTangent),
                c.outTangent !== void 0 && (c.inTangent === void 0 && d.values.push(void 0),
                d.values.push(c.outTangent));
                break;
            case a.ANIMATIONTYPE_QUATERNION:
            case a.ANIMATIONTYPE_MATRIX:
            case a.ANIMATIONTYPE_VECTOR3:
            case a.ANIMATIONTYPE_COLOR3:
            case a.ANIMATIONTYPE_COLOR4:
                d.values = c.value.asArray(),
                c.inTangent != null && d.values.push(c.inTangent.asArray()),
                c.outTangent != null && (c.inTangent === void 0 && d.values.push(void 0),
                d.values.push(c.outTangent.asArray()));
                break
            }
            e.keys.push(d)
        }
        e.ranges = [];
        for (var _ in this._ranges) {
            var b = this._ranges[_];
            if (!!b) {
                var k = {};
                k.name = _,
                k.from = b.from,
                k.to = b.to,
                e.ranges.push(k)
            }
        }
        return e
    }
    ,
    a._UniversalLerp = function(e, i, o) {
        var s = e.constructor;
        return s.Lerp ? s.Lerp(e, i, o) : s.Slerp ? s.Slerp(e, i, o) : e.toFixed ? e * (1 - o) + o * i : i
    }
    ,
    a.Parse = function(e) {
        var i = new a(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior), o = e.dataType, s = [], c, d;
        for (e.enableBlending && (i.enableBlending = e.enableBlending),
        e.blendingSpeed && (i.blendingSpeed = e.blendingSpeed),
        d = 0; d < e.keys.length; d++) {
            var _ = e.keys[d]
              , b = void 0
              , k = void 0;
            switch (o) {
            case a.ANIMATIONTYPE_FLOAT:
                c = _.values[0],
                _.values.length >= 1 && (b = _.values[1]),
                _.values.length >= 2 && (k = _.values[2]);
                break;
            case a.ANIMATIONTYPE_QUATERNION:
                if (c = Quaternion.FromArray(_.values),
                _.values.length >= 8) {
                    var j = Quaternion.FromArray(_.values.slice(4, 8));
                    j.equals(Quaternion.Zero()) || (b = j)
                }
                if (_.values.length >= 12) {
                    var $ = Quaternion.FromArray(_.values.slice(8, 12));
                    $.equals(Quaternion.Zero()) || (k = $)
                }
                break;
            case a.ANIMATIONTYPE_MATRIX:
                c = Matrix.FromArray(_.values);
                break;
            case a.ANIMATIONTYPE_COLOR3:
                c = Color3.FromArray(_.values),
                _.values[3] && (b = Color3.FromArray(_.values[3])),
                _.values[4] && (k = Color3.FromArray(_.values[4]));
                break;
            case a.ANIMATIONTYPE_COLOR4:
                c = Color4.FromArray(_.values),
                _.values[4] && (b = Color4.FromArray(_.values[4])),
                _.values[5] && (k = Color4.FromArray(_.values[5]));
                break;
            case a.ANIMATIONTYPE_VECTOR3:
            default:
                c = Vector3.FromArray(_.values),
                _.values[3] && (b = Vector3.FromArray(_.values[3])),
                _.values[4] && (k = Vector3.FromArray(_.values[4]));
                break
            }
            var _e = {};
            _e.frame = _.frame,
            _e.value = c,
            b != null && (_e.inTangent = b),
            k != null && (_e.outTangent = k),
            s.push(_e)
        }
        if (i.setKeys(s),
        e.ranges)
            for (d = 0; d < e.ranges.length; d++)
                c = e.ranges[d],
                i.createRange(c.name, c.from, c.to);
        return i
    }
    ,
    a.AppendSerializedAnimations = function(e, i) {
        SerializationHelper.AppendSerializedAnimations(e, i)
    }
    ,
    a.ParseFromFileAsync = function(e, i) {
        var o = this;
        return new Promise(function(s, c) {
            var d = new WebRequest;
            d.addEventListener("readystatechange", function() {
                if (d.readyState == 4)
                    if (d.status == 200) {
                        var _ = JSON.parse(d.responseText);
                        if (_.length) {
                            for (var b = new Array, k = 0, j = _; k < j.length; k++) {
                                var $ = j[k];
                                b.push(o.Parse($))
                            }
                            s(b)
                        } else {
                            var b = o.Parse(_);
                            e && (b.name = e),
                            s(b)
                        }
                    } else
                        c("Unable to load the animation")
            }),
            d.open("GET", i),
            d.send()
        }
        )
    }
    ,
    a.CreateFromSnippetAsync = function(e) {
        var i = this;
        return new Promise(function(o, s) {
            var c = new WebRequest;
            c.addEventListener("readystatechange", function() {
                if (c.readyState == 4)
                    if (c.status == 200) {
                        var d = JSON.parse(JSON.parse(c.responseText).jsonPayload);
                        if (d.animations) {
                            for (var _ = JSON.parse(d.animations), b = new Array, k = 0, j = _.animations; k < j.length; k++) {
                                var $ = j[k]
                                  , _e = i.Parse($);
                                _e.snippetId = e,
                                b.push(_e)
                            }
                            o(b)
                        } else {
                            var _ = JSON.parse(d.animation)
                              , _e = i.Parse(_);
                            _e.snippetId = e,
                            o(_e)
                        }
                    } else
                        s("Unable to load the snippet " + e)
            }),
            c.open("GET", i.SnippetUrl + "/" + e.replace(/#/g, "/")),
            c.send()
        }
        )
    }
    ,
    a._UniqueIdGenerator = 0,
    a.AllowMatricesInterpolation = !1,
    a.AllowMatrixDecomposeForInterpolation = !0,
    a.SnippetUrl = "https://snippet.babylonjs.com",
    a.ANIMATIONTYPE_FLOAT = 0,
    a.ANIMATIONTYPE_VECTOR3 = 1,
    a.ANIMATIONTYPE_QUATERNION = 2,
    a.ANIMATIONTYPE_MATRIX = 3,
    a.ANIMATIONTYPE_COLOR3 = 4,
    a.ANIMATIONTYPE_COLOR4 = 7,
    a.ANIMATIONTYPE_VECTOR2 = 5,
    a.ANIMATIONTYPE_SIZE = 6,
    a.ANIMATIONLOOPMODE_RELATIVE = 0,
    a.ANIMATIONLOOPMODE_CYCLE = 1,
    a.ANIMATIONLOOPMODE_CONSTANT = 2,
    a
}();
RegisterClass("BABYLON.Animation", Animation);
Node$2._AnimationRangeFactory = function(a, e, i) {
    return new AnimationRange(a,e,i)
}
;
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 a(e, i, o, s) {
        var c = 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 = i,
        this._target = e,
        this._scene = o,
        this._host = s,
        this._activeTargets = [],
        i._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 d = {
                frame: 0,
                value: this._minValue
            };
            this._keys.splice(0, 0, d)
        }
        if (this._target instanceof Array) {
            for (var _ = 0, b = 0, k = this._target; b < k.length; b++) {
                var j = k[b];
                this._preparePath(j, _),
                this._getOriginalValues(_),
                _++
            }
            this._targetIsArray = !0
        } else
            this._preparePath(this._target),
            this._getOriginalValues(),
            this._targetIsArray = !1,
            this._directTarget = this._activeTargets[0];
        var $ = i.getEvents();
        $ && $.length > 0 && $.forEach(function(_e) {
            c._events.push(_e._clone())
        }),
        this._enableBlending = e && e.animationPropertiesOverride ? e.animationPropertiesOverride.enableBlending : this._animation.enableBlending
    }
    return Object.defineProperty(a.prototype, "currentFrame", {
        get: function() {
            return this._currentFrame
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "weight", {
        get: function() {
            return this._weight
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "currentValue", {
        get: function() {
            return this._currentValue
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "targetPath", {
        get: function() {
            return this._targetPath
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "target", {
        get: function() {
            return this._currentActiveTarget
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isAdditive", {
        get: function() {
            return this._host && this._host.isAdditive
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._preparePath = function(e, i) {
        i === void 0 && (i = 0);
        var o = this._animation.targetPropertyPath;
        if (o.length > 1) {
            for (var s = e[o[0]], c = 1; c < o.length - 1; c++)
                s = s[o[c]];
            this._targetPath = o[o.length - 1],
            this._activeTargets[i] = s
        } else
            this._targetPath = o[0],
            this._activeTargets[i] = e
    }
    ,
    Object.defineProperty(a.prototype, "animation", {
        get: function() {
            return this._animation
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.reset = function(e) {
        if (e === void 0 && (e = !1),
        e)
            if (this._target instanceof Array)
                for (var i = 0, o = 0, s = this._target; o < s.length; o++) {
                    var c = s[o];
                    this._originalValue[i] !== void 0 && this._setValue(c, this._activeTargets[i], this._originalValue[i], -1, i),
                    i++
                }
            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 i = 0; i < this._events.length; i++)
            this._events[i].isDone = !1
    }
    ,
    a.prototype.isStopped = function() {
        return this._stopped
    }
    ,
    a.prototype.dispose = function() {
        var e = this._animation.runtimeAnimations.indexOf(this);
        e > -1 && this._animation.runtimeAnimations.splice(e, 1)
    }
    ,
    a.prototype.setValue = function(e, i) {
        if (this._targetIsArray) {
            for (var o = 0; o < this._target.length; o++) {
                var s = this._target[o];
                this._setValue(s, this._activeTargets[o], e, i, o)
            }
            return
        }
        this._setValue(this._target, this._directTarget, e, i, 0)
    }
    ,
    a.prototype._getOriginalValues = function(e) {
        e === void 0 && (e = 0);
        var i, o = this._activeTargets[e];
        o.getRestPose && this._targetPath === "_matrix" ? i = o.getRestPose() : i = o[this._targetPath],
        i && i.clone ? this._originalValue[e] = i.clone() : this._originalValue[e] = i
    }
    ,
    a.prototype._setValue = function(e, i, o, s, c) {
        if (this._currentActiveTarget = i,
        this._weight = s,
        this._enableBlending && this._blendingFactor <= 1) {
            if (!this._originalBlendValue) {
                var d = i[this._targetPath];
                d.clone ? this._originalBlendValue = d.clone() : this._originalBlendValue = d
            }
            this._originalBlendValue.m ? Animation.AllowMatrixDecomposeForInterpolation ? this._currentValue ? Matrix.DecomposeLerpToRef(this._originalBlendValue, o, this._blendingFactor, this._currentValue) : this._currentValue = Matrix.DecomposeLerp(this._originalBlendValue, o, this._blendingFactor) : this._currentValue ? Matrix.LerpToRef(this._originalBlendValue, o, this._blendingFactor, this._currentValue) : this._currentValue = Matrix.Lerp(this._originalBlendValue, o, this._blendingFactor) : this._currentValue = Animation._UniversalLerp(this._originalBlendValue, o, this._blendingFactor);
            var _ = e && e.animationPropertiesOverride ? e.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
            this._blendingFactor += _
        } else
            this._currentValue ? this._currentValue.copyFrom ? this._currentValue.copyFrom(o) : this._currentValue = o : o != null && o.clone ? this._currentValue = o.clone() : this._currentValue = o;
        s !== -1 ? this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[c]) : i[this._targetPath] = this._currentValue,
        e.markAsDirty && e.markAsDirty(this._animation.targetProperty)
    }
    ,
    a.prototype._getCorrectLoopMode = function() {
        return this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.loopMode : this._animation.loopMode
    }
    ,
    a.prototype.goToFrame = function(e) {
        var i = this._animation.getKeys();
        e < i[0].frame ? e = i[0].frame : e > i[i.length - 1].frame && (e = i[i.length - 1].frame);
        var o = this._events;
        if (o.length)
            for (var s = 0; s < o.length; s++)
                o[s].onlyOnce || (o[s].isDone = o[s].frame < e);
        this._currentFrame = e;
        var c = this._animation._interpolate(e, this._animationState);
        this.setValue(c, -1)
    }
    ,
    a.prototype._prepareForSpeedRatioChange = function(e) {
        var i = this._previousDelay * (this._animation.framePerSecond * e) / 1e3;
        this._ratioOffset = this._previousRatio - i
    }
    ,
    a.prototype.animate = function(e, i, o, s, c, d) {
        d === void 0 && (d = -1);
        var _ = this._animation
          , b = _.targetPropertyPath;
        if (!b || b.length < 1)
            return this._stopped = !0,
            !1;
        var k = !0;
        (i < this._minFrame || i > this._maxFrame) && (i = this._minFrame),
        (o < this._minFrame || o > this._maxFrame) && (o = this._maxFrame);
        var j = o - i, $, _e = e * (_.framePerSecond * c) / 1e3 + this._ratioOffset, et = 0;
        if (this._previousDelay = e,
        this._previousRatio = _e,
        !s && o >= i && _e >= j)
            k = !1,
            et = _._getKeyValue(this._maxValue);
        else if (!s && i >= o && _e <= j)
            k = !1,
            et = _._getKeyValue(this._minValue);
        else if (this._animationState.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
            var tt = o.toString() + i.toString();
            if (!this._offsetsCache[tt]) {
                this._animationState.repeatCount = 0,
                this._animationState.loopMode = Animation.ANIMATIONLOOPMODE_CYCLE;
                var rt = _._interpolate(i, this._animationState)
                  , it = _._interpolate(o, this._animationState);
                switch (this._animationState.loopMode = this._getCorrectLoopMode(),
                _.dataType) {
                case Animation.ANIMATIONTYPE_FLOAT:
                    this._offsetsCache[tt] = it - rt;
                    break;
                case Animation.ANIMATIONTYPE_QUATERNION:
                    this._offsetsCache[tt] = it.subtract(rt);
                    break;
                case Animation.ANIMATIONTYPE_VECTOR3:
                    this._offsetsCache[tt] = it.subtract(rt);
                    break;
                case Animation.ANIMATIONTYPE_VECTOR2:
                    this._offsetsCache[tt] = it.subtract(rt);
                    break;
                case Animation.ANIMATIONTYPE_SIZE:
                    this._offsetsCache[tt] = it.subtract(rt);
                    break;
                case Animation.ANIMATIONTYPE_COLOR3:
                    this._offsetsCache[tt] = it.subtract(rt);
                    break
                }
                this._highLimitsCache[tt] = it
            }
            et = this._highLimitsCache[tt],
            $ = this._offsetsCache[tt]
        }
        if ($ === void 0)
            switch (_.dataType) {
            case Animation.ANIMATIONTYPE_FLOAT:
                $ = 0;
                break;
            case Animation.ANIMATIONTYPE_QUATERNION:
                $ = _staticOffsetValueQuaternion;
                break;
            case Animation.ANIMATIONTYPE_VECTOR3:
                $ = _staticOffsetValueVector3;
                break;
            case Animation.ANIMATIONTYPE_VECTOR2:
                $ = _staticOffsetValueVector2;
                break;
            case Animation.ANIMATIONTYPE_SIZE:
                $ = _staticOffsetValueSize;
                break;
            case Animation.ANIMATIONTYPE_COLOR3:
                $ = _staticOffsetValueColor3
            }
        var nt;
        if (this._host && this._host.syncRoot) {
            var ot = this._host.syncRoot
              , at = (ot.masterFrame - ot.fromFrame) / (ot.toFrame - ot.fromFrame);
            nt = i + (o - i) * at
        } else
            _e > 0 && i > o || _e < 0 && i < o ? nt = k && j !== 0 ? o + _e % j : i : nt = k && j !== 0 ? i + _e % j : o;
        var st = this._events;
        if ((c > 0 && this.currentFrame > nt || c < 0 && this.currentFrame < nt) && (this._onLoop(),
        st.length))
            for (var ut = 0; ut < st.length; ut++)
                st[ut].onlyOnce || (st[ut].isDone = !1);
        this._currentFrame = nt,
        this._animationState.repeatCount = j === 0 ? 0 : _e / j >> 0,
        this._animationState.highLimitValue = et,
        this._animationState.offsetValue = $;
        var ct = _._interpolate(nt, this._animationState);
        if (this.setValue(ct, d),
        st.length) {
            for (var ut = 0; ut < st.length; ut++)
                if (j > 0 && nt >= st[ut].frame && st[ut].frame >= i || j < 0 && nt <= st[ut].frame && st[ut].frame <= i) {
                    var lt = st[ut];
                    lt.isDone || (lt.onlyOnce && (st.splice(ut, 1),
                    ut--),
                    lt.isDone = !0,
                    lt.action(nt))
                }
        }
        return k || (this._stopped = !0),
        k
    }
    ,
    a
}()
  , Bone = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b) {
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null);
        var k = a.call(this, i, o.getScene()) || this;
        return k.name = i,
        k.children = new Array,
        k.animations = new Array,
        k._index = null,
        k._absoluteTransform = new Matrix,
        k._invertedAbsoluteTransform = new Matrix,
        k._scalingDeterminant = 1,
        k._worldTransform = new Matrix,
        k._needToDecompose = !0,
        k._needToCompose = !1,
        k._linkedTransformNode = null,
        k._waitingTransformNodeId = null,
        k._skeleton = o,
        k._localMatrix = c ? c.clone() : Matrix.Identity(),
        k._restPose = d || k._localMatrix.clone(),
        k._baseMatrix = _ || k._localMatrix.clone(),
        k._index = b,
        o.bones.push(k),
        k.setParent(s, !1),
        (_ || c) && k._updateDifferenceMatrix(),
        k
    }
    return Object.defineProperty(e.prototype, "_matrix", {
        get: function() {
            return this._compose(),
            this._localMatrix
        },
        set: function(i) {
            this._needToCompose = !1,
            i.updateFlag !== this._localMatrix.updateFlag && (this._localMatrix.copyFrom(i),
            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(i, o) {
        if (o === void 0 && (o = !0),
        this._parent !== i) {
            if (this._parent) {
                var s = this._parent.children.indexOf(this);
                s !== -1 && this._parent.children.splice(s, 1)
            }
            this._parent = i,
            this._parent && this._parent.children.push(this),
            o && 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(i) {
        this._restPose.copyFrom(i)
    }
    ,
    e.prototype.getBindPose = function() {
        return this._baseMatrix
    }
    ,
    e.prototype.setBindPose = function(i) {
        this.updateMatrix(i)
    }
    ,
    e.prototype.getWorldMatrix = function() {
        return this._worldTransform
    }
    ,
    e.prototype.returnToRest = function() {
        var i;
        if (this._linkedTransformNode) {
            var o = TmpVectors.Vector3[0]
              , s = TmpVectors.Quaternion[0]
              , c = TmpVectors.Vector3[1];
            this.getRestPose().decompose(o, s, c),
            this._linkedTransformNode.position.copyFrom(c),
            this._linkedTransformNode.rotationQuaternion = (i = this._linkedTransformNode.rotationQuaternion) !== null && i !== void 0 ? i : Quaternion.Identity(),
            this._linkedTransformNode.rotationQuaternion.copyFrom(s),
            this._linkedTransformNode.scaling.copyFrom(o)
        } else
            this._matrix = this._restPose
    }
    ,
    e.prototype.getInvertedAbsoluteTransform = function() {
        return this._invertedAbsoluteTransform
    }
    ,
    e.prototype.getAbsoluteTransform = function() {
        return this._absoluteTransform
    }
    ,
    e.prototype.linkTransformNode = function(i) {
        this._linkedTransformNode && this._skeleton._numBonesWithLinkedTransformNode--,
        this._linkedTransformNode = i,
        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(i) {
            this._decompose(),
            this._localPosition.copyFrom(i),
            this._markAsDirtyAndCompose()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotation", {
        get: function() {
            return this.getRotation()
        },
        set: function(i) {
            this.setRotation(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotationQuaternion", {
        get: function() {
            return this._decompose(),
            this._localRotation
        },
        set: function(i) {
            this.setRotationQuaternion(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaling", {
        get: function() {
            return this.getScale()
        },
        set: function(i) {
            this.setScale(i)
        },
        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(i, o, s) {
        o === void 0 && (o = !0),
        s === void 0 && (s = !0),
        this._baseMatrix.copyFrom(i),
        o && this._updateDifferenceMatrix(),
        s ? this._matrix = i : this.markAsDirty()
    }
    ,
    e.prototype._updateDifferenceMatrix = function(i, o) {
        if (o === void 0 && (o = !0),
        i || (i = this._baseMatrix),
        this._parent ? i.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform) : this._absoluteTransform.copyFrom(i),
        this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform),
        o)
            for (var s = 0; s < this.children.length; s++)
                this.children[s]._updateDifferenceMatrix();
        this._scalingDeterminant = this._absoluteTransform.determinant() < 0 ? -1 : 1
    }
    ,
    e.prototype.markAsDirty = function(i) {
        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(i, o, s) {
        o === void 0 && (o = Space.LOCAL);
        var c = this.getLocalMatrix();
        if (o == Space.LOCAL)
            c.addAtIndex(12, i.x),
            c.addAtIndex(13, i.y),
            c.addAtIndex(14, i.z);
        else {
            var d = null;
            s && (d = s.getWorldMatrix()),
            this._skeleton.computeAbsoluteTransforms();
            var _ = e._tmpMats[0]
              , b = e._tmpVecs[0];
            this._parent ? s && d ? (_.copyFrom(this._parent.getAbsoluteTransform()),
            _.multiplyToRef(d, _)) : _.copyFrom(this._parent.getAbsoluteTransform()) : Matrix.IdentityToRef(_),
            _.setTranslationFromFloats(0, 0, 0),
            _.invert(),
            Vector3.TransformCoordinatesToRef(i, _, b),
            c.addAtIndex(12, b.x),
            c.addAtIndex(13, b.y),
            c.addAtIndex(14, b.z)
        }
        this._markAsDirtyAndDecompose()
    }
    ,
    e.prototype.setPosition = function(i, o, s) {
        o === void 0 && (o = Space.LOCAL);
        var c = this.getLocalMatrix();
        if (o == Space.LOCAL)
            c.setTranslationFromFloats(i.x, i.y, i.z);
        else {
            var d = null;
            s && (d = s.getWorldMatrix()),
            this._skeleton.computeAbsoluteTransforms();
            var _ = e._tmpMats[0]
              , b = e._tmpVecs[0];
            this._parent ? (s && d ? (_.copyFrom(this._parent.getAbsoluteTransform()),
            _.multiplyToRef(d, _)) : _.copyFrom(this._parent.getAbsoluteTransform()),
            _.invert()) : Matrix.IdentityToRef(_),
            Vector3.TransformCoordinatesToRef(i, _, b),
            c.setTranslationFromFloats(b.x, b.y, b.z)
        }
        this._markAsDirtyAndDecompose()
    }
    ,
    e.prototype.setAbsolutePosition = function(i, o) {
        this.setPosition(i, Space.WORLD, o)
    }
    ,
    e.prototype.scale = function(i, o, s, c) {
        c === void 0 && (c = !1);
        var d = this.getLocalMatrix()
          , _ = e._tmpMats[0];
        Matrix.ScalingToRef(i, o, s, _),
        _.multiplyToRef(d, d),
        _.invert();
        for (var b = 0, k = this.children; b < k.length; b++) {
            var j = k[b]
              , $ = j.getLocalMatrix();
            $.multiplyToRef(_, $),
            $.multiplyAtIndex(12, i),
            $.multiplyAtIndex(13, o),
            $.multiplyAtIndex(14, s),
            j._markAsDirtyAndDecompose()
        }
        if (this._markAsDirtyAndDecompose(),
        c)
            for (var _e = 0, et = this.children; _e < et.length; _e++) {
                var j = et[_e];
                j.scale(i, o, s, c)
            }
    }
    ,
    e.prototype.setScale = function(i) {
        this._decompose(),
        this._localScaling.copyFrom(i),
        this._markAsDirtyAndCompose()
    }
    ,
    e.prototype.getScale = function() {
        return this._decompose(),
        this._localScaling
    }
    ,
    e.prototype.getScaleToRef = function(i) {
        this._decompose(),
        i.copyFrom(this._localScaling)
    }
    ,
    e.prototype.setYawPitchRoll = function(i, o, s, c, d) {
        if (c === void 0 && (c = Space.LOCAL),
        c === Space.LOCAL) {
            var _ = e._tmpQuat;
            Quaternion.RotationYawPitchRollToRef(i, o, s, _),
            this.setRotationQuaternion(_, c, d);
            return
        }
        var b = e._tmpMats[0];
        if (!!this._getNegativeRotationToRef(b, d)) {
            var k = e._tmpMats[1];
            Matrix.RotationYawPitchRollToRef(i, o, s, k),
            b.multiplyToRef(k, k),
            this._rotateWithMatrix(k, c, d)
        }
    }
    ,
    e.prototype.rotate = function(i, o, s, c) {
        s === void 0 && (s = Space.LOCAL);
        var d = e._tmpMats[0];
        d.setTranslationFromFloats(0, 0, 0),
        Matrix.RotationAxisToRef(i, o, d),
        this._rotateWithMatrix(d, s, c)
    }
    ,
    e.prototype.setAxisAngle = function(i, o, s, c) {
        if (s === void 0 && (s = Space.LOCAL),
        s === Space.LOCAL) {
            var d = e._tmpQuat;
            Quaternion.RotationAxisToRef(i, o, d),
            this.setRotationQuaternion(d, s, c);
            return
        }
        var _ = e._tmpMats[0];
        if (!!this._getNegativeRotationToRef(_, c)) {
            var b = e._tmpMats[1];
            Matrix.RotationAxisToRef(i, o, b),
            _.multiplyToRef(b, b),
            this._rotateWithMatrix(b, s, c)
        }
    }
    ,
    e.prototype.setRotation = function(i, o, s) {
        o === void 0 && (o = Space.LOCAL),
        this.setYawPitchRoll(i.y, i.x, i.z, o, s)
    }
    ,
    e.prototype.setRotationQuaternion = function(i, o, s) {
        if (o === void 0 && (o = Space.LOCAL),
        o === Space.LOCAL) {
            this._decompose(),
            this._localRotation.copyFrom(i),
            this._markAsDirtyAndCompose();
            return
        }
        var c = e._tmpMats[0];
        if (!!this._getNegativeRotationToRef(c, s)) {
            var d = e._tmpMats[1];
            Matrix.FromQuaternionToRef(i, d),
            c.multiplyToRef(d, d),
            this._rotateWithMatrix(d, o, s)
        }
    }
    ,
    e.prototype.setRotationMatrix = function(i, o, s) {
        if (o === void 0 && (o = Space.LOCAL),
        o === Space.LOCAL) {
            var c = e._tmpQuat;
            Quaternion.FromRotationMatrixToRef(i, c),
            this.setRotationQuaternion(c, o, s);
            return
        }
        var d = e._tmpMats[0];
        if (!!this._getNegativeRotationToRef(d, s)) {
            var _ = e._tmpMats[1];
            _.copyFrom(i),
            d.multiplyToRef(i, _),
            this._rotateWithMatrix(_, o, s)
        }
    }
    ,
    e.prototype._rotateWithMatrix = function(i, o, s) {
        o === void 0 && (o = Space.LOCAL);
        var c = this.getLocalMatrix()
          , d = c.m[12]
          , _ = c.m[13]
          , b = c.m[14]
          , k = this.getParent()
          , j = e._tmpMats[3]
          , $ = e._tmpMats[4];
        k && o == Space.WORLD ? (s ? (j.copyFrom(s.getWorldMatrix()),
        k.getAbsoluteTransform().multiplyToRef(j, j)) : j.copyFrom(k.getAbsoluteTransform()),
        $.copyFrom(j),
        $.invert(),
        c.multiplyToRef(j, c),
        c.multiplyToRef(i, c),
        c.multiplyToRef($, c)) : o == Space.WORLD && s ? (j.copyFrom(s.getWorldMatrix()),
        $.copyFrom(j),
        $.invert(),
        c.multiplyToRef(j, c),
        c.multiplyToRef(i, c),
        c.multiplyToRef($, c)) : c.multiplyToRef(i, c),
        c.setTranslationFromFloats(d, _, b),
        this.computeAbsoluteTransforms(),
        this._markAsDirtyAndDecompose()
    }
    ,
    e.prototype._getNegativeRotationToRef = function(i, o) {
        var s = e._tmpMats[2];
        return i.copyFrom(this.getAbsoluteTransform()),
        o && (i.multiplyToRef(o.getWorldMatrix(), i),
        Matrix.ScalingToRef(o.scaling.x, o.scaling.y, o.scaling.z, s)),
        i.invert(),
        isNaN(i.m[0]) ? !1 : (s.multiplyAtIndex(0, this._scalingDeterminant),
        i.multiplyToRef(s, i),
        !0)
    }
    ,
    e.prototype.getPosition = function(i, o) {
        i === void 0 && (i = Space.LOCAL),
        o === void 0 && (o = null);
        var s = Vector3.Zero();
        return this.getPositionToRef(i, o, s),
        s
    }
    ,
    e.prototype.getPositionToRef = function(i, o, s) {
        if (i === void 0 && (i = Space.LOCAL),
        i == Space.LOCAL) {
            var c = this.getLocalMatrix();
            s.x = c.m[12],
            s.y = c.m[13],
            s.z = c.m[14]
        } else {
            var d = null;
            o && (d = o.getWorldMatrix()),
            this._skeleton.computeAbsoluteTransforms();
            var _ = e._tmpMats[0];
            o && d ? (_.copyFrom(this.getAbsoluteTransform()),
            _.multiplyToRef(d, _)) : _ = this.getAbsoluteTransform(),
            s.x = _.m[12],
            s.y = _.m[13],
            s.z = _.m[14]
        }
    }
    ,
    e.prototype.getAbsolutePosition = function(i) {
        i === void 0 && (i = null);
        var o = Vector3.Zero();
        return this.getPositionToRef(Space.WORLD, i, o),
        o
    }
    ,
    e.prototype.getAbsolutePositionToRef = function(i, o) {
        this.getPositionToRef(Space.WORLD, i, o)
    }
    ,
    e.prototype.computeAbsoluteTransforms = function() {
        if (this._compose(),
        this._parent)
            this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
        else {
            this._absoluteTransform.copyFrom(this._localMatrix);
            var i = this._skeleton.getPoseMatrix();
            i && this._absoluteTransform.multiplyToRef(i, this._absoluteTransform)
        }
        for (var o = this.children, s = o.length, c = 0; c < s; c++)
            o[c].computeAbsoluteTransforms()
    }
    ,
    e.prototype.getDirection = function(i, o) {
        o === void 0 && (o = null);
        var s = Vector3.Zero();
        return this.getDirectionToRef(i, o, s),
        s
    }
    ,
    e.prototype.getDirectionToRef = function(i, o, s) {
        o === void 0 && (o = null);
        var c = null;
        o && (c = o.getWorldMatrix()),
        this._skeleton.computeAbsoluteTransforms();
        var d = e._tmpMats[0];
        d.copyFrom(this.getAbsoluteTransform()),
        o && c && d.multiplyToRef(c, d),
        Vector3.TransformNormalToRef(i, d, s),
        s.normalize()
    }
    ,
    e.prototype.getRotation = function(i, o) {
        i === void 0 && (i = Space.LOCAL),
        o === void 0 && (o = null);
        var s = Vector3.Zero();
        return this.getRotationToRef(i, o, s),
        s
    }
    ,
    e.prototype.getRotationToRef = function(i, o, s) {
        i === void 0 && (i = Space.LOCAL),
        o === void 0 && (o = null);
        var c = e._tmpQuat;
        this.getRotationQuaternionToRef(i, o, c),
        c.toEulerAnglesToRef(s)
    }
    ,
    e.prototype.getRotationQuaternion = function(i, o) {
        i === void 0 && (i = Space.LOCAL),
        o === void 0 && (o = null);
        var s = Quaternion.Identity();
        return this.getRotationQuaternionToRef(i, o, s),
        s
    }
    ,
    e.prototype.getRotationQuaternionToRef = function(i, o, s) {
        if (i === void 0 && (i = Space.LOCAL),
        o === void 0 && (o = null),
        i == Space.LOCAL)
            this._decompose(),
            s.copyFrom(this._localRotation);
        else {
            var c = e._tmpMats[0]
              , d = this.getAbsoluteTransform();
            o ? d.multiplyToRef(o.getWorldMatrix(), c) : c.copyFrom(d),
            c.multiplyAtIndex(0, this._scalingDeterminant),
            c.multiplyAtIndex(1, this._scalingDeterminant),
            c.multiplyAtIndex(2, this._scalingDeterminant),
            c.decompose(void 0, s, void 0)
        }
    }
    ,
    e.prototype.getRotationMatrix = function(i, o) {
        i === void 0 && (i = Space.LOCAL);
        var s = Matrix.Identity();
        return this.getRotationMatrixToRef(i, o, s),
        s
    }
    ,
    e.prototype.getRotationMatrixToRef = function(i, o, s) {
        if (i === void 0 && (i = Space.LOCAL),
        i == Space.LOCAL)
            this.getLocalMatrix().getRotationMatrixToRef(s);
        else {
            var c = e._tmpMats[0]
              , d = this.getAbsoluteTransform();
            o ? d.multiplyToRef(o.getWorldMatrix(), c) : c.copyFrom(d),
            c.multiplyAtIndex(0, this._scalingDeterminant),
            c.multiplyAtIndex(1, this._scalingDeterminant),
            c.multiplyAtIndex(2, this._scalingDeterminant),
            c.getRotationMatrixToRef(s)
        }
    }
    ,
    e.prototype.getAbsolutePositionFromLocal = function(i, o) {
        o === void 0 && (o = null);
        var s = Vector3.Zero();
        return this.getAbsolutePositionFromLocalToRef(i, o, s),
        s
    }
    ,
    e.prototype.getAbsolutePositionFromLocalToRef = function(i, o, s) {
        o === void 0 && (o = null);
        var c = null;
        o && (c = o.getWorldMatrix()),
        this._skeleton.computeAbsoluteTransforms();
        var d = e._tmpMats[0];
        o && c ? (d.copyFrom(this.getAbsoluteTransform()),
        d.multiplyToRef(c, d)) : d = this.getAbsoluteTransform(),
        Vector3.TransformCoordinatesToRef(i, d, s)
    }
    ,
    e.prototype.getLocalPositionFromAbsolute = function(i, o) {
        o === void 0 && (o = null);
        var s = Vector3.Zero();
        return this.getLocalPositionFromAbsoluteToRef(i, o, s),
        s
    }
    ,
    e.prototype.getLocalPositionFromAbsoluteToRef = function(i, o, s) {
        o === void 0 && (o = null);
        var c = null;
        o && (c = o.getWorldMatrix()),
        this._skeleton.computeAbsoluteTransforms();
        var d = e._tmpMats[0];
        d.copyFrom(this.getAbsoluteTransform()),
        o && c && d.multiplyToRef(c, d),
        d.invert(),
        Vector3.TransformCoordinatesToRef(i, d, s)
    }
    ,
    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 a(e, i, o, s, c, d, _, b, k, j) {
        o === void 0 && (o = 0),
        s === void 0 && (s = 100),
        c === void 0 && (c = !1),
        d === void 0 && (d = 1),
        j === void 0 && (j = !1),
        this.target = i,
        this.fromFrame = o,
        this.toFrame = s,
        this.loopAnimation = c,
        this.onAnimationEnd = _,
        this.onAnimationLoop = k,
        this.isAdditive = j,
        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,
        b && this.appendAnimations(i, b),
        this._speedRatio = d,
        e._activeAnimatables.push(this)
    }
    return Object.defineProperty(a.prototype, "syncRoot", {
        get: function() {
            return this._syncRoot
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "masterFrame", {
        get: function() {
            return this._runtimeAnimations.length === 0 ? 0 : this._runtimeAnimations[0].currentFrame
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "speedRatio", {
        get: function() {
            return this._speedRatio
        },
        set: function(e) {
            for (var i = 0; i < this._runtimeAnimations.length; i++) {
                var o = this._runtimeAnimations[i];
                o._prepareForSpeedRatioChange(e)
            }
            this._speedRatio = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.syncWith = function(e) {
        if (this._syncRoot = e,
        e) {
            var i = this._scene._activeAnimatables.indexOf(this);
            i > -1 && (this._scene._activeAnimatables.splice(i, 1),
            this._scene._activeAnimatables.push(this))
        }
        return this
    }
    ,
    a.prototype.getAnimations = function() {
        return this._runtimeAnimations
    }
    ,
    a.prototype.appendAnimations = function(e, i) {
        for (var o = this, s = 0; s < i.length; s++) {
            var c = i[s]
              , d = new RuntimeAnimation(e,c,this._scene,this);
            d._onLoop = function() {
                o.onAnimationLoopObservable.notifyObservers(o),
                o.onAnimationLoop && o.onAnimationLoop()
            }
            ,
            this._runtimeAnimations.push(d)
        }
    }
    ,
    a.prototype.getAnimationByTargetProperty = function(e) {
        for (var i = this._runtimeAnimations, o = 0; o < i.length; o++)
            if (i[o].animation.targetProperty === e)
                return i[o].animation;
        return null
    }
    ,
    a.prototype.getRuntimeAnimationByTargetProperty = function(e) {
        for (var i = this._runtimeAnimations, o = 0; o < i.length; o++)
            if (i[o].animation.targetProperty === e)
                return i[o];
        return null
    }
    ,
    a.prototype.reset = function() {
        for (var e = this._runtimeAnimations, i = 0; i < e.length; i++)
            e[i].reset(!0);
        this._localDelayOffset = null,
        this._pausedDelay = null
    }
    ,
    a.prototype.enableBlending = function(e) {
        for (var i = this._runtimeAnimations, o = 0; o < i.length; o++)
            i[o].animation.enableBlending = !0,
            i[o].animation.blendingSpeed = e
    }
    ,
    a.prototype.disableBlending = function() {
        for (var e = this._runtimeAnimations, i = 0; i < e.length; i++)
            e[i].animation.enableBlending = !1
    }
    ,
    a.prototype.goToFrame = function(e) {
        var i, o = this._runtimeAnimations;
        if (o[0]) {
            var s = o[0].animation.framePerSecond;
            this._frameToSyncFromJump = (i = this._frameToSyncFromJump) !== null && i !== void 0 ? i : o[0].currentFrame;
            var c = this.speedRatio === 0 ? 0 : (e - this._frameToSyncFromJump) / s * 1e3 / this.speedRatio;
            this._manualJumpDelay = -c
        }
        for (var d = 0; d < o.length; d++)
            o[d].goToFrame(e)
    }
    ,
    a.prototype.pause = function() {
        this._paused || (this._paused = !0)
    }
    ,
    a.prototype.restart = function() {
        this._paused = !1
    }
    ,
    a.prototype._raiseOnAnimationEnd = function() {
        this.onAnimationEnd && this.onAnimationEnd(),
        this.onAnimationEndObservable.notifyObservers(this)
    }
    ,
    a.prototype.stop = function(e, i) {
        if (e || i) {
            var o = this._scene._activeAnimatables.indexOf(this);
            if (o > -1) {
                for (var s = this._runtimeAnimations, c = s.length - 1; c >= 0; c--) {
                    var d = s[c];
                    e && d.animation.name != e || i && !i(d.target) || (d.dispose(),
                    s.splice(c, 1))
                }
                s.length == 0 && (this._scene._activeAnimatables.splice(o, 1),
                this._raiseOnAnimationEnd())
            }
        } else {
            var c = this._scene._activeAnimatables.indexOf(this);
            if (c > -1) {
                this._scene._activeAnimatables.splice(c, 1);
                for (var s = this._runtimeAnimations, c = 0; c < s.length; c++)
                    s[c].dispose();
                this._raiseOnAnimationEnd()
            }
        }
    }
    ,
    a.prototype.waitAsync = function() {
        var e = this;
        return new Promise(function(i, o) {
            e.onAnimationEndObservable.add(function() {
                i(e)
            }, void 0, void 0, e, !0)
        }
        )
    }
    ,
    a.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 i = !1, o = this._runtimeAnimations, s;
        for (s = 0; s < o.length; s++) {
            var c = o[s]
              , d = c.animate(e - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
            i = i || d
        }
        if (this.animationStarted = i,
        !i) {
            if (this.disposeOnEnd)
                for (s = this._scene._activeAnimatables.indexOf(this),
                this._scene._activeAnimatables.splice(s, 1),
                s = 0; s < o.length; s++)
                    o[s].dispose();
            this._raiseOnAnimationEnd(),
            this.disposeOnEnd && (this.onAnimationEnd = null,
            this.onAnimationLoop = null,
            this.onAnimationLoopObservable.clear(),
            this.onAnimationEndObservable.clear())
        }
        return i
    }
    ,
    a
}();
Scene.prototype._animate = function() {
    if (!!this.animationsEnabled) {
        var a = PrecisionDate.Now;
        if (!this._animationTimeLast) {
            if (this._pendingData.length > 0)
                return;
            this._animationTimeLast = a
        }
        this.deltaTime = this.useConstantAnimationDeltaTime ? 16 : (a - this._animationTimeLast) * this.animationTimeScale,
        this._animationTimeLast = a;
        var e = this._activeAnimatables;
        if (e.length !== 0) {
            this._animationTime += this.deltaTime;
            for (var i = this._animationTime, o = 0; o < e.length; o++) {
                var s = e[o];
                !s._animate(i) && s.disposeOnEnd && o--
            }
            this._processLateAnimationBindings()
        }
    }
}
;
Scene.prototype.beginWeightedAnimation = function(a, e, i, o, s, c, d, _, b, k, j) {
    o === void 0 && (o = 1),
    c === void 0 && (c = 1),
    j === void 0 && (j = !1);
    var $ = this.beginAnimation(a, e, i, s, c, d, _, !1, b, k, j);
    return $.weight = o,
    $
}
;
Scene.prototype.beginAnimation = function(a, e, i, o, s, c, d, _, b, k, j) {
    s === void 0 && (s = 1),
    _ === void 0 && (_ = !0),
    j === void 0 && (j = !1),
    e > i && s > 0 && (s *= -1),
    _ && this.stopAnimation(a, void 0, b),
    d || (d = new Animatable(this,a,e,i,o,s,c,void 0,k,j));
    var $ = b ? b(a) : !0;
    if (a.animations && $ && d.appendAnimations(a, a.animations),
    a.getAnimatables)
        for (var _e = a.getAnimatables(), et = 0; et < _e.length; et++)
            this.beginAnimation(_e[et], e, i, o, s, c, d, _, b, k);
    return d.reset(),
    d
}
;
Scene.prototype.beginHierarchyAnimation = function(a, e, i, o, s, c, d, _, b, k, j, $) {
    c === void 0 && (c = 1),
    b === void 0 && (b = !0),
    $ === void 0 && ($ = !1);
    var _e = a.getDescendants(e)
      , et = [];
    et.push(this.beginAnimation(a, i, o, s, c, d, _, b, k, void 0, $));
    for (var tt = 0, rt = _e; tt < rt.length; tt++) {
        var it = rt[tt];
        et.push(this.beginAnimation(it, i, o, s, c, d, _, b, k, void 0, $))
    }
    return et
}
;
Scene.prototype.beginDirectAnimation = function(a, e, i, o, s, c, d, _, b) {
    if (b === void 0 && (b = !1),
    c === void 0 && (c = 1),
    i > o && c > 0)
        c *= -1;
    else if (o > i && c < 0) {
        var k = o;
        o = i,
        i = k
    }
    var j = new Animatable(this,a,i,o,s,c,d,e,_,b);
    return j
}
;
Scene.prototype.beginDirectHierarchyAnimation = function(a, e, i, o, s, c, d, _, b, k) {
    k === void 0 && (k = !1);
    var j = a.getDescendants(e)
      , $ = [];
    $.push(this.beginDirectAnimation(a, i, o, s, c, d, _, b, k));
    for (var _e = 0, et = j; _e < et.length; _e++) {
        var tt = et[_e];
        $.push(this.beginDirectAnimation(tt, i, o, s, c, d, _, b, k))
    }
    return $
}
;
Scene.prototype.getAnimatableByTarget = function(a) {
    for (var e = 0; e < this._activeAnimatables.length; e++)
        if (this._activeAnimatables[e].target === a)
            return this._activeAnimatables[e];
    return null
}
;
Scene.prototype.getAllAnimatablesByTarget = function(a) {
    for (var e = [], i = 0; i < this._activeAnimatables.length; i++)
        this._activeAnimatables[i].target === a && e.push(this._activeAnimatables[i]);
    return e
}
;
Scene.prototype.stopAnimation = function(a, e, i) {
    for (var o = this.getAllAnimatablesByTarget(a), s = 0, c = o; s < c.length; s++) {
        var d = c[s];
        d.stop(e, i)
    }
}
;
Scene.prototype.stopAllAnimations = function() {
    if (this._activeAnimatables) {
        for (var a = 0; a < this._activeAnimatables.length; a++)
            this._activeAnimatables[a].stop();
        this._activeAnimatables = []
    }
    for (var e = 0, i = this.animationGroups; e < i.length; e++) {
        var o = i[e];
        o.stop()
    }
}
;
Scene.prototype._registerTargetForLateAnimationBinding = function(a, e) {
    var i = a.target;
    this._registeredForLateAnimationBindings.pushNoDuplicate(i),
    i._lateAnimationHolders || (i._lateAnimationHolders = {}),
    i._lateAnimationHolders[a.targetPath] || (i._lateAnimationHolders[a.targetPath] = {
        totalWeight: 0,
        totalAdditiveWeight: 0,
        animations: [],
        additiveAnimations: [],
        originalValue: e
    }),
    a.isAdditive ? (i._lateAnimationHolders[a.targetPath].additiveAnimations.push(a),
    i._lateAnimationHolders[a.targetPath].totalAdditiveWeight += a.weight) : (i._lateAnimationHolders[a.targetPath].animations.push(a),
    i._lateAnimationHolders[a.targetPath].totalWeight += a.weight)
}
;
Scene.prototype._processLateAnimationBindingsForMatrices = function(a) {
    if (a.totalWeight === 0 && a.totalAdditiveWeight === 0)
        return a.originalValue;
    var e = 1
      , i = TmpVectors.Vector3[0]
      , o = TmpVectors.Vector3[1]
      , s = TmpVectors.Quaternion[0]
      , c = 0
      , d = a.animations[0]
      , _ = a.originalValue
      , b = 1
      , k = !1;
    if (a.totalWeight < 1)
        b = 1 - a.totalWeight,
        _.decompose(o, s, i);
    else {
        if (c = 1,
        e = a.totalWeight,
        b = d.weight / e,
        b == 1)
            if (a.totalAdditiveWeight)
                k = !0;
            else
                return d.currentValue;
        d.currentValue.decompose(o, s, i)
    }
    if (!k) {
        o.scaleInPlace(b),
        i.scaleInPlace(b),
        s.scaleInPlace(b);
        for (var j = c; j < a.animations.length; j++) {
            var $ = a.animations[j];
            if ($.weight !== 0) {
                var b = $.weight / e
                  , _e = TmpVectors.Vector3[2]
                  , et = TmpVectors.Vector3[3]
                  , tt = TmpVectors.Quaternion[1];
                $.currentValue.decompose(et, tt, _e),
                et.scaleAndAddToRef(b, o),
                tt.scaleAndAddToRef(b, s),
                _e.scaleAndAddToRef(b, i)
            }
        }
    }
    for (var rt = 0; rt < a.additiveAnimations.length; rt++) {
        var $ = a.additiveAnimations[rt];
        if ($.weight !== 0) {
            var _e = TmpVectors.Vector3[2]
              , et = TmpVectors.Vector3[3]
              , tt = TmpVectors.Quaternion[1];
            $.currentValue.decompose(et, tt, _e),
            et.multiplyToRef(o, et),
            Vector3.LerpToRef(o, et, $.weight, o),
            s.multiplyToRef(tt, tt),
            Quaternion.SlerpToRef(s, tt, $.weight, s),
            _e.scaleAndAddToRef($.weight, i)
        }
    }
    var it = d ? d._animationState.workValue : TmpVectors.Matrix[0].clone();
    return Matrix.ComposeToRef(o, s, i, it),
    it
}
;
Scene.prototype._processLateAnimationBindingsForQuaternions = function(a, e) {
    if (a.totalWeight === 0 && a.totalAdditiveWeight === 0)
        return e;
    var i = a.animations[0]
      , o = a.originalValue
      , s = e;
    if (a.totalWeight === 0 && a.totalAdditiveWeight > 0)
        s.copyFrom(o);
    else if (a.animations.length === 1) {
        if (Quaternion.SlerpToRef(o, i.currentValue, Math.min(1, a.totalWeight), s),
        a.totalAdditiveWeight === 0)
            return s
    } else if (a.animations.length > 1) {
        var c = 1
          , d = void 0
          , _ = void 0;
        if (a.totalWeight < 1) {
            var b = 1 - a.totalWeight;
            d = [],
            _ = [],
            d.push(o),
            _.push(b)
        } else {
            if (a.animations.length === 2 && (Quaternion.SlerpToRef(a.animations[0].currentValue, a.animations[1].currentValue, a.animations[1].weight / a.totalWeight, e),
            a.totalAdditiveWeight === 0))
                return e;
            d = [],
            _ = [],
            c = a.totalWeight
        }
        for (var k = 0; k < a.animations.length; k++) {
            var j = a.animations[k];
            d.push(j.currentValue),
            _.push(j.weight / c)
        }
        for (var $ = 0, _e = 0; _e < d.length; ) {
            if (!_e) {
                Quaternion.SlerpToRef(d[_e], d[_e + 1], _[_e + 1] / (_[_e] + _[_e + 1]), e),
                s = e,
                $ = _[_e] + _[_e + 1],
                _e += 2;
                continue
            }
            $ += _[_e],
            Quaternion.SlerpToRef(s, d[_e], _[_e] / $, s),
            _e++
        }
    }
    for (var et = 0; et < a.additiveAnimations.length; et++) {
        var j = a.additiveAnimations[et];
        j.weight !== 0 && (s.multiplyToRef(j.currentValue, TmpVectors.Quaternion[0]),
        Quaternion.SlerpToRef(s, TmpVectors.Quaternion[0], j.weight, s))
    }
    return s
}
;
Scene.prototype._processLateAnimationBindings = function() {
    if (!!this._registeredForLateAnimationBindings.length) {
        for (var a = 0; a < this._registeredForLateAnimationBindings.length; a++) {
            var e = this._registeredForLateAnimationBindings.data[a];
            for (var i in e._lateAnimationHolders) {
                var o = e._lateAnimationHolders[i]
                  , s = o.animations[0]
                  , c = o.originalValue
                  , d = Animation.AllowMatrixDecomposeForInterpolation && c.m
                  , _ = e[i];
                if (d)
                    _ = this._processLateAnimationBindingsForMatrices(o);
                else {
                    var b = c.w !== void 0;
                    if (b)
                        _ = this._processLateAnimationBindingsForQuaternions(o, _ || Quaternion.Identity());
                    else {
                        var k = 0
                          , j = 1;
                        if (o.totalWeight < 1)
                            s && c.scale ? _ = c.scale(1 - o.totalWeight) : s ? _ = c * (1 - o.totalWeight) : c.clone ? _ = c.clone() : _ = c;
                        else if (s) {
                            j = o.totalWeight;
                            var $ = s.weight / j;
                            $ !== 1 ? s.currentValue.scale ? _ = s.currentValue.scale($) : _ = s.currentValue * $ : _ = s.currentValue,
                            k = 1
                        }
                        for (var _e = k; _e < o.animations.length; _e++) {
                            var et = o.animations[_e]
                              , tt = et.weight / j;
                            if (tt)
                                et.currentValue.scaleAndAddToRef ? et.currentValue.scaleAndAddToRef(tt, _) : _ += et.currentValue * tt;
                            else
                                continue
                        }
                        for (var rt = 0; rt < o.additiveAnimations.length; rt++) {
                            var et = o.additiveAnimations[rt]
                              , tt = et.weight;
                            if (tt)
                                et.currentValue.scaleAndAddToRef ? et.currentValue.scaleAndAddToRef(tt, _) : _ += et.currentValue * tt;
                            else
                                continue
                        }
                    }
                }
                e[i] = _
            }
            e._lateAnimationHolders = {}
        }
        this._registeredForLateAnimationBindings.reset()
    }
}
;
Bone.prototype.copyAnimationRange = function(a, e, i, o, s) {
    o === void 0 && (o = !1),
    s === void 0 && (s = null),
    this.animations.length === 0 && (this.animations.push(new Animation(this.name,"_matrix",a.animations[0].framePerSecond,Animation.ANIMATIONTYPE_MATRIX,0)),
    this.animations[0].setKeys([]));
    var c = a.animations[0].getRange(e);
    if (!c)
        return !1;
    for (var d = c.from, _ = c.to, b = a.animations[0].getKeys(), k = a.length, j = a.getParent(), $ = this.getParent(), _e = o && j && k && this.length && k !== this.length, et = _e && $ && j ? $.length / j.length : 1, tt = o && !$ && s && (s.x !== 1 || s.y !== 1 || s.z !== 1), rt = this.animations[0].getKeys(), it, nt, ot, at = 0, st = b.length; at < st; at++)
        it = b[at],
        it.frame >= d && it.frame <= _ && (o ? (ot = it.value.clone(),
        _e ? (nt = ot.getTranslation(),
        ot.setTranslation(nt.scaleInPlace(et))) : tt && s ? (nt = ot.getTranslation(),
        ot.setTranslation(nt.multiplyInPlace(s))) : ot = it.value) : ot = it.value,
        rt.push({
            frame: it.frame + i,
            value: ot
        }));
    return this.animations[0].createRange(e, d + i, _ + i),
    !0
}
;
var TargetedAnimation = function() {
    function a() {}
    return a.prototype.getClassName = function() {
        return "TargetedAnimation"
    }
    ,
    a.prototype.serialize = function() {
        var e = {};
        return e.animation = this.animation.serialize(),
        e.targetId = this.target.id,
        e
    }
    ,
    a
}()
  , AnimationGroup = function() {
    function a(e, i) {
        i === void 0 && (i = 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 = i || EngineStore.LastCreatedScene,
        this.uniqueId = this._scene.getUniqueId(),
        this._scene.addAnimationGroup(this)
    }
    return Object.defineProperty(a.prototype, "from", {
        get: function() {
            return this._from
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "to", {
        get: function() {
            return this._to
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isStarted", {
        get: function() {
            return this._isStarted
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isPlaying", {
        get: function() {
            return this._isStarted && !this._isPaused
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "speedRatio", {
        get: function() {
            return this._speedRatio
        },
        set: function(e) {
            if (this._speedRatio !== e) {
                this._speedRatio = e;
                for (var i = 0; i < this._animatables.length; i++) {
                    var o = this._animatables[i];
                    o.speedRatio = this._speedRatio
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "loopAnimation", {
        get: function() {
            return this._loopAnimation
        },
        set: function(e) {
            if (this._loopAnimation !== e) {
                this._loopAnimation = e;
                for (var i = 0; i < this._animatables.length; i++) {
                    var o = this._animatables[i];
                    o.loopAnimation = this._loopAnimation
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isAdditive", {
        get: function() {
            return this._isAdditive
        },
        set: function(e) {
            if (this._isAdditive !== e) {
                this._isAdditive = e;
                for (var i = 0; i < this._animatables.length; i++) {
                    var o = this._animatables[i];
                    o.isAdditive = this._isAdditive
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "targetedAnimations", {
        get: function() {
            return this._targetedAnimations
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "animatables", {
        get: function() {
            return this._animatables
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "children", {
        get: function() {
            return this._targetedAnimations
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.addTargetedAnimation = function(e, i) {
        var o = new TargetedAnimation;
        o.animation = e,
        o.target = i;
        var s = e.getKeys();
        return this._from > s[0].frame && (this._from = s[0].frame),
        this._to < s[s.length - 1].frame && (this._to = s[s.length - 1].frame),
        this._targetedAnimations.push(o),
        o
    }
    ,
    a.prototype.normalize = function(e, i) {
        e === void 0 && (e = null),
        i === void 0 && (i = null),
        e == null && (e = this._from),
        i == null && (i = this._to);
        for (var o = 0; o < this._targetedAnimations.length; o++) {
            var s = this._targetedAnimations[o]
              , c = s.animation.getKeys()
              , d = c[0]
              , _ = c[c.length - 1];
            if (d.frame > e) {
                var b = {
                    frame: e,
                    value: d.value,
                    inTangent: d.inTangent,
                    outTangent: d.outTangent,
                    interpolation: d.interpolation
                };
                c.splice(0, 0, b)
            }
            if (_.frame < i) {
                var b = {
                    frame: i,
                    value: _.value,
                    inTangent: _.inTangent,
                    outTangent: _.outTangent,
                    interpolation: _.interpolation
                };
                c.push(b)
            }
        }
        return this._from = e,
        this._to = i,
        this
    }
    ,
    a.prototype._processLoop = function(e, i, o) {
        var s = this;
        e.onAnimationLoop = function() {
            s.onAnimationLoopObservable.notifyObservers(i),
            !s._animationLoopFlags[o] && (s._animationLoopFlags[o] = !0,
            s._animationLoopCount++,
            s._animationLoopCount === s._targetedAnimations.length && (s.onAnimationGroupLoopObservable.notifyObservers(s),
            s._animationLoopCount = 0,
            s._animationLoopFlags = []))
        }
    }
    ,
    a.prototype.start = function(e, i, o, s, c) {
        var d = this;
        if (e === void 0 && (e = !1),
        i === void 0 && (i = 1),
        this._isStarted || this._targetedAnimations.length === 0)
            return this;
        this._loopAnimation = e,
        this._animationLoopCount = 0,
        this._animationLoopFlags = [];
        for (var _ = function() {
            var j = b._targetedAnimations[k]
              , $ = b._scene.beginDirectAnimation(j.target, [j.animation], o !== void 0 ? o : b._from, s !== void 0 ? s : b._to, e, i, void 0, void 0, c !== void 0 ? c : b._isAdditive);
            $.onAnimationEnd = function() {
                d.onAnimationEndObservable.notifyObservers(j),
                d._checkAnimationGroupEnded($)
            }
            ,
            b._processLoop($, j, k),
            b._animatables.push($)
        }, b = this, k = 0; k < this._targetedAnimations.length; k++)
            _();
        return this._speedRatio = i,
        this._isStarted = !0,
        this._isPaused = !1,
        this.onAnimationGroupPlayObservable.notifyObservers(this),
        this
    }
    ,
    a.prototype.pause = function() {
        if (!this._isStarted)
            return this;
        this._isPaused = !0;
        for (var e = 0; e < this._animatables.length; e++) {
            var i = this._animatables[e];
            i.pause()
        }
        return this.onAnimationGroupPauseObservable.notifyObservers(this),
        this
    }
    ,
    a.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
    }
    ,
    a.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 i = this._animatables[e];
            i.reset()
        }
        return this
    }
    ,
    a.prototype.restart = function() {
        if (!this._isStarted)
            return this;
        for (var e = 0; e < this._animatables.length; e++) {
            var i = this._animatables[e];
            i.restart()
        }
        return this.onAnimationGroupPlayObservable.notifyObservers(this),
        this
    }
    ,
    a.prototype.stop = function() {
        if (!this._isStarted)
            return this;
        for (var e = this._animatables.slice(), i = 0; i < e.length; i++)
            e[i].stop();
        return this._isStarted = !1,
        this
    }
    ,
    a.prototype.setWeightForAllAnimatables = function(e) {
        for (var i = 0; i < this._animatables.length; i++) {
            var o = this._animatables[i];
            o.weight = e
        }
        return this
    }
    ,
    a.prototype.syncAllAnimationsWith = function(e) {
        for (var i = 0; i < this._animatables.length; i++) {
            var o = this._animatables[i];
            o.syncWith(e)
        }
        return this
    }
    ,
    a.prototype.goToFrame = function(e) {
        if (!this._isStarted)
            return this;
        for (var i = 0; i < this._animatables.length; i++) {
            var o = this._animatables[i];
            o.goToFrame(e)
        }
        return this
    }
    ,
    a.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 i = this._parentContainer.animationGroups.indexOf(this);
            i > -1 && this._parentContainer.animationGroups.splice(i, 1),
            this._parentContainer = null
        }
        this.onAnimationEndObservable.clear(),
        this.onAnimationGroupEndObservable.clear(),
        this.onAnimationGroupPauseObservable.clear(),
        this.onAnimationGroupPlayObservable.clear(),
        this.onAnimationLoopObservable.clear(),
        this.onAnimationGroupLoopObservable.clear()
    }
    ,
    a.prototype._checkAnimationGroupEnded = function(e) {
        var i = this._animatables.indexOf(e);
        i > -1 && this._animatables.splice(i, 1),
        this._animatables.length === 0 && (this._isStarted = !1,
        this.onAnimationGroupEndObservable.notifyObservers(this))
    }
    ,
    a.prototype.clone = function(e, i, o) {
        o === void 0 && (o = !1);
        for (var s = new a(e || this.name,this._scene), c = 0, d = this._targetedAnimations; c < d.length; c++) {
            var _ = d[c];
            s.addTargetedAnimation(o ? _.animation.clone() : _.animation, i ? i(_.target) : _.target)
        }
        return s
    }
    ,
    a.prototype.serialize = function() {
        var e = {};
        e.name = this.name,
        e.from = this.from,
        e.to = this.to,
        e.targetedAnimations = [];
        for (var i = 0; i < this.targetedAnimations.length; i++) {
            var o = this.targetedAnimations[i];
            e.targetedAnimations[i] = o.serialize()
        }
        return Tags && Tags.HasTags(this) && (e.tags = Tags.GetTags(this)),
        this.metadata && (e.metadata = this.metadata),
        e
    }
    ,
    a.Parse = function(e, i) {
        for (var o = new a(e.name,i), s = 0; s < e.targetedAnimations.length; s++) {
            var c = e.targetedAnimations[s]
              , d = Animation.Parse(c.animation)
              , _ = c.targetId;
            if (c.animation.property === "influence") {
                var b = i.getMorphTargetById(_);
                b && o.addTargetedAnimation(d, b)
            } else {
                var k = i.getNodeById(_);
                k != null && o.addTargetedAnimation(d, k)
            }
        }
        return e.from !== null && e.to !== null && o.normalize(e.from, e.to),
        Tags && Tags.AddTagsTo(o, e.tags),
        e.metadata !== void 0 && (o.metadata = e.metadata),
        o
    }
    ,
    a.MakeAnimationAdditive = function(e, i, o, s, c) {
        i === void 0 && (i = 0),
        s === void 0 && (s = !1);
        var d = e;
        s && (d = e.clone(c || d.name));
        for (var _ = d.targetedAnimations, b = 0; b < _.length; b++) {
            var k = _[b];
            Animation.MakeAnimationAdditive(k.animation, i, o)
        }
        return d.isAdditive = !0,
        d
    }
    ,
    a.prototype.getClassName = function() {
        return "AnimationGroup"
    }
    ,
    a.prototype.toString = function(e) {
        var i = "Name: " + this.name;
        return i += ", type: " + this.getClassName(),
        e && (i += ", from: " + this._from,
        i += ", to: " + this._to,
        i += ", isStarted: " + this._isStarted,
        i += ", speedRatio: " + this._speedRatio,
        i += ", targetedAnimations length: " + this._targetedAnimations.length,
        i += ", animatables length: " + this._animatables),
        i
    }
    ,
    a
}()
  , RawTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $) {
        _ === void 0 && (_ = !0),
        b === void 0 && (b = !1),
        k === void 0 && (k = 3),
        j === void 0 && (j = 0);
        var _e = a.call(this, null, d, !_, b, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, $) || this;
        return _e.format = c,
        _e._engine && (!_e._engine._caps.textureFloatLinearFiltering && j === 1 && (k = 1),
        !_e._engine._caps.textureHalfFloatLinearFiltering && j === 2 && (k = 1),
        _e._texture = _e._engine.createRawTexture(i, o, s, c, _, b, k, null, j, $ != null ? $ : 0),
        _e.wrapU = Texture.CLAMP_ADDRESSMODE,
        _e.wrapV = Texture.CLAMP_ADDRESSMODE),
        _e
    }
    return e.prototype.update = function(i) {
        this._getEngine().updateRawTexture(this._texture, i, this._texture.format, this._texture.invertY, null, this._texture.type)
    }
    ,
    e.CreateLuminanceTexture = function(i, o, s, c, d, _, b) {
        return d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = 3),
        new e(i,o,s,1,c,d,_,b)
    }
    ,
    e.CreateLuminanceAlphaTexture = function(i, o, s, c, d, _, b) {
        return d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = 3),
        new e(i,o,s,2,c,d,_,b)
    }
    ,
    e.CreateAlphaTexture = function(i, o, s, c, d, _, b) {
        return d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = 3),
        new e(i,o,s,0,c,d,_,b)
    }
    ,
    e.CreateRGBTexture = function(i, o, s, c, d, _, b, k) {
        return d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = 3),
        k === void 0 && (k = 0),
        new e(i,o,s,4,c,d,_,b,k)
    }
    ,
    e.CreateRGBATexture = function(i, o, s, c, d, _, b, k) {
        return d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = 3),
        k === void 0 && (k = 0),
        new e(i,o,s,5,c,d,_,b,k)
    }
    ,
    e.CreateRGBAStorageTexture = function(i, o, s, c, d, _, b, k) {
        return d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = 3),
        k === void 0 && (k = 0),
        new e(i,o,s,5,c,d,_,b,k,1)
    }
    ,
    e.CreateRTexture = function(i, o, s, c, d, _, b, k) {
        return d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = Texture.TRILINEAR_SAMPLINGMODE),
        k === void 0 && (k = 1),
        new e(i,o,s,6,c,d,_,b,k)
    }
    ,
    e.CreateRStorageTexture = function(i, o, s, c, d, _, b, k) {
        return d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = Texture.TRILINEAR_SAMPLINGMODE),
        k === void 0 && (k = 1),
        new e(i,o,s,6,c,d,_,b,k,1)
    }
    ,
    e
}(Texture)
  , Skeleton = function() {
    function a(e, i, o) {
        this.name = e,
        this.id = i,
        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 = o || EngineStore.LastCreatedScene,
        this._uniqueId = this._scene.getUniqueId(),
        this._scene.addSkeleton(this),
        this._isDirty = !0;
        var s = this._scene.getEngine().getCaps();
        this._canUseTextureForBones = s.textureFloat && s.maxVertexTextureImageUnits > 0
    }
    return Object.defineProperty(a.prototype, "useTextureToStoreBoneMatrices", {
        get: function() {
            return this._useTextureToStoreBoneMatrices
        },
        set: function(e) {
            this._useTextureToStoreBoneMatrices = e,
            this._markAsDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "animationPropertiesOverride", {
        get: function() {
            return this._animationPropertiesOverride ? this._animationPropertiesOverride : this._scene.animationPropertiesOverride
        },
        set: function(e) {
            this._animationPropertiesOverride = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isUsingTextureForMatrices", {
        get: function() {
            return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getClassName = function() {
        return "Skeleton"
    }
    ,
    a.prototype.getChildren = function() {
        return this.bones.filter(function(e) {
            return !e.getParent()
        })
    }
    ,
    a.prototype.getTransformMatrices = function(e) {
        return this.needInitialSkinMatrix && e._bonesTransformMatrices ? e._bonesTransformMatrices : (this._transformMatrices || this.prepare(),
        this._transformMatrices)
    }
    ,
    a.prototype.getTransformMatrixTexture = function(e) {
        return this.needInitialSkinMatrix && e._transformMatrixTexture ? e._transformMatrixTexture : this._transformMatrixTexture
    }
    ,
    a.prototype.getScene = function() {
        return this._scene
    }
    ,
    a.prototype.toString = function(e) {
        var i = "Name: " + this.name + ", nBones: " + this.bones.length;
        if (i += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"),
        e) {
            i += ", Ranges: {";
            var o = !0;
            for (var s in this._ranges)
                o && (i += ", ",
                o = !1),
                i += s;
            i += "}"
        }
        return i
    }
    ,
    a.prototype.getBoneIndexByName = function(e) {
        for (var i = 0, o = this.bones.length; i < o; i++)
            if (this.bones[i].name === e)
                return i;
        return -1
    }
    ,
    a.prototype.createAnimationRange = function(e, i, o) {
        if (!this._ranges[e]) {
            this._ranges[e] = new AnimationRange(e,i,o);
            for (var s = 0, c = this.bones.length; s < c; s++)
                this.bones[s].animations[0] && this.bones[s].animations[0].createRange(e, i, o)
        }
    }
    ,
    a.prototype.deleteAnimationRange = function(e, i) {
        i === void 0 && (i = !0);
        for (var o = 0, s = this.bones.length; o < s; o++)
            this.bones[o].animations[0] && this.bones[o].animations[0].deleteRange(e, i);
        this._ranges[e] = null
    }
    ,
    a.prototype.getAnimationRange = function(e) {
        return this._ranges[e] || null
    }
    ,
    a.prototype.getAnimationRanges = function() {
        var e = [], i;
        for (i in this._ranges)
            e.push(this._ranges[i]);
        return e
    }
    ,
    a.prototype.copyAnimationRange = function(e, i, o) {
        if (o === void 0 && (o = !1),
        this._ranges[i] || !e.getAnimationRange(i))
            return !1;
        var s = !0, c = this._getHighestAnimationFrame() + 1, d = {}, _ = e.bones, b, k;
        for (k = 0,
        b = _.length; k < b; k++)
            d[_[k].name] = _[k];
        this.bones.length !== _.length && (Logger$2.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + _.length),
        s = !1);
        var j = o && this.dimensionsAtRest && e.dimensionsAtRest ? this.dimensionsAtRest.divide(e.dimensionsAtRest) : null;
        for (k = 0,
        b = this.bones.length; k < b; k++) {
            var $ = this.bones[k].name
              , _e = d[$];
            _e ? s = s && this.bones[k].copyAnimationRange(_e, i, c, o, j) : (Logger$2.Warn("copyAnimationRange: not same rig, missing source bone " + $),
            s = !1)
        }
        var et = e.getAnimationRange(i);
        return et && (this._ranges[i] = new AnimationRange(i,et.from + c,et.to + c)),
        s
    }
    ,
    a.prototype.returnToRest = function() {
        for (var e = 0, i = this.bones; e < i.length; e++) {
            var o = i[e];
            o._index !== -1 && o.returnToRest()
        }
    }
    ,
    a.prototype._getHighestAnimationFrame = function() {
        for (var e = 0, i = 0, o = this.bones.length; i < o; i++)
            if (this.bones[i].animations[0]) {
                var s = this.bones[i].animations[0].getHighestFrame();
                e < s && (e = s)
            }
        return e
    }
    ,
    a.prototype.beginAnimation = function(e, i, o, s) {
        var c = this.getAnimationRange(e);
        return c ? this._scene.beginAnimation(this, c.from, c.to, i, o, s) : null
    }
    ,
    a.MakeAnimationAdditive = function(e, i, o) {
        i === void 0 && (i = 0);
        var s = e.getAnimationRange(o);
        if (!s)
            return null;
        for (var c = e._scene.getAllAnimatablesByTarget(e), d = null, _ = 0; _ < c.length; _++) {
            var b = c[_];
            if (b.fromFrame === (s == null ? void 0 : s.from) && b.toFrame === (s == null ? void 0 : s.to)) {
                d = b;
                break
            }
        }
        for (var k = e.getAnimatables(), _ = 0; _ < k.length; _++) {
            var j = k[_]
              , $ = j.animations;
            if (!!$)
                for (var _e = 0; _e < $.length; _e++)
                    Animation.MakeAnimationAdditive($[_e], i, o)
        }
        return d && (d.isAdditive = !0),
        e
    }
    ,
    a.prototype._markAsDirty = function() {
        this._isDirty = !0
    }
    ,
    a.prototype._registerMeshWithPoseMatrix = function(e) {
        this._meshesWithPoseMatrix.push(e)
    }
    ,
    a.prototype._unregisterMeshWithPoseMatrix = function(e) {
        var i = this._meshesWithPoseMatrix.indexOf(e);
        i > -1 && this._meshesWithPoseMatrix.splice(i, 1)
    }
    ,
    a.prototype._computeTransformMatrices = function(e, i) {
        this.onBeforeComputeObservable.notifyObservers(this);
        for (var o = 0; o < this.bones.length; o++) {
            var s = this.bones[o];
            s._childUpdateId++;
            var c = s.getParent();
            if (c ? s.getLocalMatrix().multiplyToRef(c.getWorldMatrix(), s.getWorldMatrix()) : i ? s.getLocalMatrix().multiplyToRef(i, s.getWorldMatrix()) : s.getWorldMatrix().copyFrom(s.getLocalMatrix()),
            s._index !== -1) {
                var d = s._index === null ? o : s._index;
                s.getInvertedAbsoluteTransform().multiplyToArray(s.getWorldMatrix(), e, d * 16)
            }
        }
        this._identity.copyToArray(e, this.bones.length * 16)
    }
    ,
    a.prototype.prepare = function() {
        if (this._numBonesWithLinkedTransformNode > 0)
            for (var e = 0, i = this.bones; e < i.length; e++) {
                var o = i[e];
                o._linkedTransformNode && (o._linkedTransformNode.computeWorldMatrix(),
                o._matrix = o._linkedTransformNode._localMatrix)
            }
        if (!!this._isDirty) {
            if (this.needInitialSkinMatrix)
                for (var s = 0; s < this._meshesWithPoseMatrix.length; s++) {
                    var c = this._meshesWithPoseMatrix[s]
                      , d = c.getPoseMatrix();
                    if ((!c._bonesTransformMatrices || c._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) && (c._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1))),
                    this._synchronizedWithMesh !== c) {
                        this._synchronizedWithMesh = c;
                        for (var _ = 0; _ < this.bones.length; _++) {
                            var b = this.bones[_];
                            if (!b.getParent()) {
                                var k = b.getBaseMatrix();
                                k.multiplyToRef(d, TmpVectors.Matrix[1]),
                                b._updateDifferenceMatrix(TmpVectors.Matrix[1])
                            }
                        }
                        if (this.isUsingTextureForMatrices) {
                            var j = (this.bones.length + 1) * 4;
                            (!c._transformMatrixTexture || c._transformMatrixTexture.getSize().width !== j) && (c._transformMatrixTexture && c._transformMatrixTexture.dispose(),
                            c._transformMatrixTexture = RawTexture.CreateRGBATexture(c._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, !1, !1, 1, 1))
                        }
                    }
                    this._computeTransformMatrices(c._bonesTransformMatrices, d),
                    this.isUsingTextureForMatrices && c._transformMatrixTexture && c._transformMatrixTexture.update(c._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)
        }
    }
    ,
    a.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
    }
    ,
    a.prototype.clone = function(e, i) {
        var o = new a(e,i || e,this._scene);
        o.needInitialSkinMatrix = this.needInitialSkinMatrix,
        o.overrideMesh = this.overrideMesh;
        for (var s = 0; s < this.bones.length; s++) {
            var c = this.bones[s]
              , d = null
              , _ = c.getParent();
            if (_) {
                var b = this.bones.indexOf(_);
                d = o.bones[b]
            }
            var k = new Bone(c.name,o,d,c.getBaseMatrix().clone(),c.getRestPose().clone());
            k._index = c._index,
            c._linkedTransformNode && k.linkTransformNode(c._linkedTransformNode),
            DeepCopier.DeepCopy(c.animations, k.animations)
        }
        if (this._ranges) {
            o._ranges = {};
            for (var j in this._ranges) {
                var $ = this._ranges[j];
                $ && (o._ranges[j] = $.clone())
            }
        }
        return this._isDirty = !0,
        o
    }
    ,
    a.prototype.enableBlending = function(e) {
        e === void 0 && (e = .01),
        this.bones.forEach(function(i) {
            i.animations.forEach(function(o) {
                o.enableBlending = !0,
                o.blendingSpeed = e
            })
        })
    }
    ,
    a.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)
    }
    ,
    a.prototype.serialize = function() {
        var e, i, o = {};
        o.name = this.name,
        o.id = this.id,
        this.dimensionsAtRest && (o.dimensionsAtRest = this.dimensionsAtRest.asArray()),
        o.bones = [],
        o.needInitialSkinMatrix = this.needInitialSkinMatrix,
        o.overrideMeshId = (e = this.overrideMesh) === null || e === void 0 ? void 0 : e.id;
        for (var s = 0; s < this.bones.length; s++) {
            var c = this.bones[s]
              , d = c.getParent()
              , _ = {
                parentBoneIndex: d ? this.bones.indexOf(d) : -1,
                index: c.getIndex(),
                name: c.name,
                id: c.id,
                matrix: c.getBaseMatrix().toArray(),
                rest: c.getRestPose().toArray(),
                linkedTransformNodeId: (i = c.getTransformNode()) === null || i === void 0 ? void 0 : i.id
            };
            o.bones.push(_),
            c.length && (_.length = c.length),
            c.metadata && (_.metadata = c.metadata),
            c.animations && c.animations.length > 0 && (_.animation = c.animations[0].serialize()),
            o.ranges = [];
            for (var b in this._ranges) {
                var k = this._ranges[b];
                if (!!k) {
                    var j = {};
                    j.name = b,
                    j.from = k.from,
                    j.to = k.to,
                    o.ranges.push(j)
                }
            }
        }
        return o
    }
    ,
    a.Parse = function(e, i) {
        var o = new a(e.name,e.id,i);
        e.dimensionsAtRest && (o.dimensionsAtRest = Vector3.FromArray(e.dimensionsAtRest)),
        o.needInitialSkinMatrix = e.needInitialSkinMatrix,
        e.overrideMeshId && (o._hasWaitingData = !0,
        o._waitingOverrideMeshId = e.overrideMeshId);
        var s;
        for (s = 0; s < e.bones.length; s++) {
            var c = e.bones[s]
              , d = e.bones[s].index
              , _ = null;
            c.parentBoneIndex > -1 && (_ = o.bones[c.parentBoneIndex]);
            var b = c.rest ? Matrix.FromArray(c.rest) : null
              , k = new Bone(c.name,o,_,Matrix.FromArray(c.matrix),b,null,d);
            c.id !== void 0 && c.id !== null && (k.id = c.id),
            c.length && (k.length = c.length),
            c.metadata && (k.metadata = c.metadata),
            c.animation && k.animations.push(Animation.Parse(c.animation)),
            c.linkedTransformNodeId !== void 0 && c.linkedTransformNodeId !== null && (o._hasWaitingData = !0,
            k._waitingTransformNodeId = c.linkedTransformNodeId)
        }
        if (e.ranges)
            for (s = 0; s < e.ranges.length; s++) {
                var j = e.ranges[s];
                o.createAnimationRange(j.name, j.from, j.to)
            }
        return o
    }
    ,
    a.prototype.computeAbsoluteTransforms = function(e) {
        e === void 0 && (e = !1);
        var i = this._scene.getRenderId();
        (this._lastAbsoluteTransformsUpdateId != i || e) && (this.bones[0].computeAbsoluteTransforms(),
        this._lastAbsoluteTransformsUpdateId = i)
    }
    ,
    a.prototype.getPoseMatrix = function() {
        var e = null;
        return this._meshesWithPoseMatrix.length > 0 && (e = this._meshesWithPoseMatrix[0].getPoseMatrix()),
        e
    }
    ,
    a.prototype.sortBones = function() {
        for (var e = new Array, i = new Array(this.bones.length), o = 0; o < this.bones.length; o++)
            this._sortBones(o, e, i);
        this.bones = e
    }
    ,
    a.prototype._sortBones = function(e, i, o) {
        if (!o[e]) {
            o[e] = !0;
            var s = this.bones[e];
            s._index === void 0 && (s._index = e);
            var c = s.getParent();
            c && this._sortBones(this.bones.indexOf(c), i, o),
            i.push(s)
        }
    }
    ,
    a.prototype.setCurrentPoseAsRest = function() {
        this.bones.forEach(function(e) {
            e.setCurrentPoseAsRest()
        })
    }
    ,
    a
}()
  , IntersectionInfo = function() {
    function a(e, i, o) {
        this.bu = e,
        this.bv = i,
        this.distance = o,
        this.faceId = 0,
        this.subMeshId = 0
    }
    return a
}()
  , SubMesh = function() {
    function a(e, i, o, s, c, d, _, b, k) {
        b === void 0 && (b = !0),
        k === void 0 && (k = !0),
        this.materialIndex = e,
        this.verticesStart = i,
        this.verticesCount = o,
        this.indexStart = s,
        this.indexCount = c,
        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 = d,
        this._renderingMesh = _ || d,
        k && d.subMeshes.push(this),
        this._engine = this._mesh.getScene().getEngine(),
        this.resetDrawCache(),
        this._trianglePlanes = [],
        this._id = d.subMeshes.length - 1,
        b && (this.refreshBoundingInfo(),
        d.computeWorldMatrix(!0))
    }
    return Object.defineProperty(a.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 i, o = (i = this._mainDrawWrapperOverride) !== null && i !== void 0 ? i : this._getDrawWrapper(void 0, !0);
            o.defines = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._getDrawWrapper = function(e, i) {
        i === void 0 && (i = !1),
        e = e != null ? e : this._engine.currentRenderPassId;
        var o = this._drawWrappers[e];
        return !o && i && (this._drawWrappers[e] = o = new DrawWrapper(this._mesh.getScene().getEngine())),
        o
    }
    ,
    a.prototype._removeDrawWrapper = function(e, i) {
        var o;
        i === void 0 && (i = !0),
        i && ((o = this._drawWrappers[e]) === null || o === void 0 || o.dispose()),
        this._drawWrappers[e] = void 0
    }
    ,
    Object.defineProperty(a.prototype, "effect", {
        get: function() {
            var e, i;
            return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : (i = (e = this._getDrawWrapper()) === null || e === void 0 ? void 0 : e.effect) !== null && i !== void 0 ? i : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "_drawWrapperOverride", {
        get: function() {
            return this._mainDrawWrapperOverride
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._setMainDrawWrapperOverride = function(e) {
        this._mainDrawWrapperOverride = e
    }
    ,
    a.prototype.setEffect = function(e, i, o, s) {
        i === void 0 && (i = null),
        s === void 0 && (s = !0);
        var c = this._drawWrapper;
        c.setEffect(e, i, s),
        o !== void 0 && (c.materialContext = o),
        e || (c.defines = null,
        c.materialContext = void 0)
    }
    ,
    a.prototype.resetDrawCache = function() {
        if (this._drawWrappers)
            for (var e = 0, i = this._drawWrappers; e < i.length; e++) {
                var o = i[e];
                o == null || o.dispose()
            }
        this._drawWrappers = []
    }
    ,
    a.AddToMesh = function(e, i, o, s, c, d, _, b) {
        return b === void 0 && (b = !0),
        new a(e,i,o,s,c,d,_,b)
    }
    ,
    Object.defineProperty(a.prototype, "IsGlobal", {
        get: function() {
            return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices()
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getBoundingInfo = function() {
        return this.IsGlobal ? this._mesh.getBoundingInfo() : this._boundingInfo
    }
    ,
    a.prototype.setBoundingInfo = function(e) {
        return this._boundingInfo = e,
        this
    }
    ,
    a.prototype.getMesh = function() {
        return this._mesh
    }
    ,
    a.prototype.getRenderingMesh = function() {
        return this._renderingMesh
    }
    ,
    a.prototype.getReplacementMesh = function() {
        return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null
    }
    ,
    a.prototype.getEffectiveMesh = function() {
        var e = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;
        return e || this._renderingMesh
    }
    ,
    a.prototype.getMaterial = function() {
        var e, i = (e = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)) !== null && e !== void 0 ? e : this._renderingMesh.material;
        if (i == null)
            return this._mesh.getScene().defaultMaterial;
        if (this._IsMultiMaterial(i)) {
            var o = i.getSubMaterial(this.materialIndex);
            return this._currentMaterial !== o && (this._currentMaterial = o,
            this.resetDrawCache()),
            o
        }
        return i
    }
    ,
    a.prototype._IsMultiMaterial = function(e) {
        return e.getSubMaterial !== void 0
    }
    ,
    a.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 i = this._renderingMesh.getIndices(), o;
        if (this.indexStart === 0 && this.indexCount === i.length) {
            var s = this._renderingMesh.getBoundingInfo();
            o = {
                minimum: s.minimum.clone(),
                maximum: s.maximum.clone()
            }
        } else
            o = extractMinAndMaxIndexed(e, i, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
        return this._boundingInfo ? this._boundingInfo.reConstruct(o.minimum, o.maximum) : this._boundingInfo = new BoundingInfo(o.minimum,o.maximum),
        this
    }
    ,
    a.prototype._checkCollision = function(e) {
        var i = this.getBoundingInfo();
        return i._checkCollision(e)
    }
    ,
    a.prototype.updateBoundingInfo = function(e) {
        var i = this.getBoundingInfo();
        return i || (this.refreshBoundingInfo(),
        i = this.getBoundingInfo()),
        i && i.update(e),
        this
    }
    ,
    a.prototype.isInFrustum = function(e) {
        var i = this.getBoundingInfo();
        return i ? i.isInFrustum(e, this._mesh.cullingStrategy) : !1
    }
    ,
    a.prototype.isCompletelyInFrustum = function(e) {
        var i = this.getBoundingInfo();
        return i ? i.isCompletelyInFrustum(e) : !1
    }
    ,
    a.prototype.render = function(e) {
        return this._renderingMesh.render(this, e, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : void 0),
        this
    }
    ,
    a.prototype._getLinesIndexBuffer = function(e, i) {
        if (!this._linesIndexBuffer) {
            for (var o = [], s = this.indexStart; s < this.indexStart + this.indexCount; s += 3)
                o.push(e[s], e[s + 1], e[s + 1], e[s + 2], e[s + 2], e[s]);
            this._linesIndexBuffer = i.createIndexBuffer(o),
            this._linesIndexCount = o.length
        }
        return this._linesIndexBuffer
    }
    ,
    a.prototype.canIntersects = function(e) {
        var i = this.getBoundingInfo();
        return i ? e.intersectsBox(i.boundingBox) : !1
    }
    ,
    a.prototype.intersects = function(e, i, o, s, c) {
        var d = this.getMaterial();
        if (!d)
            return null;
        var _ = 3
          , b = !1;
        switch (d.fillMode) {
        case 3:
        case 4:
        case 5:
        case 6:
        case 8:
            return null;
        case 7:
            _ = 1,
            b = !0;
            break
        }
        return this._mesh.getClassName() === "InstancedLinesMesh" || this._mesh.getClassName() === "LinesMesh" ? o.length ? this._intersectLines(e, i, o, this._mesh.intersectionThreshold, s) : this._intersectUnIndexedLines(e, i, o, this._mesh.intersectionThreshold, s) : !o.length && this._mesh._unIndexed ? this._intersectUnIndexedTriangles(e, i, o, s, c) : this._intersectTriangles(e, i, o, _, b, s, c)
    }
    ,
    a.prototype._intersectLines = function(e, i, o, s, c) {
        for (var d = null, _ = this.indexStart; _ < this.indexStart + this.indexCount; _ += 2) {
            var b = i[o[_]]
              , k = i[o[_ + 1]]
              , j = e.intersectionSegment(b, k, s);
            if (!(j < 0) && (c || !d || j < d.distance) && (d = new IntersectionInfo(null,null,j),
            d.faceId = _ / 2,
            c))
                break
        }
        return d
    }
    ,
    a.prototype._intersectUnIndexedLines = function(e, i, o, s, c) {
        for (var d = null, _ = this.verticesStart; _ < this.verticesStart + this.verticesCount; _ += 2) {
            var b = i[_]
              , k = i[_ + 1]
              , j = e.intersectionSegment(b, k, s);
            if (!(j < 0) && (c || !d || j < d.distance) && (d = new IntersectionInfo(null,null,j),
            d.faceId = _ / 2,
            c))
                break
        }
        return d
    }
    ,
    a.prototype._intersectTriangles = function(e, i, o, s, c, d, _) {
        for (var b = null, k = -1, j = this.indexStart; j < this.indexStart + this.indexCount - (3 - s); j += s) {
            k++;
            var $ = o[j]
              , _e = o[j + 1]
              , et = o[j + 2];
            if (c && et === 4294967295) {
                j += 2;
                continue
            }
            var tt = i[$]
              , rt = i[_e]
              , it = i[et];
            if (!(!tt || !rt || !it) && !(_ && !_(tt, rt, it, e))) {
                var nt = e.intersectsTriangle(tt, rt, it);
                if (nt) {
                    if (nt.distance < 0)
                        continue;
                    if ((d || !b || nt.distance < b.distance) && (b = nt,
                    b.faceId = k,
                    d))
                        break
                }
            }
        }
        return b
    }
    ,
    a.prototype._intersectUnIndexedTriangles = function(e, i, o, s, c) {
        for (var d = null, _ = this.verticesStart; _ < this.verticesStart + this.verticesCount; _ += 3) {
            var b = i[_]
              , k = i[_ + 1]
              , j = i[_ + 2];
            if (!(c && !c(b, k, j, e))) {
                var $ = e.intersectsTriangle(b, k, j);
                if ($) {
                    if ($.distance < 0)
                        continue;
                    if ((s || !d || $.distance < d.distance) && (d = $,
                    d.faceId = _ / 3,
                    s))
                        break
                }
            }
        }
        return d
    }
    ,
    a.prototype._rebuild = function() {
        this._linesIndexBuffer && (this._linesIndexBuffer = null)
    }
    ,
    a.prototype.clone = function(e, i) {
        var o = new a(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,i,!1);
        if (!this.IsGlobal) {
            var s = this.getBoundingInfo();
            if (!s)
                return o;
            o._boundingInfo = new BoundingInfo(s.minimum,s.maximum)
        }
        return o
    }
    ,
    a.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()
    }
    ,
    a.prototype.getClassName = function() {
        return "SubMesh"
    }
    ,
    a.CreateFromIndices = function(e, i, o, s, c, d) {
        d === void 0 && (d = !0);
        for (var _ = Number.MAX_VALUE, b = -Number.MAX_VALUE, k = c || s, j = k.getIndices(), $ = i; $ < i + o; $++) {
            var _e = j[$];
            _e < _ && (_ = _e),
            _e > b && (b = _e)
        }
        return new a(e,_,b - _ + 1,i,o,s,c,d)
    }
    ,
    a
}()
  , Geometry = function() {
    function a(e, i, o, s, c) {
        s === void 0 && (s = !1),
        c === void 0 && (c = 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 = i.getUniqueId(),
        this._engine = i.getEngine(),
        this._meshes = [],
        this._scene = i,
        this._vertexBuffers = {},
        this._indices = [],
        this._updatable = s,
        o ? this.setAllVerticesData(o, s) : (this._totalVertices = 0,
        this._indices = []),
        this._engine.getCaps().vertexArrayObject && (this._vertexArrayObjects = {}),
        c && (this.applyToMesh(c),
        c.computeWorldMatrix(!0))
    }
    return Object.defineProperty(a.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
    }),
    a.CreateGeometryForMesh = function(e) {
        var i = new a(a.RandomId(),e.getScene());
        return i.applyToMesh(e),
        i
    }
    ,
    Object.defineProperty(a.prototype, "meshes", {
        get: function() {
            return this._meshes
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "extend", {
        get: function() {
            return this._extend
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getScene = function() {
        return this._scene
    }
    ,
    a.prototype.getEngine = function() {
        return this._engine
    }
    ,
    a.prototype.isReady = function() {
        return this.delayLoadState === 1 || this.delayLoadState === 0
    }
    ,
    Object.defineProperty(a.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
    }),
    a.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 i = this._vertexBuffers[e];
            i._rebuild()
        }
    }
    ,
    a.prototype.setAllVerticesData = function(e, i) {
        e.applyToGeometry(this, i),
        this.notifyUpdate()
    }
    ,
    a.prototype.setVerticesData = function(e, i, o, s) {
        o === void 0 && (o = !1),
        o && Array.isArray(i) && (i = new Float32Array(i));
        var c = new VertexBuffer(this._engine,i,e,o,this._meshes.length === 0,s);
        this.setVerticesBuffer(c)
    }
    ,
    a.prototype.removeVerticesData = function(e) {
        this._vertexBuffers[e] && (this._vertexBuffers[e].dispose(),
        delete this._vertexBuffers[e]),
        this._vertexArrayObjects && this._disposeVertexArrayObjects()
    }
    ,
    a.prototype.setVerticesBuffer = function(e, i, o) {
        i === void 0 && (i = null),
        o === void 0 && (o = !0);
        var s = e.getKind();
        this._vertexBuffers[s] && o && this._vertexBuffers[s].dispose(),
        e._buffer && e._buffer._increaseReferences(),
        this._vertexBuffers[s] = e;
        var c = this._meshes
          , d = c.length;
        if (s === VertexBuffer.PositionKind) {
            var _ = e.getData();
            i != null ? this._totalVertices = i : _ != null && (this._totalVertices = _.length / (e.type === VertexBuffer.BYTE ? e.byteStride : e.byteStride / 4)),
            this._updateExtend(_),
            this._resetPointsArrayCache();
            for (var b = 0; b < d; b++) {
                var k = c[b];
                k.buildBoundingInfo(this._extend.minimum, this._extend.maximum),
                k._createGlobalSubMesh(!1),
                k.computeWorldMatrix(!0),
                k.synchronizeInstances()
            }
        }
        this.notifyUpdate(s)
    }
    ,
    a.prototype.updateVerticesDataDirectly = function(e, i, o, s) {
        s === void 0 && (s = !1);
        var c = this.getVertexBuffer(e);
        !c || (c.updateDirectly(i, o, s),
        this.notifyUpdate(e))
    }
    ,
    a.prototype.updateVerticesData = function(e, i, o) {
        o === void 0 && (o = !1);
        var s = this.getVertexBuffer(e);
        !s || (s.update(i),
        e === VertexBuffer.PositionKind && this._updateBoundingInfo(o, i),
        this.notifyUpdate(e))
    }
    ,
    a.prototype._updateBoundingInfo = function(e, i) {
        if (e && this._updateExtend(i),
        this._resetPointsArrayCache(),
        e)
            for (var o = this._meshes, s = 0, c = o; s < c.length; s++) {
                var d = c[s];
                d.hasBoundingInfo ? d.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum) : d.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
                for (var _ = d.subMeshes, b = 0, k = _; b < k.length; b++) {
                    var j = k[b];
                    j.refreshBoundingInfo()
                }
            }
    }
    ,
    a.prototype._bind = function(e, i, o, s) {
        if (!!e) {
            i === void 0 && (i = this._indexBuffer);
            var c = this.getVertexBuffers();
            if (!!c) {
                if (i != this._indexBuffer || !this._vertexArrayObjects && !s) {
                    this._engine.bindBuffers(c, i, e, o);
                    return
                }
                var d = s || this._vertexArrayObjects;
                d[e.key] || (d[e.key] = this._engine.recordVertexArrayObject(c, i, e, o)),
                this._engine.bindVertexArrayObject(d[e.key], i)
            }
        }
    }
    ,
    a.prototype.getTotalVertices = function() {
        return this.isReady() ? this._totalVertices : 0
    }
    ,
    a.prototype.getVerticesData = function(e, i, o) {
        var s = this.getVertexBuffer(e);
        return s ? s.getFloatData(this._totalVertices, o || i && this._meshes.length !== 1) : null
    }
    ,
    a.prototype.isVertexBufferUpdatable = function(e) {
        var i = this._vertexBuffers[e];
        return i ? i.isUpdatable() : !1
    }
    ,
    a.prototype.getVertexBuffer = function(e) {
        return this.isReady() ? this._vertexBuffers[e] : null
    }
    ,
    a.prototype.getVertexBuffers = function() {
        return this.isReady() ? this._vertexBuffers : null
    }
    ,
    a.prototype.isVerticesDataPresent = function(e) {
        return this._vertexBuffers ? this._vertexBuffers[e] !== void 0 : this._delayInfo ? this._delayInfo.indexOf(e) !== -1 : !1
    }
    ,
    a.prototype.getVerticesDataKinds = function() {
        var e = [], i;
        if (!this._vertexBuffers && this._delayInfo)
            for (i in this._delayInfo)
                e.push(i);
        else
            for (i in this._vertexBuffers)
                e.push(i);
        return e
    }
    ,
    a.prototype.updateIndices = function(e, i, o) {
        if (o === void 0 && (o = !1),
        !!this._indexBuffer)
            if (!this._indexBufferIsUpdatable)
                this.setIndices(e, null, !0);
            else {
                var s = e.length !== this._indices.length;
                if (o || (this._indices = e.slice()),
                this._engine.updateDynamicIndexBuffer(this._indexBuffer, e, i),
                s)
                    for (var c = 0, d = this._meshes; c < d.length; c++) {
                        var _ = d[c];
                        _._createGlobalSubMesh(!0)
                    }
            }
    }
    ,
    a.prototype.setIndices = function(e, i, o) {
        i === void 0 && (i = null),
        o === void 0 && (o = !1),
        this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer),
        this._indices = e,
        this._indexBufferIsUpdatable = o,
        this._meshes.length !== 0 && this._indices && (this._indexBuffer = this._engine.createIndexBuffer(this._indices, o)),
        i != null && (this._totalVertices = i);
        for (var s = 0, c = this._meshes; s < c.length; s++) {
            var d = c[s];
            d._createGlobalSubMesh(!0),
            d.synchronizeInstances()
        }
        this.notifyUpdate()
    }
    ,
    a.prototype.getTotalIndices = function() {
        return this.isReady() ? this._indices.length : 0
    }
    ,
    a.prototype.getIndices = function(e, i) {
        if (!this.isReady())
            return null;
        var o = this._indices;
        return !i && (!e || this._meshes.length === 1) ? o : Tools.Slice(o)
    }
    ,
    a.prototype.getIndexBuffer = function() {
        return this.isReady() ? this._indexBuffer : null
    }
    ,
    a.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])
    }
    ,
    a.prototype.releaseForMesh = function(e, i) {
        var o = this._meshes
          , s = o.indexOf(e);
        s !== -1 && (o.splice(s, 1),
        this._vertexArrayObjects && e._invalidateInstanceVertexArrayObject(),
        e._geometry = null,
        o.length === 0 && i && this.dispose())
    }
    ,
    a.prototype.applyToMesh = function(e) {
        if (e._geometry !== this) {
            var i = e._geometry;
            i && i.releaseForMesh(e),
            this._vertexArrayObjects && e._invalidateInstanceVertexArrayObject();
            var o = this._meshes;
            e._geometry = this,
            e._internalAbstractMeshDataInfo._positions = null,
            this._scene.pushGeometry(this),
            o.push(e),
            this.isReady() ? this._applyToMesh(e) : this._boundingInfo && e.setBoundingInfo(this._boundingInfo)
        }
    }
    ,
    a.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))
    }
    ,
    a.prototype._applyToMesh = function(e) {
        var i = this._meshes.length;
        for (var o in this._vertexBuffers)
            i === 1 && this._vertexBuffers[o].create(),
            o === VertexBuffer.PositionKind && (this._extend || this._updateExtend(),
            e.buildBoundingInfo(this._extend.minimum, this._extend.maximum),
            e._createGlobalSubMesh(!1),
            e._updateBoundingInfo());
        i === 1 && this._indices && this._indices.length > 0 && (this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable)),
        e._syncGeometryWithMorphTargetManager(),
        e.synchronizeInstances()
    }
    ,
    a.prototype.notifyUpdate = function(e) {
        this.onGeometryUpdated && this.onGeometryUpdated(this, e),
        this._vertexArrayObjects && this._disposeVertexArrayObjects();
        for (var i = 0, o = this._meshes; i < o.length; i++) {
            var s = o[i];
            s._markSubMeshesAsAttributesDirty()
        }
    }
    ,
    a.prototype.load = function(e, i) {
        if (this.delayLoadState !== 2) {
            if (this.isReady()) {
                i && i();
                return
            }
            this.delayLoadState = 2,
            this._queueLoad(e, i)
        }
    }
    ,
    a.prototype._queueLoad = function(e, i) {
        var o = this;
        !this.delayLoadingFile || (e._addPendingData(this),
        e._loadFile(this.delayLoadingFile, function(s) {
            if (!!o._delayLoadingFunction) {
                o._delayLoadingFunction(JSON.parse(s), o),
                o.delayLoadState = 1,
                o._delayInfo = [],
                e._removePendingData(o);
                for (var c = o._meshes, d = c.length, _ = 0; _ < d; _++)
                    o._applyToMesh(c[_]);
                i && i()
            }
        }, void 0, !0))
    }
    ,
    a.prototype.toLeftHanded = function() {
        var e = this.getIndices(!1);
        if (e != null && e.length > 0) {
            for (var i = 0; i < e.length; i += 3) {
                var o = e[i + 0];
                e[i + 0] = e[i + 2],
                e[i + 2] = o
            }
            this.setIndices(e)
        }
        var s = this.getVerticesData(VertexBuffer.PositionKind, !1);
        if (s != null && s.length > 0) {
            for (var i = 0; i < s.length; i += 3)
                s[i + 2] = -s[i + 2];
            this.setVerticesData(VertexBuffer.PositionKind, s, !1)
        }
        var c = this.getVerticesData(VertexBuffer.NormalKind, !1);
        if (c != null && c.length > 0) {
            for (var i = 0; i < c.length; i += 3)
                c[i + 2] = -c[i + 2];
            this.setVerticesData(VertexBuffer.NormalKind, c, !1)
        }
    }
    ,
    a.prototype._resetPointsArrayCache = function() {
        this._positions = null
    }
    ,
    a.prototype._generatePointsArray = function() {
        if (this._positions)
            return !0;
        var e = this.getVerticesData(VertexBuffer.PositionKind);
        if (!e || e.length === 0)
            return !1;
        for (var i = this._positionsCache.length * 3, o = this._positionsCache.length; i < e.length; i += 3,
        ++o)
            this._positionsCache[o] = Vector3.FromArray(e, i);
        for (var i = 0, o = 0; i < e.length; i += 3,
        ++o)
            this._positionsCache[o].set(e[0 + i], e[1 + i], e[2 + i]);
        return this._positionsCache.length = e.length / 3,
        this._positions = this._positionsCache,
        !0
    }
    ,
    a.prototype.isDisposed = function() {
        return this._isDisposed
    }
    ,
    a.prototype._disposeVertexArrayObjects = function() {
        if (this._vertexArrayObjects) {
            for (var e in this._vertexArrayObjects)
                this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);
            this._vertexArrayObjects = {};
            for (var i = this._meshes, o = i.length, s = 0; s < o; s++)
                i[s]._invalidateInstanceVertexArrayObject()
        }
    }
    ,
    a.prototype.dispose = function() {
        var e = this._meshes, i = e.length, o;
        for (o = 0; o < i; o++)
            this.releaseForMesh(e[o]);
        this._meshes = [],
        this._disposeVertexArrayObjects();
        for (var s in this._vertexBuffers)
            this._vertexBuffers[s].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 c = this._parentContainer.geometries.indexOf(this);
            c > -1 && this._parentContainer.geometries.splice(c, 1),
            this._parentContainer = null
        }
        this._isDisposed = !0
    }
    ,
    a.prototype.copy = function(e) {
        var i = new VertexData;
        i.indices = [];
        var o = this.getIndices();
        if (o)
            for (var s = 0; s < o.length; s++)
                i.indices.push(o[s]);
        var c = !1, d = !1, _;
        for (_ in this._vertexBuffers) {
            var b = this.getVerticesData(_);
            if (b && (b instanceof Float32Array ? i.set(new Float32Array(b), _) : i.set(b.slice(0), _),
            !d)) {
                var k = this.getVertexBuffer(_);
                k && (c = k.isUpdatable(),
                d = !c)
            }
        }
        var j = new a(e,this._scene,i,c);
        j.delayLoadState = this.delayLoadState,
        j.delayLoadingFile = this.delayLoadingFile,
        j._delayLoadingFunction = this._delayLoadingFunction;
        for (_ in this._delayInfo)
            j._delayInfo = j._delayInfo || [],
            j._delayInfo.push(_);
        return j._boundingInfo = new BoundingInfo(this._extend.minimum,this._extend.maximum),
        j
    }
    ,
    a.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
    }
    ,
    a.prototype.toNumberArray = function(e) {
        return Array.isArray(e) ? e : Array.prototype.slice.call(e)
    }
    ,
    a.prototype.clearCachedData = function() {
        this._indices = [],
        this._resetPointsArrayCache();
        for (var e in this._vertexBuffers)
            !this._vertexBuffers.hasOwnProperty(e) || (this._vertexBuffers[e]._buffer._data = null)
    }
    ,
    a.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
    }
    ,
    a.ExtractFromMesh = function(e, i) {
        var o = e._geometry;
        return o ? o.copy(i) : null
    }
    ,
    a.RandomId = function() {
        return Tools.RandomId()
    }
    ,
    a._GetGeometryByLoadedUniqueId = function(e, i) {
        for (var o = 0; o < i.geometries.length; o++)
            if (i.geometries[o]._loadedUniqueId === e)
                return i.geometries[o];
        return null
    }
    ,
    a._ImportGeometry = function(e, i) {
        var o = i.getScene()
          , s = e.geometryUniqueId
          , c = e.geometryId;
        if (s || c) {
            var d = s ? this._GetGeometryByLoadedUniqueId(s, o) : o.getGeometryById(c);
            d && d.applyToMesh(i)
        } else if (e instanceof ArrayBuffer) {
            var _ = i._binaryInfo;
            if (_.positionsAttrDesc && _.positionsAttrDesc.count > 0) {
                var b = new Float32Array(e,_.positionsAttrDesc.offset,_.positionsAttrDesc.count);
                i.setVerticesData(VertexBuffer.PositionKind, b, !1)
            }
            if (_.normalsAttrDesc && _.normalsAttrDesc.count > 0) {
                var k = new Float32Array(e,_.normalsAttrDesc.offset,_.normalsAttrDesc.count);
                i.setVerticesData(VertexBuffer.NormalKind, k, !1)
            }
            if (_.tangetsAttrDesc && _.tangetsAttrDesc.count > 0) {
                var j = new Float32Array(e,_.tangetsAttrDesc.offset,_.tangetsAttrDesc.count);
                i.setVerticesData(VertexBuffer.TangentKind, j, !1)
            }
            if (_.uvsAttrDesc && _.uvsAttrDesc.count > 0) {
                var $ = new Float32Array(e,_.uvsAttrDesc.offset,_.uvsAttrDesc.count);
                i.setVerticesData(VertexBuffer.UVKind, $, !1)
            }
            if (_.uvs2AttrDesc && _.uvs2AttrDesc.count > 0) {
                var _e = new Float32Array(e,_.uvs2AttrDesc.offset,_.uvs2AttrDesc.count);
                i.setVerticesData(VertexBuffer.UV2Kind, _e, !1)
            }
            if (_.uvs3AttrDesc && _.uvs3AttrDesc.count > 0) {
                var et = new Float32Array(e,_.uvs3AttrDesc.offset,_.uvs3AttrDesc.count);
                i.setVerticesData(VertexBuffer.UV3Kind, et, !1)
            }
            if (_.uvs4AttrDesc && _.uvs4AttrDesc.count > 0) {
                var tt = new Float32Array(e,_.uvs4AttrDesc.offset,_.uvs4AttrDesc.count);
                i.setVerticesData(VertexBuffer.UV4Kind, tt, !1)
            }
            if (_.uvs5AttrDesc && _.uvs5AttrDesc.count > 0) {
                var rt = new Float32Array(e,_.uvs5AttrDesc.offset,_.uvs5AttrDesc.count);
                i.setVerticesData(VertexBuffer.UV5Kind, rt, !1)
            }
            if (_.uvs6AttrDesc && _.uvs6AttrDesc.count > 0) {
                var it = new Float32Array(e,_.uvs6AttrDesc.offset,_.uvs6AttrDesc.count);
                i.setVerticesData(VertexBuffer.UV6Kind, it, !1)
            }
            if (_.colorsAttrDesc && _.colorsAttrDesc.count > 0) {
                var nt = new Float32Array(e,_.colorsAttrDesc.offset,_.colorsAttrDesc.count);
                i.setVerticesData(VertexBuffer.ColorKind, nt, !1, _.colorsAttrDesc.stride)
            }
            if (_.matricesIndicesAttrDesc && _.matricesIndicesAttrDesc.count > 0) {
                for (var ot = new Int32Array(e,_.matricesIndicesAttrDesc.offset,_.matricesIndicesAttrDesc.count), at = [], st = 0; st < ot.length; st++) {
                    var ut = ot[st];
                    at.push(ut & 255),
                    at.push((ut & 65280) >> 8),
                    at.push((ut & 16711680) >> 16),
                    at.push(ut >> 24 & 255)
                }
                i.setVerticesData(VertexBuffer.MatricesIndicesKind, at, !1)
            }
            if (_.matricesIndicesExtraAttrDesc && _.matricesIndicesExtraAttrDesc.count > 0) {
                for (var ot = new Int32Array(e,_.matricesIndicesExtraAttrDesc.offset,_.matricesIndicesExtraAttrDesc.count), at = [], st = 0; st < ot.length; st++) {
                    var ut = ot[st];
                    at.push(ut & 255),
                    at.push((ut & 65280) >> 8),
                    at.push((ut & 16711680) >> 16),
                    at.push(ut >> 24 & 255)
                }
                i.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, at, !1)
            }
            if (_.matricesWeightsAttrDesc && _.matricesWeightsAttrDesc.count > 0) {
                var ct = new Float32Array(e,_.matricesWeightsAttrDesc.offset,_.matricesWeightsAttrDesc.count);
                i.setVerticesData(VertexBuffer.MatricesWeightsKind, ct, !1)
            }
            if (_.indicesAttrDesc && _.indicesAttrDesc.count > 0) {
                var lt = new Int32Array(e,_.indicesAttrDesc.offset,_.indicesAttrDesc.count);
                i.setIndices(lt, null)
            }
            if (_.subMeshesAttrDesc && _.subMeshesAttrDesc.count > 0) {
                var ft = new Int32Array(e,_.subMeshesAttrDesc.offset,_.subMeshesAttrDesc.count * 5);
                i.subMeshes = [];
                for (var st = 0; st < _.subMeshesAttrDesc.count; st++) {
                    var ht = ft[st * 5 + 0]
                      , pt = ft[st * 5 + 1]
                      , dt = ft[st * 5 + 2]
                      , _t = ft[st * 5 + 3]
                      , mt = ft[st * 5 + 4];
                    SubMesh.AddToMesh(ht, pt, dt, _t, mt, i)
                }
            }
        } else if (e.positions && e.normals && e.indices) {
            if (i.setVerticesData(VertexBuffer.PositionKind, e.positions, e.positions._updatable),
            i.setVerticesData(VertexBuffer.NormalKind, e.normals, e.normals._updatable),
            e.tangents && i.setVerticesData(VertexBuffer.TangentKind, e.tangents, e.tangents._updatable),
            e.uvs && i.setVerticesData(VertexBuffer.UVKind, e.uvs, e.uvs._updatable),
            e.uvs2 && i.setVerticesData(VertexBuffer.UV2Kind, e.uvs2, e.uvs2._updatable),
            e.uvs3 && i.setVerticesData(VertexBuffer.UV3Kind, e.uvs3, e.uvs3._updatable),
            e.uvs4 && i.setVerticesData(VertexBuffer.UV4Kind, e.uvs4, e.uvs4._updatable),
            e.uvs5 && i.setVerticesData(VertexBuffer.UV5Kind, e.uvs5, e.uvs5._updatable),
            e.uvs6 && i.setVerticesData(VertexBuffer.UV6Kind, e.uvs6, e.uvs6._updatable),
            e.colors && i.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(e.colors, e.positions.length / 3), e.colors._updatable),
            e.matricesIndices)
                if (e.matricesIndices._isExpanded)
                    delete e.matricesIndices._isExpanded,
                    i.setVerticesData(VertexBuffer.MatricesIndicesKind, e.matricesIndices, e.matricesIndices._updatable);
                else {
                    for (var at = [], st = 0; st < e.matricesIndices.length; st++) {
                        var vt = e.matricesIndices[st];
                        at.push(vt & 255),
                        at.push((vt & 65280) >> 8),
                        at.push((vt & 16711680) >> 16),
                        at.push(vt >> 24 & 255)
                    }
                    i.setVerticesData(VertexBuffer.MatricesIndicesKind, at, e.matricesIndices._updatable)
                }
            if (e.matricesIndicesExtra)
                if (e.matricesIndicesExtra._isExpanded)
                    delete e.matricesIndices._isExpanded,
                    i.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, e.matricesIndicesExtra, e.matricesIndicesExtra._updatable);
                else {
                    for (var at = [], st = 0; st < e.matricesIndicesExtra.length; st++) {
                        var vt = e.matricesIndicesExtra[st];
                        at.push(vt & 255),
                        at.push((vt & 65280) >> 8),
                        at.push((vt & 16711680) >> 16),
                        at.push(vt >> 24 & 255)
                    }
                    i.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, at, e.matricesIndicesExtra._updatable)
                }
            e.matricesWeights && (a._CleanMatricesWeights(e, i),
            i.setVerticesData(VertexBuffer.MatricesWeightsKind, e.matricesWeights, e.matricesWeights._updatable)),
            e.matricesWeightsExtra && i.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, e.matricesWeightsExtra, e.matricesWeights._updatable),
            i.setIndices(e.indices, null)
        }
        if (e.subMeshes) {
            i.subMeshes = [];
            for (var yt = 0; yt < e.subMeshes.length; yt++) {
                var Et = e.subMeshes[yt];
                SubMesh.AddToMesh(Et.materialIndex, Et.verticesStart, Et.verticesCount, Et.indexStart, Et.indexCount, i)
            }
        }
        i._shouldGenerateFlatShading && (i.convertToFlatShadedMesh(),
        i._shouldGenerateFlatShading = !1),
        i.computeWorldMatrix(!0),
        o.onMeshImportedObservable.notifyObservers(i)
    }
    ,
    a._CleanMatricesWeights = function(e, i) {
        var o = .001;
        if (!!SceneLoaderFlags.CleanBoneMatrixWeights) {
            var s = 0;
            if (e.skeletonId > -1) {
                var c = i.getScene().getLastSkeletonById(e.skeletonId);
                if (!c)
                    return;
                s = c.bones.length
            } else
                return;
            for (var d = i.getVerticesData(VertexBuffer.MatricesIndicesKind), _ = i.getVerticesData(VertexBuffer.MatricesIndicesExtraKind), b = e.matricesWeights, k = e.matricesWeightsExtra, j = e.numBoneInfluencer, $ = b.length, _e = 0; _e < $; _e += 4) {
                for (var et = 0, tt = -1, rt = 0; rt < 4; rt++) {
                    var it = b[_e + rt];
                    et += it,
                    it < o && tt < 0 && (tt = rt)
                }
                if (k)
                    for (var rt = 0; rt < 4; rt++) {
                        var it = k[_e + rt];
                        et += it,
                        it < o && tt < 0 && (tt = rt + 4)
                    }
                if ((tt < 0 || tt > j - 1) && (tt = j - 1),
                et > o) {
                    for (var nt = 1 / et, rt = 0; rt < 4; rt++)
                        b[_e + rt] *= nt;
                    if (k)
                        for (var rt = 0; rt < 4; rt++)
                            k[_e + rt] *= nt
                } else
                    tt >= 4 ? (k[_e + tt - 4] = 1 - et,
                    _[_e + tt - 4] = s) : (b[_e + tt] = 1 - et,
                    d[_e + tt] = s)
            }
            i.setVerticesData(VertexBuffer.MatricesIndicesKind, d),
            e.matricesWeightsExtra && i.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, _)
        }
    }
    ,
    a.Parse = function(e, i, o) {
        var s = new a(e.id,i,void 0,e.updatable);
        return s._loadedUniqueId = e.uniqueId,
        Tags && Tags.AddTagsTo(s, e.tags),
        e.delayLoadingFile ? (s.delayLoadState = 4,
        s.delayLoadingFile = o + e.delayLoadingFile,
        s._boundingInfo = new BoundingInfo(Vector3.FromArray(e.boundingBoxMinimum),Vector3.FromArray(e.boundingBoxMaximum)),
        s._delayInfo = [],
        e.hasUVs && s._delayInfo.push(VertexBuffer.UVKind),
        e.hasUVs2 && s._delayInfo.push(VertexBuffer.UV2Kind),
        e.hasUVs3 && s._delayInfo.push(VertexBuffer.UV3Kind),
        e.hasUVs4 && s._delayInfo.push(VertexBuffer.UV4Kind),
        e.hasUVs5 && s._delayInfo.push(VertexBuffer.UV5Kind),
        e.hasUVs6 && s._delayInfo.push(VertexBuffer.UV6Kind),
        e.hasColors && s._delayInfo.push(VertexBuffer.ColorKind),
        e.hasMatricesIndices && s._delayInfo.push(VertexBuffer.MatricesIndicesKind),
        e.hasMatricesWeights && s._delayInfo.push(VertexBuffer.MatricesWeightsKind),
        s._delayLoadingFunction = VertexData.ImportVertexData) : VertexData.ImportVertexData(e, s),
        i.pushGeometry(s, !0),
        s
    }
    ,
    a
}()
  , Light = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o) || this;
        return s.diffuse = new Color3(1,1,1),
        s.specular = new Color3(1,1,1),
        s.falloffType = e.FALLOFF_DEFAULT,
        s.intensity = 1,
        s._range = Number.MAX_VALUE,
        s._inverseSquaredRange = 0,
        s._photometricScale = 1,
        s._intensityMode = e.INTENSITYMODE_AUTOMATIC,
        s._radius = 1e-5,
        s.renderPriority = 0,
        s._shadowEnabled = !0,
        s._excludeWithLayerMask = 0,
        s._includeOnlyWithLayerMask = 0,
        s._lightmapMode = 0,
        s._excludedMeshesIds = new Array,
        s._includedOnlyMeshesIds = new Array,
        s._isLight = !0,
        s.getScene().addLight(s),
        s._uniformBuffer = new UniformBuffer(s.getScene().getEngine(),void 0,void 0,i),
        s._buildUniformLayout(),
        s.includedOnlyMeshes = new Array,
        s.excludedMeshes = new Array,
        s._resyncMeshes(),
        s
    }
    return Object.defineProperty(e.prototype, "range", {
        get: function() {
            return this._range
        },
        set: function(i) {
            this._range = i,
            this._inverseSquaredRange = 1 / (this.range * this.range)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "intensityMode", {
        get: function() {
            return this._intensityMode
        },
        set: function(i) {
            this._intensityMode = i,
            this._computePhotometricScale()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "radius", {
        get: function() {
            return this._radius
        },
        set: function(i) {
            this._radius = i,
            this._computePhotometricScale()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowEnabled", {
        get: function() {
            return this._shadowEnabled
        },
        set: function(i) {
            this._shadowEnabled !== i && (this._shadowEnabled = i,
            this._markMeshesAsLightDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "includedOnlyMeshes", {
        get: function() {
            return this._includedOnlyMeshes
        },
        set: function(i) {
            this._includedOnlyMeshes = i,
            this._hookArrayForIncludedOnly(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "excludedMeshes", {
        get: function() {
            return this._excludedMeshes
        },
        set: function(i) {
            this._excludedMeshes = i,
            this._hookArrayForExcluded(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "excludeWithLayerMask", {
        get: function() {
            return this._excludeWithLayerMask
        },
        set: function(i) {
            this._excludeWithLayerMask = i,
            this._resyncMeshes()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "includeOnlyWithLayerMask", {
        get: function() {
            return this._includeOnlyWithLayerMask
        },
        set: function(i) {
            this._includeOnlyWithLayerMask = i,
            this._resyncMeshes()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lightmapMode", {
        get: function() {
            return this._lightmapMode
        },
        set: function(i) {
            this._lightmapMode !== i && (this._lightmapMode = i,
            this._markMeshesAsLightDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.transferTexturesToEffect = function(i, o) {
        return this
    }
    ,
    e.prototype._bindLight = function(i, o, s, c, d) {
        d === void 0 && (d = !0);
        var _ = i.toString()
          , b = !1;
        if (this._uniformBuffer.bindToEffect(s, "Light" + _),
        this._renderId !== o.getRenderId() || !this._uniformBuffer.useUbo) {
            this._renderId = o.getRenderId();
            var k = this.getScaledIntensity();
            this.transferToEffect(s, _),
            this.diffuse.scaleToRef(k, TmpColors.Color3[0]),
            this._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], this.range, _),
            c && (this.specular.scaleToRef(k, TmpColors.Color3[1]),
            this._uniformBuffer.updateColor4("vLightSpecular", TmpColors.Color3[1], this.radius, _)),
            b = !0
        }
        if (this.transferTexturesToEffect(s, _),
        o.shadowsEnabled && this.shadowEnabled && d) {
            var j = this.getShadowGenerator();
            j && (j.bindShadowLight(_, s),
            b = !0)
        }
        b ? this._uniformBuffer.update() : this._uniformBuffer.bindUniformBuffer()
    }
    ,
    e.prototype.getClassName = function() {
        return "Light"
    }
    ,
    e.prototype.toString = function(i) {
        var o = "Name: " + this.name;
        if (o += ", type: " + ["Point", "Directional", "Spot", "Hemispheric"][this.getTypeID()],
        this.animations)
            for (var s = 0; s < this.animations.length; s++)
                o += ", animation[0]: " + this.animations[s].toString(i);
        return o
    }
    ,
    e.prototype._syncParentEnabledState = function() {
        a.prototype._syncParentEnabledState.call(this),
        this.isDisposed() || this._resyncMeshes()
    }
    ,
    e.prototype.setEnabled = function(i) {
        a.prototype.setEnabled.call(this, i),
        this._resyncMeshes()
    }
    ,
    e.prototype.getShadowGenerator = function() {
        return this._shadowGenerator
    }
    ,
    e.prototype.getAbsolutePosition = function() {
        return Vector3.Zero()
    }
    ,
    e.prototype.canAffectMesh = function(i) {
        return i ? !(this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(i) === -1 || this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(i) !== -1 || this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & i.layerMask) === 0 || this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & i.layerMask) : !0
    }
    ,
    e.prototype.dispose = function(i, o) {
        if (o === void 0 && (o = !1),
        this._shadowGenerator && (this._shadowGenerator.dispose(),
        this._shadowGenerator = null),
        this.getScene().stopAnimation(this),
        this._parentContainer) {
            var s = this._parentContainer.lights.indexOf(this);
            s > -1 && this._parentContainer.lights.splice(s, 1),
            this._parentContainer = null
        }
        for (var c = 0, d = this.getScene().meshes; c < d.length; c++) {
            var _ = d[c];
            _._removeLightSource(this, !0)
        }
        this._uniformBuffer.dispose(),
        this.getScene().removeLight(this),
        a.prototype.dispose.call(this, i, o)
    }
    ,
    e.prototype.getTypeID = function() {
        return 0
    }
    ,
    e.prototype.getScaledIntensity = function() {
        return this._photometricScale * this.intensity
    }
    ,
    e.prototype.clone = function(i, o) {
        o === void 0 && (o = null);
        var s = e.GetConstructorFromName(this.getTypeID(), i, this.getScene());
        if (!s)
            return null;
        var c = SerializationHelper.Clone(s, this);
        return i && (c.name = i),
        o && (c.parent = o),
        c.setEnabled(this.isEnabled()),
        this.onClonedObservable.notifyObservers(c),
        c
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        return i.uniqueId = this.uniqueId,
        i.type = this.getTypeID(),
        this.parent && (i.parentId = this.parent.uniqueId),
        this.excludedMeshes.length > 0 && (i.excludedMeshesIds = [],
        this.excludedMeshes.forEach(function(o) {
            i.excludedMeshesIds.push(o.id)
        })),
        this.includedOnlyMeshes.length > 0 && (i.includedOnlyMeshesIds = [],
        this.includedOnlyMeshes.forEach(function(o) {
            i.includedOnlyMeshesIds.push(o.id)
        })),
        SerializationHelper.AppendSerializedAnimations(this, i),
        i.ranges = this.serializeAnimationRanges(),
        i.isEnabled = this.isEnabled(),
        i
    }
    ,
    e.GetConstructorFromName = function(i, o, s) {
        var c = Node$2.Construct("Light_Type_" + i, o, s);
        return c || null
    }
    ,
    e.Parse = function(i, o) {
        var s = e.GetConstructorFromName(i.type, i.name, o);
        if (!s)
            return null;
        var c = SerializationHelper.Parse(s, i, o);
        if (i.excludedMeshesIds && (c._excludedMeshesIds = i.excludedMeshesIds),
        i.includedOnlyMeshesIds && (c._includedOnlyMeshesIds = i.includedOnlyMeshesIds),
        i.parentId && (c._waitingParentId = i.parentId),
        i.falloffType !== void 0 && (c.falloffType = i.falloffType),
        i.lightmapMode !== void 0 && (c.lightmapMode = i.lightmapMode),
        i.animations) {
            for (var d = 0; d < i.animations.length; d++) {
                var _ = i.animations[d]
                  , b = GetClass("BABYLON.Animation");
                b && c.animations.push(b.Parse(_))
            }
            Node$2.ParseAnimationRanges(c, i, o)
        }
        return i.autoAnimate && o.beginAnimation(c, i.autoAnimateFrom, i.autoAnimateTo, i.autoAnimateLoop, i.autoAnimateSpeed || 1),
        i.isEnabled !== void 0 && c.setEnabled(i.isEnabled),
        c
    }
    ,
    e.prototype._hookArrayForExcluded = function(i) {
        var o = this
          , s = i.push;
        i.push = function() {
            for (var k = [], j = 0; j < arguments.length; j++)
                k[j] = arguments[j];
            for (var $ = s.apply(i, k), _e = 0, et = k; _e < et.length; _e++) {
                var tt = et[_e];
                tt._resyncLightSource(o)
            }
            return $
        }
        ;
        var c = i.splice;
        i.splice = function(k, j) {
            for (var $ = c.apply(i, [k, j]), _e = 0, et = $; _e < et.length; _e++) {
                var tt = et[_e];
                tt._resyncLightSource(o)
            }
            return $
        }
        ;
        for (var d = 0, _ = i; d < _.length; d++) {
            var b = _[d];
            b._resyncLightSource(this)
        }
    }
    ,
    e.prototype._hookArrayForIncludedOnly = function(i) {
        var o = this
          , s = i.push;
        i.push = function() {
            for (var d = [], _ = 0; _ < arguments.length; _++)
                d[_] = arguments[_];
            var b = s.apply(i, d);
            return o._resyncMeshes(),
            b
        }
        ;
        var c = i.splice;
        i.splice = function(d, _) {
            var b = c.apply(i, [d, _]);
            return o._resyncMeshes(),
            b
        }
        ,
        this._resyncMeshes()
    }
    ,
    e.prototype._resyncMeshes = function() {
        for (var i = 0, o = this.getScene().meshes; i < o.length; i++) {
            var s = o[i];
            s._resyncLightSource(this)
        }
    }
    ,
    e.prototype._markMeshesAsLightDirty = function() {
        for (var i = 0, o = this.getScene().meshes; i < o.length; i++) {
            var s = o[i];
            s.lightSources.indexOf(this) !== -1 && s._markSubMeshesAsLightDirty()
        }
    }
    ,
    e.prototype._computePhotometricScale = function() {
        this._photometricScale = this._getPhotometricScale(),
        this.getScene().resetCachedMaterial()
    }
    ,
    e.prototype._getPhotometricScale = function() {
        var i = 0
          , o = this.getTypeID()
          , s = this.intensityMode;
        switch (s === e.INTENSITYMODE_AUTOMATIC && (o === e.LIGHTTYPEID_DIRECTIONALLIGHT ? s = e.INTENSITYMODE_ILLUMINANCE : s = e.INTENSITYMODE_LUMINOUSINTENSITY),
        o) {
        case e.LIGHTTYPEID_POINTLIGHT:
        case e.LIGHTTYPEID_SPOTLIGHT:
            switch (s) {
            case e.INTENSITYMODE_LUMINOUSPOWER:
                i = 1 / (4 * Math.PI);
                break;
            case e.INTENSITYMODE_LUMINOUSINTENSITY:
                i = 1;
                break;
            case e.INTENSITYMODE_LUMINANCE:
                i = this.radius * this.radius;
                break
            }
            break;
        case e.LIGHTTYPEID_DIRECTIONALLIGHT:
            switch (s) {
            case e.INTENSITYMODE_ILLUMINANCE:
                i = 1;
                break;
            case e.INTENSITYMODE_LUMINANCE:
                var c = this.radius;
                c = Math.max(c, .001);
                var d = 2 * Math.PI * (1 - Math.cos(c));
                i = d;
                break
            }
            break;
        case e.LIGHTTYPEID_HEMISPHERICLIGHT:
            i = 1;
            break
        }
        return i
    }
    ,
    e.prototype._reorderLightsInScene = function() {
        var i = this.getScene();
        this._renderPriority != 0 && (i.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 a() {}
    return a.BindClipPlane = function(e, i) {
        if (i.clipPlane) {
            var o = i.clipPlane;
            e.setFloat4("vClipPlane", o.normal.x, o.normal.y, o.normal.z, o.d)
        }
        if (i.clipPlane2) {
            var o = i.clipPlane2;
            e.setFloat4("vClipPlane2", o.normal.x, o.normal.y, o.normal.z, o.d)
        }
        if (i.clipPlane3) {
            var o = i.clipPlane3;
            e.setFloat4("vClipPlane3", o.normal.x, o.normal.y, o.normal.z, o.d)
        }
        if (i.clipPlane4) {
            var o = i.clipPlane4;
            e.setFloat4("vClipPlane4", o.normal.x, o.normal.y, o.normal.z, o.d)
        }
        if (i.clipPlane5) {
            var o = i.clipPlane5;
            e.setFloat4("vClipPlane5", o.normal.x, o.normal.y, o.normal.z, o.d)
        }
        if (i.clipPlane6) {
            var o = i.clipPlane6;
            e.setFloat4("vClipPlane6", o.normal.x, o.normal.y, o.normal.z, o.d)
        }
    }
    ,
    a
}()
  , MaterialHelper = function() {
    function a() {}
    return a.BindSceneUniformBuffer = function(e, i) {
        i.bindToEffect(e, "Scene")
    }
    ,
    a.PrepareDefinesForMergedUV = function(e, i, o) {
        i._needUVs = !0,
        i[o] = !0,
        e.getTextureMatrix().isIdentityAs3x2() ? (i[o + "DIRECTUV"] = e.coordinatesIndex + 1,
        i["MAINUV" + (e.coordinatesIndex + 1)] = !0) : i[o + "DIRECTUV"] = 0
    }
    ,
    a.BindTextureMatrix = function(e, i, o) {
        var s = e.getTextureMatrix();
        i.updateMatrix(o + "Matrix", s)
    }
    ,
    a.GetFogState = function(e, i) {
        return i.fogEnabled && e.applyFog && i.fogMode !== Scene.FOGMODE_NONE
    }
    ,
    a.PrepareDefinesForMisc = function(e, i, o, s, c, d, _) {
        _._areMiscDirty && (_.LOGARITHMICDEPTH = o,
        _.POINTSIZE = s,
        _.FOG = c && this.GetFogState(e, i),
        _.NONUNIFORMSCALING = e.nonUniformScaling,
        _.ALPHATEST = d)
    }
    ,
    a.PrepareDefinesForFrameBoundValues = function(e, i, o, s, c, d) {
        c === void 0 && (c = null),
        d === void 0 && (d = !1);
        var _ = !1
          , b = !1
          , k = !1
          , j = !1
          , $ = !1
          , _e = !1
          , et = !1;
        b = c == null ? e.clipPlane !== void 0 && e.clipPlane !== null : c,
        k = c == null ? e.clipPlane2 !== void 0 && e.clipPlane2 !== null : c,
        j = c == null ? e.clipPlane3 !== void 0 && e.clipPlane3 !== null : c,
        $ = c == null ? e.clipPlane4 !== void 0 && e.clipPlane4 !== null : c,
        _e = c == null ? e.clipPlane5 !== void 0 && e.clipPlane5 !== null : c,
        et = c == null ? e.clipPlane6 !== void 0 && e.clipPlane6 !== null : c,
        o.CLIPPLANE !== b && (o.CLIPPLANE = b,
        _ = !0),
        o.CLIPPLANE2 !== k && (o.CLIPPLANE2 = k,
        _ = !0),
        o.CLIPPLANE3 !== j && (o.CLIPPLANE3 = j,
        _ = !0),
        o.CLIPPLANE4 !== $ && (o.CLIPPLANE4 = $,
        _ = !0),
        o.CLIPPLANE5 !== _e && (o.CLIPPLANE5 = _e,
        _ = !0),
        o.CLIPPLANE6 !== et && (o.CLIPPLANE6 = et,
        _ = !0),
        o.DEPTHPREPASS !== !i.getColorWrite() && (o.DEPTHPREPASS = !o.DEPTHPREPASS,
        _ = !0),
        o.INSTANCES !== s && (o.INSTANCES = s,
        _ = !0),
        o.THIN_INSTANCES !== d && (o.THIN_INSTANCES = d,
        _ = !0),
        _ && o.markAsUnprocessed()
    }
    ,
    a.PrepareDefinesForBones = function(e, i) {
        if (e.useBones && e.computeBonesUsingShaders && e.skeleton) {
            i.NUM_BONE_INFLUENCERS = e.numBoneInfluencers;
            var o = i.BONETEXTURE !== void 0;
            if (e.skeleton.isUsingTextureForMatrices && o)
                i.BONETEXTURE = !0;
            else {
                i.BonesPerMesh = e.skeleton.bones.length + 1,
                i.BONETEXTURE = o ? !1 : void 0;
                var s = e.getScene().prePassRenderer;
                if (s && s.enabled) {
                    var c = s.excludedSkinnedMesh.indexOf(e) === -1;
                    i.BONES_VELOCITY_ENABLED = c
                }
            }
        } else
            i.NUM_BONE_INFLUENCERS = 0,
            i.BonesPerMesh = 0
    }
    ,
    a.PrepareDefinesForMorphTargets = function(e, i) {
        var o = e.morphTargetManager;
        o ? (i.MORPHTARGETS_UV = o.supportsUVs && i.UV1,
        i.MORPHTARGETS_TANGENT = o.supportsTangents && i.TANGENT,
        i.MORPHTARGETS_NORMAL = o.supportsNormals && i.NORMAL,
        i.MORPHTARGETS = o.numInfluencers > 0,
        i.NUM_MORPH_INFLUENCERS = o.numInfluencers,
        i.MORPHTARGETS_TEXTURE = o.isUsingTextureForTargets) : (i.MORPHTARGETS_UV = !1,
        i.MORPHTARGETS_TANGENT = !1,
        i.MORPHTARGETS_NORMAL = !1,
        i.MORPHTARGETS = !1,
        i.NUM_MORPH_INFLUENCERS = 0)
    }
    ,
    a.PrepareDefinesForBakedVertexAnimation = function(e, i) {
        var o = e.bakedVertexAnimationManager;
        i.BAKED_VERTEX_ANIMATION_TEXTURE = !!(o && o.isEnabled)
    }
    ,
    a.PrepareDefinesForAttributes = function(e, i, o, s, c, d, _) {
        if (c === void 0 && (c = !1),
        d === void 0 && (d = !0),
        _ === void 0 && (_ = !0),
        !i._areAttributesDirty && i._needNormals === i._normals && i._needUVs === i._uvs)
            return !1;
        i._normals = i._needNormals,
        i._uvs = i._needUVs,
        i.NORMAL = i._needNormals && e.isVerticesDataPresent(VertexBuffer.NormalKind),
        i._needNormals && e.isVerticesDataPresent(VertexBuffer.TangentKind) && (i.TANGENT = !0);
        for (var b = 1; b <= 6; ++b)
            i["UV" + b] = i._needUVs ? e.isVerticesDataPresent("uv" + (b === 1 ? "" : b)) : !1;
        if (o) {
            var k = e.useVertexColors && e.isVerticesDataPresent(VertexBuffer.ColorKind);
            i.VERTEXCOLOR = k,
            i.VERTEXALPHA = e.hasVertexAlpha && k && d
        }
        return s && this.PrepareDefinesForBones(e, i),
        c && this.PrepareDefinesForMorphTargets(e, i),
        _ && this.PrepareDefinesForBakedVertexAnimation(e, i),
        !0
    }
    ,
    a.PrepareDefinesForMultiview = function(e, i) {
        if (e.activeCamera) {
            var o = i.MULTIVIEW;
            i.MULTIVIEW = e.activeCamera.outputRenderTarget !== null && e.activeCamera.outputRenderTarget.getViewCount() > 1,
            i.MULTIVIEW != o && i.markAsUnprocessed()
        }
    }
    ,
    a.PrepareDefinesForOIT = function(e, i, o) {
        var s = i.ORDER_INDEPENDENT_TRANSPARENCY
          , c = i.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;
        i.ORDER_INDEPENDENT_TRANSPARENCY = e.useOrderIndependentTransparency && o,
        i.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !e.getEngine().getCaps().textureFloatLinearFiltering,
        (s !== i.ORDER_INDEPENDENT_TRANSPARENCY || c !== i.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) && i.markAsUnprocessed()
    }
    ,
    a.PrepareDefinesForPrePass = function(e, i, o) {
        var s = i.PREPASS;
        if (!!i._arePrePassDirty) {
            var c = [{
                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 && o) {
                i.PREPASS = !0,
                i.SCENE_MRT_COUNT = e.prePassRenderer.mrtCount;
                for (var d = 0; d < c.length; d++) {
                    var _ = e.prePassRenderer.getIndex(c[d].type);
                    _ !== -1 ? (i[c[d].define] = !0,
                    i[c[d].index] = _) : i[c[d].define] = !1
                }
            } else {
                i.PREPASS = !1;
                for (var d = 0; d < c.length; d++)
                    i[c[d].define] = !1
            }
            i.PREPASS != s && (i.markAsUnprocessed(),
            i.markAsImageProcessingDirty())
        }
    }
    ,
    a.PrepareDefinesForLight = function(e, i, o, s, c, d, _) {
        switch (_.needNormals = !0,
        c["LIGHT" + s] === void 0 && (_.needRebuild = !0),
        c["LIGHT" + s] = !0,
        c["SPOTLIGHT" + s] = !1,
        c["HEMILIGHT" + s] = !1,
        c["POINTLIGHT" + s] = !1,
        c["DIRLIGHT" + s] = !1,
        o.prepareLightSpecificDefines(c, s),
        c["LIGHT_FALLOFF_PHYSICAL" + s] = !1,
        c["LIGHT_FALLOFF_GLTF" + s] = !1,
        c["LIGHT_FALLOFF_STANDARD" + s] = !1,
        o.falloffType) {
        case Light.FALLOFF_GLTF:
            c["LIGHT_FALLOFF_GLTF" + s] = !0;
            break;
        case Light.FALLOFF_PHYSICAL:
            c["LIGHT_FALLOFF_PHYSICAL" + s] = !0;
            break;
        case Light.FALLOFF_STANDARD:
            c["LIGHT_FALLOFF_STANDARD" + s] = !0;
            break
        }
        if (d && !o.specular.equalsFloats(0, 0, 0) && (_.specularEnabled = !0),
        c["SHADOW" + s] = !1,
        c["SHADOWCSM" + s] = !1,
        c["SHADOWCSMDEBUG" + s] = !1,
        c["SHADOWCSMNUM_CASCADES" + s] = !1,
        c["SHADOWCSMUSESHADOWMAXZ" + s] = !1,
        c["SHADOWCSMNOBLEND" + s] = !1,
        c["SHADOWCSM_RIGHTHANDED" + s] = !1,
        c["SHADOWPCF" + s] = !1,
        c["SHADOWPCSS" + s] = !1,
        c["SHADOWPOISSON" + s] = !1,
        c["SHADOWESM" + s] = !1,
        c["SHADOWCLOSEESM" + s] = !1,
        c["SHADOWCUBE" + s] = !1,
        c["SHADOWLOWQUALITY" + s] = !1,
        c["SHADOWMEDIUMQUALITY" + s] = !1,
        i && i.receiveShadows && e.shadowsEnabled && o.shadowEnabled) {
            var b = o.getShadowGenerator();
            if (b) {
                var k = b.getShadowMap();
                k && k.renderList && k.renderList.length > 0 && (_.shadowEnabled = !0,
                b.prepareDefines(c, s))
            }
        }
        o.lightmapMode != Light.LIGHTMAP_DEFAULT ? (_.lightmapMode = !0,
        c["LIGHTMAPEXCLUDED" + s] = !0,
        c["LIGHTMAPNOSPECULAR" + s] = o.lightmapMode == Light.LIGHTMAP_SHADOWSONLY) : (c["LIGHTMAPEXCLUDED" + s] = !1,
        c["LIGHTMAPNOSPECULAR" + s] = !1)
    }
    ,
    a.PrepareDefinesForLights = function(e, i, o, s, c, d) {
        if (c === void 0 && (c = 4),
        d === void 0 && (d = !1),
        !o._areLightsDirty)
            return o._needNormals;
        var _ = 0
          , b = {
            needNormals: !1,
            needRebuild: !1,
            lightmapMode: !1,
            shadowEnabled: !1,
            specularEnabled: !1
        };
        if (e.lightsEnabled && !d)
            for (var k = 0, j = i.lightSources; k < j.length; k++) {
                var $ = j[k];
                if (this.PrepareDefinesForLight(e, i, $, _, o, s, b),
                _++,
                _ === c)
                    break
            }
        o.SPECULARTERM = b.specularEnabled,
        o.SHADOWS = b.shadowEnabled;
        for (var _e = _; _e < c; _e++)
            o["LIGHT" + _e] !== void 0 && (o["LIGHT" + _e] = !1,
            o["HEMILIGHT" + _e] = !1,
            o["POINTLIGHT" + _e] = !1,
            o["DIRLIGHT" + _e] = !1,
            o["SPOTLIGHT" + _e] = !1,
            o["SHADOW" + _e] = !1,
            o["SHADOWCSM" + _e] = !1,
            o["SHADOWCSMDEBUG" + _e] = !1,
            o["SHADOWCSMNUM_CASCADES" + _e] = !1,
            o["SHADOWCSMUSESHADOWMAXZ" + _e] = !1,
            o["SHADOWCSMNOBLEND" + _e] = !1,
            o["SHADOWCSM_RIGHTHANDED" + _e] = !1,
            o["SHADOWPCF" + _e] = !1,
            o["SHADOWPCSS" + _e] = !1,
            o["SHADOWPOISSON" + _e] = !1,
            o["SHADOWESM" + _e] = !1,
            o["SHADOWCLOSEESM" + _e] = !1,
            o["SHADOWCUBE" + _e] = !1,
            o["SHADOWLOWQUALITY" + _e] = !1,
            o["SHADOWMEDIUMQUALITY" + _e] = !1);
        var et = e.getEngine().getCaps();
        return o.SHADOWFLOAT === void 0 && (b.needRebuild = !0),
        o.SHADOWFLOAT = b.shadowEnabled && (et.textureFloatRender && et.textureFloatLinearFiltering || et.textureHalfFloatRender && et.textureHalfFloatLinearFiltering),
        o.LIGHTMAPEXCLUDED = b.lightmapMode,
        b.needRebuild && o.rebuild(),
        b.needNormals
    }
    ,
    a.PrepareUniformsAndSamplersForLight = function(e, i, o, s, c, d) {
        c === void 0 && (c = null),
        d === void 0 && (d = !1),
        c && c.push("Light" + e),
        !d && (i.push("vLightData" + e, "vLightDiffuse" + e, "vLightSpecular" + e, "vLightDirection" + e, "vLightFalloff" + e, "vLightGround" + e, "lightMatrix" + e, "shadowsInfo" + e, "depthValues" + e),
        o.push("shadowSampler" + e),
        o.push("depthSampler" + e),
        i.push("viewFrustumZ" + e, "cascadeBlendFactor" + e, "lightSizeUVCorrection" + e, "depthCorrection" + e, "penumbraDarkness" + e, "frustumLengths" + e),
        s && (o.push("projectionLightSampler" + e),
        i.push("textureProjectionMatrix" + e)))
    }
    ,
    a.PrepareUniformsAndSamplersList = function(e, i, o, s) {
        s === void 0 && (s = 4);
        var c, d = null;
        if (e.uniformsNames) {
            var _ = e;
            c = _.uniformsNames,
            d = _.uniformBuffersNames,
            i = _.samplers,
            o = _.defines,
            s = _.maxSimultaneousLights || 0
        } else
            c = e,
            i || (i = []);
        for (var b = 0; b < s && o["LIGHT" + b]; b++)
            this.PrepareUniformsAndSamplersForLight(b, c, i, o["PROJECTEDLIGHTTEXTURE" + b], d);
        o.NUM_MORPH_INFLUENCERS && c.push("morphTargetInfluences"),
        o.BAKED_VERTEX_ANIMATION_TEXTURE && (c.push("bakedVertexAnimationSettings"),
        c.push("bakedVertexAnimationTextureSizeInverted"),
        c.push("bakedVertexAnimationTime"),
        i.push("bakedVertexAnimationTexture"))
    }
    ,
    a.HandleFallbacksForShadows = function(e, i, o, s) {
        o === void 0 && (o = 4),
        s === void 0 && (s = 0);
        for (var c = 0, d = 0; d < o && e["LIGHT" + d]; d++)
            d > 0 && (c = s + d,
            i.addFallback(c, "LIGHT" + d)),
            e.SHADOWS || (e["SHADOW" + d] && i.addFallback(s, "SHADOW" + d),
            e["SHADOWPCF" + d] && i.addFallback(s, "SHADOWPCF" + d),
            e["SHADOWPCSS" + d] && i.addFallback(s, "SHADOWPCSS" + d),
            e["SHADOWPOISSON" + d] && i.addFallback(s, "SHADOWPOISSON" + d),
            e["SHADOWESM" + d] && i.addFallback(s, "SHADOWESM" + d),
            e["SHADOWCLOSEESM" + d] && i.addFallback(s, "SHADOWCLOSEESM" + d));
        return c++
    }
    ,
    a.PrepareAttributesForMorphTargetsInfluencers = function(e, i, o) {
        this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = o,
        this.PrepareAttributesForMorphTargets(e, i, this._TmpMorphInfluencers)
    }
    ,
    a.PrepareAttributesForMorphTargets = function(e, i, o) {
        var s = o.NUM_MORPH_INFLUENCERS;
        if (s > 0 && EngineStore.LastCreatedEngine) {
            var c = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs
              , d = i.morphTargetManager;
            if (d != null && d.isUsingTextureForTargets)
                return;
            for (var _ = d && d.supportsNormals && o.NORMAL, b = d && d.supportsTangents && o.TANGENT, k = d && d.supportsUVs && o.UV1, j = 0; j < s; j++)
                e.push(VertexBuffer.PositionKind + j),
                _ && e.push(VertexBuffer.NormalKind + j),
                b && e.push(VertexBuffer.TangentKind + j),
                k && e.push(VertexBuffer.UVKind + "_" + j),
                e.length > c && Logger$2.Error("Cannot add more vertex attributes for mesh " + i.name)
        }
    }
    ,
    a.PrepareAttributesForBakedVertexAnimation = function(e, i, o) {
        var s = o.BAKED_VERTEX_ANIMATION_TEXTURE && o.INSTANCES;
        s && (e.push("bakedVertexAnimationSettingsInstanced"),
        e.push("bakedVertexAnimationTimeInstanced"))
    }
    ,
    a.PrepareAttributesForBones = function(e, i, o, s) {
        o.NUM_BONE_INFLUENCERS > 0 && (s.addCPUSkinningFallback(0, i),
        e.push(VertexBuffer.MatricesIndicesKind),
        e.push(VertexBuffer.MatricesWeightsKind),
        o.NUM_BONE_INFLUENCERS > 4 && (e.push(VertexBuffer.MatricesIndicesExtraKind),
        e.push(VertexBuffer.MatricesWeightsExtraKind)))
    }
    ,
    a.PrepareAttributesForInstances = function(e, i) {
        (i.INSTANCES || i.THIN_INSTANCES) && this.PushAttributesForInstances(e, !!i.PREPASS_VELOCITY)
    }
    ,
    a.PushAttributesForInstances = function(e, i) {
        i === void 0 && (i = !1),
        e.push("world0"),
        e.push("world1"),
        e.push("world2"),
        e.push("world3"),
        i && (e.push("previousWorld0"),
        e.push("previousWorld1"),
        e.push("previousWorld2"),
        e.push("previousWorld3"))
    }
    ,
    a.BindLightProperties = function(e, i, o) {
        e.transferToEffect(i, o + "")
    }
    ,
    a.BindLight = function(e, i, o, s, c, d) {
        d === void 0 && (d = !0),
        e._bindLight(i, o, s, c, d)
    }
    ,
    a.BindLights = function(e, i, o, s, c) {
        c === void 0 && (c = 4);
        for (var d = Math.min(i.lightSources.length, c), _ = 0; _ < d; _++) {
            var b = i.lightSources[_];
            this.BindLight(b, _, e, o, typeof s == "boolean" ? s : s.SPECULARTERM, i.receiveShadows)
        }
    }
    ,
    a.BindFogParameters = function(e, i, o, s) {
        s === void 0 && (s = !1),
        e.fogEnabled && i.applyFog && e.fogMode !== Scene.FOGMODE_NONE && (o.setFloat4("vFogInfos", e.fogMode, e.fogStart, e.fogEnd, e.fogDensity),
        s ? (e.fogColor.toLinearSpaceToRef(this._tempFogColor),
        o.setColor3("vFogColor", this._tempFogColor)) : o.setColor3("vFogColor", e.fogColor))
    }
    ,
    a.BindBonesParameters = function(e, i, o) {
        if (!(!i || !e) && (e.computeBonesUsingShaders && i._bonesComputationForcedToCPU && (e.computeBonesUsingShaders = !1),
        e.useBones && e.computeBonesUsingShaders && e.skeleton)) {
            var s = e.skeleton;
            if (s.isUsingTextureForMatrices && i.getUniformIndex("boneTextureWidth") > -1) {
                var c = s.getTransformMatrixTexture(e);
                i.setTexture("boneSampler", c),
                i.setFloat("boneTextureWidth", 4 * (s.bones.length + 1))
            } else {
                var d = s.getTransformMatrices(e);
                d && (i.setMatrices("mBones", d),
                o && e.getScene().prePassRenderer && e.getScene().prePassRenderer.getIndex(2) && (o.previousBones[e.uniqueId] || (o.previousBones[e.uniqueId] = d.slice()),
                i.setMatrices("mPreviousBones", o.previousBones[e.uniqueId]),
                a._CopyBonesTransformationMatrices(d, o.previousBones[e.uniqueId])))
            }
        }
    }
    ,
    a._CopyBonesTransformationMatrices = function(e, i) {
        return i.set(e),
        i
    }
    ,
    a.BindMorphTargetParameters = function(e, i) {
        var o = e.morphTargetManager;
        !e || !o || i.setFloatArray("morphTargetInfluences", o.influences)
    }
    ,
    a.BindLogDepth = function(e, i, o) {
        if (!e || e.LOGARITHMICDEPTH) {
            var s = o.activeCamera;
            s.mode === Camera$1.ORTHOGRAPHIC_CAMERA && Logger$2.Error("Logarithmic depth is not compatible with orthographic cameras!", 20),
            i.setFloat("logarithmicDepthConstant", 2 / (Math.log(s.maxZ + 1) / Math.LN2))
        }
    }
    ,
    a.BindClipPlane = function(e, i) {
        ThinMaterialHelper.BindClipPlane(e, i)
    }
    ,
    a._TmpMorphInfluencers = {
        NUM_MORPH_INFLUENCERS: 0
    },
    a._tempFogColor = Color3.Black(),
    a
}()
  , MaterialStencilState = function() {
    function a() {
        this.reset()
    }
    return a.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(a.prototype, "func", {
        get: function() {
            return this._func
        },
        set: function(e) {
            this._func = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "funcRef", {
        get: function() {
            return this._funcRef
        },
        set: function(e) {
            this._funcRef = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "funcMask", {
        get: function() {
            return this._funcMask
        },
        set: function(e) {
            this._funcMask = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "opStencilFail", {
        get: function() {
            return this._opStencilFail
        },
        set: function(e) {
            this._opStencilFail = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "opDepthFail", {
        get: function() {
            return this._opDepthFail
        },
        set: function(e) {
            this._opDepthFail = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "opStencilDepthPass", {
        get: function() {
            return this._opStencilDepthPass
        },
        set: function(e) {
            this._opStencilDepthPass = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "mask", {
        get: function() {
            return this._mask
        },
        set: function(e) {
            this._mask = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "enabled", {
        get: function() {
            return this._enabled
        },
        set: function(e) {
            this._enabled = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getClassName = function() {
        return "MaterialStencilState"
    }
    ,
    a.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.prototype.parse = function(e, i, o) {
        var s = this;
        SerializationHelper.Parse(function() {
            return s
        }, e, i, o)
    }
    ,
    __decorate([serialize()], a.prototype, "func", null),
    __decorate([serialize()], a.prototype, "funcRef", null),
    __decorate([serialize()], a.prototype, "funcMask", null),
    __decorate([serialize()], a.prototype, "opStencilFail", null),
    __decorate([serialize()], a.prototype, "opDepthFail", null),
    __decorate([serialize()], a.prototype, "opStencilDepthPass", null),
    __decorate([serialize()], a.prototype, "mask", null),
    __decorate([serialize()], a.prototype, "enabled", null),
    a
}()
  , Material = function() {
    function a(e, i, o) {
        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 = a.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 = i || 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 = a.ClockWiseSideOrientation : this.sideOrientation = a.CounterClockWiseSideOrientation,
        this._uniformBuffer = new UniformBuffer(this._scene.getEngine(),void 0,void 0,e),
        this._useUBO = this.getScene().getEngine().supportsUniformBuffers,
        o || this._scene.addMaterial(this),
        this._scene.useMaterialMeshMap && (this.meshMap = {})
    }
    return Object.defineProperty(a.prototype, "canRenderToMRT", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "alpha", {
        get: function() {
            return this._alpha
        },
        set: function(e) {
            this._alpha !== e && (this._alpha = e,
            this.markAsDirty(a.MiscDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "backFaceCulling", {
        get: function() {
            return this._backFaceCulling
        },
        set: function(e) {
            this._backFaceCulling !== e && (this._backFaceCulling = e,
            this.markAsDirty(a.TextureDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "cullBackFaces", {
        get: function() {
            return this._cullBackFaces
        },
        set: function(e) {
            this._cullBackFaces !== e && (this._cullBackFaces = e,
            this.markAsDirty(a.TextureDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasRenderTargetTextures", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onBindObservable", {
        get: function() {
            return this._onBindObservable || (this._onBindObservable = new Observable),
            this._onBindObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onBind", {
        set: function(e) {
            this._onBindObserver && this.onBindObservable.remove(this._onBindObserver),
            this._onBindObserver = this.onBindObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onUnBindObservable", {
        get: function() {
            return this._onUnBindObservable || (this._onUnBindObservable = new Observable),
            this._onUnBindObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onEffectCreatedObservable", {
        get: function() {
            return this._onEffectCreatedObservable || (this._onEffectCreatedObservable = new Observable),
            this._onEffectCreatedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "alphaMode", {
        get: function() {
            return this._alphaMode
        },
        set: function(e) {
            this._alphaMode !== e && (this._alphaMode = e,
            this.markAsDirty(a.TextureDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "isPrePassCapable", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "fogEnabled", {
        get: function() {
            return this._fogEnabled
        },
        set: function(e) {
            this._fogEnabled !== e && (this._fogEnabled = e,
            this.markAsDirty(a.MiscDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "wireframe", {
        get: function() {
            switch (this._fillMode) {
            case a.WireFrameFillMode:
            case a.LineListDrawMode:
            case a.LineLoopDrawMode:
            case a.LineStripDrawMode:
                return !0
            }
            return this._scene.forceWireframe
        },
        set: function(e) {
            this.fillMode = e ? a.WireFrameFillMode : a.TriangleFillMode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "pointsCloud", {
        get: function() {
            switch (this._fillMode) {
            case a.PointFillMode:
            case a.PointListDrawMode:
                return !0
            }
            return this._scene.forcePointsCloud
        },
        set: function(e) {
            this.fillMode = e ? a.PointFillMode : a.TriangleFillMode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "fillMode", {
        get: function() {
            return this._fillMode
        },
        set: function(e) {
            this._fillMode !== e && (this._fillMode = e,
            this.markAsDirty(a.MiscDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._getDrawWrapper = function() {
        return this._drawWrapper
    }
    ,
    a.prototype._setDrawWrapper = function(e) {
        this._drawWrapper = e
    }
    ,
    a.prototype.toString = function(e) {
        var i = "Name: " + this.name;
        return i
    }
    ,
    a.prototype.getClassName = function() {
        return "Material"
    }
    ,
    Object.defineProperty(a.prototype, "isFrozen", {
        get: function() {
            return this.checkReadyOnlyOnce
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.freeze = function() {
        this.markDirty(),
        this.checkReadyOnlyOnce = !0
    }
    ,
    a.prototype.unfreeze = function() {
        this.markDirty(),
        this.checkReadyOnlyOnce = !1
    }
    ,
    a.prototype.isReady = function(e, i) {
        return !0
    }
    ,
    a.prototype.isReadyForSubMesh = function(e, i, o) {
        return !1
    }
    ,
    a.prototype.getEffect = function() {
        return this._drawWrapper.effect
    }
    ,
    a.prototype.getScene = function() {
        return this._scene
    }
    ,
    Object.defineProperty(a.prototype, "transparencyMode", {
        get: function() {
            return this._transparencyMode
        },
        set: function(e) {
            this._transparencyMode !== e && (this._transparencyMode = e,
            this._forceAlphaTest = e === a.MATERIAL_ALPHATESTANDBLEND,
            this._markAllSubMeshesAsTexturesAndMiscDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "_disableAlphaBlending", {
        get: function() {
            return this._transparencyMode === a.MATERIAL_OPAQUE || this._transparencyMode === a.MATERIAL_ALPHATEST
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.needAlphaBlending = function() {
        return this._disableAlphaBlending ? !1 : this.alpha < 1
    }
    ,
    a.prototype.needAlphaBlendingForMesh = function(e) {
        return this._disableAlphaBlending && e.visibility >= 1 ? !1 : this.needAlphaBlending() || e.visibility < 1 || e.hasVertexAlpha
    }
    ,
    a.prototype.needAlphaTesting = function() {
        return !!this._forceAlphaTest
    }
    ,
    a.prototype._shouldTurnAlphaTestOn = function(e) {
        return !this.needAlphaBlendingForMesh(e) && this.needAlphaTesting()
    }
    ,
    a.prototype.getAlphaTestTexture = function() {
        return null
    }
    ,
    a.prototype.markDirty = function() {
        for (var e = this.getScene().meshes, i = 0, o = e; i < o.length; i++) {
            var s = o[i];
            if (!!s.subMeshes)
                for (var c = 0, d = s.subMeshes; c < d.length; c++) {
                    var _ = d[c];
                    _.getMaterial() === this && (!_.effect || (_.effect._wasPreviouslyReady = !1))
                }
        }
    }
    ,
    a.prototype._preBind = function(e, i) {
        i === void 0 && (i = null);
        var o = this._scene.getEngine()
          , s = i == null ? this.sideOrientation : i
          , c = s === a.ClockWiseSideOrientation;
        return o.enableEffect(e || this._getDrawWrapper()),
        o.setState(this.backFaceCulling, this.zOffset, !1, c, this.cullBackFaces, this.stencil, this.zOffsetUnits),
        c
    }
    ,
    a.prototype.bind = function(e, i) {}
    ,
    a.prototype.bindForSubMesh = function(e, i, o) {}
    ,
    a.prototype.bindOnlyWorldMatrix = function(e) {}
    ,
    a.prototype.bindView = function(e) {
        this._useUBO ? this._needToBindSceneUbo = !0 : e.setMatrix("view", this.getScene().getViewMatrix())
    }
    ,
    a.prototype.bindViewProjection = function(e) {
        this._useUBO ? this._needToBindSceneUbo = !0 : (e.setMatrix("viewProjection", this.getScene().getTransformMatrix()),
        e.setMatrix("projection", this.getScene().getProjectionMatrix()))
    }
    ,
    a.prototype.bindEyePosition = function(e, i) {
        this._useUBO ? this._needToBindSceneUbo = !0 : this._scene.bindEyePosition(e, i)
    }
    ,
    a.prototype._afterBind = function(e, i) {
        if (i === void 0 && (i = null),
        this._scene._cachedMaterial = this,
        this._needToBindSceneUbo && i && (this._needToBindSceneUbo = !1,
        MaterialHelper.BindSceneUniformBuffer(i, 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 o = this._scene.getEngine();
            this._cachedDepthWriteState = o.getDepthWrite(),
            o.setDepthWrite(!1)
        }
        if (this.disableColorWrite) {
            var o = this._scene.getEngine();
            this._cachedColorWriteState = o.getColorWrite(),
            o.setColorWrite(!1)
        }
        if (this.depthFunction !== 0) {
            var o = this._scene.getEngine();
            this._cachedDepthFunctionState = o.getDepthFunction() || 0,
            o.setDepthFunction(this.depthFunction)
        }
    }
    ,
    a.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)
        }
    }
    ,
    a.prototype.getActiveTextures = function() {
        return []
    }
    ,
    a.prototype.hasTexture = function(e) {
        return !1
    }
    ,
    a.prototype.clone = function(e) {
        return null
    }
    ,
    a.prototype.getBindedMeshes = function() {
        var e = this;
        if (this.meshMap) {
            var i = new Array;
            for (var o in this.meshMap) {
                var s = this.meshMap[o];
                s && i.push(s)
            }
            return i
        } else {
            var c = this._scene.meshes;
            return c.filter(function(d) {
                return d.material === e
            })
        }
    }
    ,
    a.prototype.forceCompilation = function(e, i, o, s) {
        var c = this
          , d = __assign({
            clipPlane: !1,
            useInstances: !1
        }, o)
          , _ = this.getScene()
          , b = this.allowShaderHotSwapping;
        this.allowShaderHotSwapping = !1;
        var k = function() {
            if (!(!c._scene || !c._scene.getEngine())) {
                var j = _.clipPlane;
                if (d.clipPlane && (_.clipPlane = new Plane(0,0,0,1)),
                c._storeEffectOnSubMeshes) {
                    var $ = !0
                      , _e = null;
                    if (e.subMeshes) {
                        var et = new SubMesh(0,0,0,0,0,e,void 0,!1,!1);
                        et.materialDefines && (et.materialDefines._renderId = -1),
                        c.isReadyForSubMesh(e, et, d.useInstances) || (et.effect && et.effect.getCompilationError() && et.effect.allFallbacksProcessed() ? _e = et.effect.getCompilationError() : ($ = !1,
                        setTimeout(k, 16)))
                    }
                    $ && (c.allowShaderHotSwapping = b,
                    _e && s && s(_e),
                    i && i(c))
                } else
                    c.isReady() ? (c.allowShaderHotSwapping = b,
                    i && i(c)) : setTimeout(k, 16);
                d.clipPlane && (_.clipPlane = j)
            }
        };
        k()
    }
    ,
    a.prototype.forceCompilationAsync = function(e, i) {
        var o = this;
        return new Promise(function(s, c) {
            o.forceCompilation(e, function() {
                s()
            }, i, function(d) {
                c(d)
            })
        }
        )
    }
    ,
    a.prototype.markAsDirty = function(e) {
        this.getScene().blockMaterialDirtyMechanism || (a._DirtyCallbackArray.length = 0,
        e & a.TextureDirtyFlag && a._DirtyCallbackArray.push(a._TextureDirtyCallBack),
        e & a.LightDirtyFlag && a._DirtyCallbackArray.push(a._LightsDirtyCallBack),
        e & a.FresnelDirtyFlag && a._DirtyCallbackArray.push(a._FresnelDirtyCallBack),
        e & a.AttributesDirtyFlag && a._DirtyCallbackArray.push(a._AttributeDirtyCallBack),
        e & a.MiscDirtyFlag && a._DirtyCallbackArray.push(a._MiscDirtyCallBack),
        e & a.PrePassDirtyFlag && a._DirtyCallbackArray.push(a._PrePassDirtyCallBack),
        a._DirtyCallbackArray.length && this._markAllSubMeshesAsDirty(a._RunDirtyCallBacks),
        this.getScene().resetCachedMaterial())
    }
    ,
    a.prototype._markAllSubMeshesAsDirty = function(e) {
        if (!this.getScene().blockMaterialDirtyMechanism)
            for (var i = this.getScene().meshes, o = 0, s = i; o < s.length; o++) {
                var c = s[o];
                if (!!c.subMeshes)
                    for (var d = 0, _ = c.subMeshes; d < _.length; d++) {
                        var b = _[d];
                        if (b.getMaterial() === this)
                            for (var k = 0, j = b._drawWrappers; k < j.length; k++) {
                                var $ = j[k];
                                !$ || !$.defines || !$.defines.markAllAsDirty || this._materialContext === $.materialContext && e($.defines)
                            }
                    }
            }
    }
    ,
    a.prototype._markScenePrePassDirty = function() {
        if (!this.getScene().blockMaterialDirtyMechanism) {
            var e = this.getScene().enablePrePassRenderer();
            e && e.markAsDirty()
        }
    }
    ,
    a.prototype._markAllSubMeshesAsAllDirty = function() {
        this._markAllSubMeshesAsDirty(a._AllDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsImageProcessingDirty = function() {
        this._markAllSubMeshesAsDirty(a._ImageProcessingDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._markAllSubMeshesAsDirty(a._TextureDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsFresnelDirty = function() {
        this._markAllSubMeshesAsDirty(a._FresnelDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function() {
        this._markAllSubMeshesAsDirty(a._FresnelAndMiscDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsLightsDirty = function() {
        this._markAllSubMeshesAsDirty(a._LightsDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsAttributesDirty = function() {
        this._markAllSubMeshesAsDirty(a._AttributeDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsMiscDirty = function() {
        this._markAllSubMeshesAsDirty(a._MiscDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsPrePassDirty = function() {
        this._markAllSubMeshesAsDirty(a._MiscDirtyCallBack)
    }
    ,
    a.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function() {
        this._markAllSubMeshesAsDirty(a._TextureAndMiscDirtyCallBack)
    }
    ,
    a.prototype.setPrePassRenderer = function(e) {
        return !1
    }
    ,
    a.prototype.dispose = function(e, i, o) {
        var s = this.getScene();
        if (s.stopAnimation(this),
        s.freeProcessedMaterials(),
        s.removeMaterial(this),
        this._parentContainer) {
            var c = this._parentContainer.materials.indexOf(this);
            c > -1 && this._parentContainer.materials.splice(c, 1),
            this._parentContainer = null
        }
        if (o !== !0)
            if (this.meshMap)
                for (var d in this.meshMap) {
                    var _ = this.meshMap[d];
                    _ && (_.material = null,
                    this.releaseVertexArrayObject(_, e))
                }
            else
                for (var b = s.meshes, k = 0, j = b; k < j.length; k++) {
                    var _ = j[k];
                    _.material === this && !_.sourceMesh && (_.material = null,
                    this.releaseVertexArrayObject(_, 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()
    }
    ,
    a.prototype.releaseVertexArrayObject = function(e, i) {
        if (e.geometry) {
            var o = e.geometry;
            if (this._storeEffectOnSubMeshes)
                for (var s = 0, c = e.subMeshes; s < c.length; s++) {
                    var d = c[s];
                    o._releaseVertexArrayObject(d.effect),
                    i && d.effect && d.effect.dispose()
                }
            else
                o._releaseVertexArrayObject(this._drawWrapper.effect)
        }
    }
    ,
    a.prototype.serialize = function() {
        var e = SerializationHelper.Serialize(this);
        return e.stencil = this.stencil.serialize(),
        e
    }
    ,
    a.Parse = function(e, i, o) {
        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 s = Tools.Instantiate(e.customType);
        return s.Parse(e, i, o)
    }
    ,
    a.TriangleFillMode = 0,
    a.WireFrameFillMode = 1,
    a.PointFillMode = 2,
    a.PointListDrawMode = 3,
    a.LineListDrawMode = 4,
    a.LineLoopDrawMode = 5,
    a.LineStripDrawMode = 6,
    a.TriangleStripDrawMode = 7,
    a.TriangleFanDrawMode = 8,
    a.ClockWiseSideOrientation = 0,
    a.CounterClockWiseSideOrientation = 1,
    a.TextureDirtyFlag = 1,
    a.LightDirtyFlag = 2,
    a.FresnelDirtyFlag = 4,
    a.AttributesDirtyFlag = 8,
    a.MiscDirtyFlag = 16,
    a.PrePassDirtyFlag = 32,
    a.AllDirtyFlag = 63,
    a.MATERIAL_OPAQUE = 0,
    a.MATERIAL_ALPHATEST = 1,
    a.MATERIAL_ALPHABLEND = 2,
    a.MATERIAL_ALPHATESTANDBLEND = 3,
    a.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0,
    a.MATERIAL_NORMALBLENDMETHOD_RNM = 1,
    a._AllDirtyCallBack = function(e) {
        return e.markAllAsDirty()
    }
    ,
    a._ImageProcessingDirtyCallBack = function(e) {
        return e.markAsImageProcessingDirty()
    }
    ,
    a._TextureDirtyCallBack = function(e) {
        return e.markAsTexturesDirty()
    }
    ,
    a._FresnelDirtyCallBack = function(e) {
        return e.markAsFresnelDirty()
    }
    ,
    a._MiscDirtyCallBack = function(e) {
        return e.markAsMiscDirty()
    }
    ,
    a._PrePassDirtyCallBack = function(e) {
        return e.markAsPrePassDirty()
    }
    ,
    a._LightsDirtyCallBack = function(e) {
        return e.markAsLightDirty()
    }
    ,
    a._AttributeDirtyCallBack = function(e) {
        return e.markAsAttributesDirty()
    }
    ,
    a._FresnelAndMiscDirtyCallBack = function(e) {
        a._FresnelDirtyCallBack(e),
        a._MiscDirtyCallBack(e)
    }
    ,
    a._TextureAndMiscDirtyCallBack = function(e) {
        a._TextureDirtyCallBack(e),
        a._MiscDirtyCallBack(e)
    }
    ,
    a._DirtyCallbackArray = [],
    a._RunDirtyCallBacks = function(e) {
        for (var i = 0, o = a._DirtyCallbackArray; i < o.length; i++) {
            var s = o[i];
            s(e)
        }
    }
    ,
    __decorate([serialize()], a.prototype, "id", void 0),
    __decorate([serialize()], a.prototype, "uniqueId", void 0),
    __decorate([serialize()], a.prototype, "name", void 0),
    __decorate([serialize()], a.prototype, "metadata", void 0),
    __decorate([serialize()], a.prototype, "checkReadyOnEveryCall", void 0),
    __decorate([serialize()], a.prototype, "checkReadyOnlyOnce", void 0),
    __decorate([serialize()], a.prototype, "state", void 0),
    __decorate([serialize("alpha")], a.prototype, "_alpha", void 0),
    __decorate([serialize("backFaceCulling")], a.prototype, "_backFaceCulling", void 0),
    __decorate([serialize("cullBackFaces")], a.prototype, "_cullBackFaces", void 0),
    __decorate([serialize()], a.prototype, "sideOrientation", void 0),
    __decorate([serialize("alphaMode")], a.prototype, "_alphaMode", void 0),
    __decorate([serialize()], a.prototype, "_needDepthPrePass", void 0),
    __decorate([serialize()], a.prototype, "disableDepthWrite", void 0),
    __decorate([serialize()], a.prototype, "disableColorWrite", void 0),
    __decorate([serialize()], a.prototype, "forceDepthWrite", void 0),
    __decorate([serialize()], a.prototype, "depthFunction", void 0),
    __decorate([serialize()], a.prototype, "separateCullingPass", void 0),
    __decorate([serialize("fogEnabled")], a.prototype, "_fogEnabled", void 0),
    __decorate([serialize()], a.prototype, "pointSize", void 0),
    __decorate([serialize()], a.prototype, "zOffset", void 0),
    __decorate([serialize()], a.prototype, "zOffsetUnits", void 0),
    __decorate([serialize()], a.prototype, "pointsCloud", null),
    __decorate([serialize()], a.prototype, "fillMode", null),
    __decorate([serialize()], a.prototype, "transparencyMode", null),
    a
}()
  , MultiMaterial = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o, !0) || this;
        return o.multiMaterials.push(s),
        s.subMaterials = new Array,
        s._storeEffectOnSubMeshes = !0,
        s
    }
    return Object.defineProperty(e.prototype, "subMaterials", {
        get: function() {
            return this._subMaterials
        },
        set: function(i) {
            this._subMaterials = i,
            this._hookArray(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getChildren = function() {
        return this.subMaterials
    }
    ,
    e.prototype._hookArray = function(i) {
        var o = this
          , s = i.push;
        i.push = function() {
            for (var d = [], _ = 0; _ < arguments.length; _++)
                d[_] = arguments[_];
            var b = s.apply(i, d);
            return o._markAllSubMeshesAsTexturesDirty(),
            b
        }
        ;
        var c = i.splice;
        i.splice = function(d, _) {
            var b = c.apply(i, [d, _]);
            return o._markAllSubMeshesAsTexturesDirty(),
            b
        }
    }
    ,
    e.prototype.getSubMaterial = function(i) {
        return i < 0 || i >= this.subMaterials.length ? this.getScene().defaultMaterial : this.subMaterials[i]
    }
    ,
    e.prototype.getActiveTextures = function() {
        var i;
        return (i = a.prototype.getActiveTextures.call(this)).concat.apply(i, this.subMaterials.map(function(o) {
            return o ? o.getActiveTextures() : []
        }))
    }
    ,
    e.prototype.hasTexture = function(i) {
        var o;
        if (a.prototype.hasTexture.call(this, i))
            return !0;
        for (var s = 0; s < this.subMaterials.length; s++)
            if (!((o = this.subMaterials[s]) === null || o === void 0) && o.hasTexture(i))
                return !0;
        return !1
    }
    ,
    e.prototype.getClassName = function() {
        return "MultiMaterial"
    }
    ,
    e.prototype.isReadyForSubMesh = function(i, o, s) {
        for (var c = 0; c < this.subMaterials.length; c++) {
            var d = this.subMaterials[c];
            if (d) {
                if (d._storeEffectOnSubMeshes) {
                    if (!d.isReadyForSubMesh(i, o, s))
                        return !1;
                    continue
                }
                if (!d.isReady(i))
                    return !1
            }
        }
        return !0
    }
    ,
    e.prototype.clone = function(i, o) {
        for (var s = new e(i,this.getScene()), c = 0; c < this.subMaterials.length; c++) {
            var d = null
              , _ = this.subMaterials[c];
            o && _ ? d = _.clone(i + "-" + _.name) : d = this.subMaterials[c],
            s.subMaterials.push(d)
        }
        return s
    }
    ,
    e.prototype.serialize = function() {
        var i = {};
        i.name = this.name,
        i.id = this.id,
        Tags && (i.tags = Tags.GetTags(this)),
        i.materials = [];
        for (var o = 0; o < this.subMaterials.length; o++) {
            var s = this.subMaterials[o];
            s ? i.materials.push(s.id) : i.materials.push(null)
        }
        return i
    }
    ,
    e.prototype.dispose = function(i, o, s) {
        var c = this.getScene();
        if (!!c) {
            if (s)
                for (var _ = 0; _ < this.subMaterials.length; _++) {
                    var d = this.subMaterials[_];
                    d && d.dispose(i, o)
                }
            var _ = c.multiMaterials.indexOf(this);
            _ >= 0 && c.multiMaterials.splice(_, 1),
            a.prototype.dispose.call(this, i, o)
        }
    }
    ,
    e.ParseMultiMaterial = function(i, o) {
        var s = new e(i.name,o);
        s.id = i.id,
        Tags && Tags.AddTagsTo(s, i.tags);
        for (var c = 0; c < i.materials.length; c++) {
            var d = i.materials[c];
            d ? s.subMaterials.push(o.getLastMaterialById(d)) : s.subMaterials.push(null)
        }
        return s
    }
    ,
    e
}(Material);
RegisterClass("BABYLON.MultiMaterial", MultiMaterial);
var MeshLODLevel = function() {
    function a(e, i) {
        this.distanceOrScreenCoverage = e,
        this.mesh = i
    }
    return a
}()
  , _injectLTSMesh = function(a) {
    a.prototype.setMaterialByID = function(e) {
        return this.setMaterialById(e)
    }
    ,
    a.CreateDisc = a.CreateDisc || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateBox = a.CreateBox || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateSphere = a.CreateSphere || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateCylinder = a.CreateCylinder || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateTorusKnot = a.CreateTorusKnot || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateTorus = a.CreateTorus || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreatePlane = a.CreatePlane || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateGround = a.CreateGround || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateTiledGround = a.CreateTiledGround || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateGroundFromHeightMap = a.CreateGroundFromHeightMap || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateTube = a.CreateTube || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreatePolyhedron = a.CreatePolyhedron || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateIcoSphere = a.CreateIcoSphere || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateDecal = a.CreateDecal || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.CreateCapsule = a.CreateCapsule || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    a.ExtendToGoldberg = a.ExtendToGoldberg || function() {
        throw _WarnImport("MeshBuilder")
    }
}
  , _CreationDataStorage = function() {
    function a() {}
    return a
}()
  , _InstanceDataStorage = function() {
    function a() {
        this.visibleInstances = {},
        this.batchCache = new _InstancesBatch,
        this.batchCacheReplacementModeInFrozenMode = new _InstancesBatch,
        this.instancesBufferSize = 32 * 16 * 4
    }
    return a
}()
  , _InstancesBatch = function() {
    function a() {
        this.mustReturn = !1,
        this.visibleInstances = new Array,
        this.renderSelf = new Array,
        this.hardwareInstancedRendering = new Array
    }
    return a
}()
  , _ThinInstanceDataStorage = function() {
    function a() {
        this.instancesCount = 0,
        this.matrixBuffer = null,
        this.previousMatrixBuffer = null,
        this.matrixBufferSize = 32 * 16,
        this.matrixData = null,
        this.boundingVectors = [],
        this.worldMatrices = null
    }
    return a
}()
  , _InternalMeshDataInfo = function() {
    function a() {
        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 a
}()
  , Mesh = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _) {
        o === void 0 && (o = null),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        _ === void 0 && (_ = !0);
        var b = a.call(this, i, o) || this;
        if (b._internalMeshDataInfo = new _InternalMeshDataInfo,
        b.delayLoadState = 0,
        b.instances = new Array,
        b._creationDataStorage = null,
        b._geometry = null,
        b._instanceDataStorage = new _InstanceDataStorage,
        b._thinInstanceDataStorage = new _ThinInstanceDataStorage,
        b._shouldGenerateFlatShading = !1,
        b._originalBuilderSideOrientation = e.DEFAULTSIDE,
        b.overrideMaterialSideOrientation = null,
        b.ignoreCameraMaxZ = !1,
        o = b.getScene(),
        c) {
            if (c._geometry && c._geometry.applyToMesh(b),
            DeepCopier.DeepCopy(c, b, ["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"]),
            b._internalMeshDataInfo._source = c,
            o.useClonedMeshMap && (c._internalMeshDataInfo.meshMap || (c._internalMeshDataInfo.meshMap = {}),
            c._internalMeshDataInfo.meshMap[b.uniqueId] = b),
            b._originalBuilderSideOrientation = c._originalBuilderSideOrientation,
            b._creationDataStorage = c._creationDataStorage,
            c._ranges) {
                var k = c._ranges;
                for (var i in k)
                    !k.hasOwnProperty(i) || !k[i] || b.createAnimationRange(i, k[i].from, k[i].to)
            }
            c.metadata && c.metadata.clone ? b.metadata = c.metadata.clone() : b.metadata = c.metadata,
            Tags && Tags.HasTags(c) && Tags.AddTagsTo(b, Tags.GetTags(c, !0)),
            b.setEnabled(c.isEnabled()),
            b.parent = c.parent,
            b.setPivotMatrix(c.getPivotMatrix()),
            b.id = i + "." + c.id,
            b.material = c.material;
            var j;
            if (!d)
                for (var $ = c.getDescendants(!0), _e = 0; _e < $.length; _e++) {
                    var et = $[_e];
                    et.clone && et.clone(i + "." + et.name, b)
                }
            if (c.morphTargetManager && (b.morphTargetManager = c.morphTargetManager),
            o.getPhysicsEngine) {
                var tt = o.getPhysicsEngine();
                if (_ && tt) {
                    var rt = tt.getImpostorForPhysicsObject(c);
                    rt && (b.physicsImpostor = rt.clone(b))
                }
            }
            for (j = 0; j < o.particleSystems.length; j++) {
                var it = o.particleSystems[j];
                it.emitter === c && it.clone(it.name, b)
            }
            b.refreshBoundingInfo(),
            b.computeWorldMatrix(!0)
        }
        return s !== null && (b.parent = s),
        b._instanceDataStorage.hardwareInstancedRendering = b.getEngine().getCaps().instancedArrays,
        b._internalMeshDataInfo._onMeshReadyObserverAdded = function(nt) {
            nt.unregisterOnNextCall = !0,
            b.isReady(!0) ? b.onMeshReadyObservable.notifyObservers(b) : b._internalMeshDataInfo._checkReadinessObserver || (b._internalMeshDataInfo._checkReadinessObserver = b._scene.onBeforeRenderObservable.add(function() {
                b.isReady(!0) && (b._scene.onBeforeRenderObservable.remove(b._internalMeshDataInfo._checkReadinessObserver),
                b._internalMeshDataInfo._checkReadinessObserver = null,
                b.onMeshReadyObservable.notifyObservers(b))
            }))
        }
        ,
        b.onMeshReadyObservable = new Observable(b._internalMeshDataInfo._onMeshReadyObserverAdded),
        c && c.onClonedObservable.notifyObservers(b),
        b
    }
    return e._GetDefaultSideOrientation = function(i) {
        return i || e.FRONTSIDE
    }
    ,
    Object.defineProperty(e.prototype, "useLODScreenCoverage", {
        get: function() {
            return this._internalMeshDataInfo._useLODScreenCoverage
        },
        set: function(i) {
            this._internalMeshDataInfo._useLODScreenCoverage = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "computeBonesUsingShaders", {
        get: function() {
            return this._internalAbstractMeshDataInfo._computeBonesUsingShaders
        },
        set: function(i) {
            this._internalAbstractMeshDataInfo._computeBonesUsingShaders !== i && (i && 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 = i,
            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(i) {
            this._onBeforeDrawObserver && this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),
            this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(i)
        },
        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 i;
            return ((i = this._thinInstanceDataStorage.instancesCount) !== null && i !== void 0 ? i : 0) > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "forcedInstanceCount", {
        get: function() {
            return this._internalMeshDataInfo._forcedInstanceCount
        },
        set: function(i) {
            this._internalMeshDataInfo._forcedInstanceCount = i
        },
        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(i) {
            this._unIndexed !== i && (this._unIndexed = i,
            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(i) {
            this._instanceDataStorage.manualUpdate = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "manualUpdateOfPreviousWorldMatrixInstancedBuffer", {
        get: function() {
            return this._instanceDataStorage.previousManualUpdate
        },
        set: function(i) {
            this._instanceDataStorage.previousManualUpdate = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.instantiateHierarchy = function(i, o, s) {
        i === void 0 && (i = null);
        var c = this.getTotalVertices() > 0 && (!o || !o.doNotInstantiate) ? this.createInstance("instance of " + (this.name || this.id)) : this.clone("Clone of " + (this.name || this.id), i || this.parent, !0);
        c && (c.parent = i || this.parent,
        c.position = this.position.clone(),
        c.scaling = this.scaling.clone(),
        this.rotationQuaternion ? c.rotationQuaternion = this.rotationQuaternion.clone() : c.rotation = this.rotation.clone(),
        s && s(this, c));
        for (var d = 0, _ = this.getChildTransformNodes(!0); d < _.length; d++) {
            var b = _[d];
            b.instantiateHierarchy(c, o, s)
        }
        return c
    }
    ,
    e.prototype.getClassName = function() {
        return "Mesh"
    }
    ,
    Object.defineProperty(e.prototype, "_isMesh", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.toString = function(i) {
        var o = a.prototype.toString.call(this, i);
        if (o += ", n vertices: " + this.getTotalVertices(),
        o += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE"),
        this.animations)
            for (var s = 0; s < this.animations.length; s++)
                o += ", animation[0]: " + this.animations[s].toString(i);
        if (i)
            if (this._geometry) {
                var c = this.getIndices()
                  , d = this.getVerticesData(VertexBuffer.PositionKind);
                d && c && (o += ", flat shading: " + (d.length / 3 === c.length ? "YES" : "NO"))
            } else
                o += ", flat shading: UNKNOWN";
        return o
    }
    ,
    e.prototype._unBindEffect = function() {
        a.prototype._unBindEffect.call(this);
        for (var i = 0, o = this.instances; i < o.length; i++) {
            var s = o[i];
            s._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 i = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1;
        this._internalMeshDataInfo._LODLevels.sort(function(o, s) {
            return o.distanceOrScreenCoverage < s.distanceOrScreenCoverage ? i : o.distanceOrScreenCoverage > s.distanceOrScreenCoverage ? -i : 0
        })
    }
    ,
    e.prototype.addLODLevel = function(i, o) {
        if (o && o._masterMesh)
            return Logger$2.Warn("You cannot use a mesh as LOD level twice"),
            this;
        var s = new MeshLODLevel(i,o);
        return this._internalMeshDataInfo._LODLevels.push(s),
        o && (o._masterMesh = this),
        this._sortLODLevels(),
        this
    }
    ,
    e.prototype.getLODLevelAtDistance = function(i) {
        for (var o = this._internalMeshDataInfo, s = 0; s < o._LODLevels.length; s++) {
            var c = o._LODLevels[s];
            if (c.distanceOrScreenCoverage === i)
                return c.mesh
        }
        return null
    }
    ,
    e.prototype.removeLODLevel = function(i) {
        for (var o = this._internalMeshDataInfo, s = 0; s < o._LODLevels.length; s++)
            o._LODLevels[s].mesh === i && (o._LODLevels.splice(s, 1),
            i && (i._masterMesh = null));
        return this._sortLODLevels(),
        this
    }
    ,
    e.prototype.getLOD = function(i, o) {
        var s = this._internalMeshDataInfo;
        if (!s._LODLevels || s._LODLevels.length === 0)
            return this;
        var c;
        if (o)
            c = o;
        else {
            var d = this.getBoundingInfo();
            c = d.boundingSphere
        }
        var _ = c.centerWorld.subtract(i.globalPosition).length()
          , b = s._useLODScreenCoverage
          , k = _
          , j = 1;
        if (b) {
            var $ = i.screenArea
              , _e = c.radiusWorld * i.minZ / _;
            _e = _e * _e * Math.PI,
            k = _e / $,
            j = -1
        }
        if (j * s._LODLevels[s._LODLevels.length - 1].distanceOrScreenCoverage > j * k)
            return this.onLODLevelSelection && this.onLODLevelSelection(k, this, this),
            this;
        for (var et = 0; et < s._LODLevels.length; et++) {
            var tt = s._LODLevels[et];
            if (j * tt.distanceOrScreenCoverage < j * k) {
                if (tt.mesh) {
                    if (tt.mesh.delayLoadState === 4)
                        return tt.mesh._checkDelayState(),
                        this;
                    if (tt.mesh.delayLoadState === 2)
                        return this;
                    tt.mesh._preActivate(),
                    tt.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)
                }
                return this.onLODLevelSelection && this.onLODLevelSelection(k, this, tt.mesh),
                tt.mesh
            }
        }
        return this.onLODLevelSelection && this.onLODLevelSelection(k, 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(i, o, s) {
        var c, d;
        if (!this._geometry)
            return null;
        var _ = (d = (c = this._userInstancedBuffersStorage) === null || c === void 0 ? void 0 : c.vertexBuffers[i]) === null || d === void 0 ? void 0 : d.getFloatData(this._geometry.getTotalVertices(), s || o && this._geometry.meshes.length !== 1);
        return _ || (_ = this._geometry.getVerticesData(i, o, s)),
        _
    }
    ,
    e.prototype.getVertexBuffer = function(i) {
        var o, s;
        return this._geometry ? (s = (o = this._userInstancedBuffersStorage) === null || o === void 0 ? void 0 : o.vertexBuffers[i]) !== null && s !== void 0 ? s : this._geometry.getVertexBuffer(i) : null
    }
    ,
    e.prototype.isVerticesDataPresent = function(i) {
        var o;
        return this._geometry ? ((o = this._userInstancedBuffersStorage) === null || o === void 0 ? void 0 : o.vertexBuffers[i]) !== void 0 || this._geometry.isVerticesDataPresent(i) : this._delayInfo ? this._delayInfo.indexOf(i) !== -1 : !1
    }
    ,
    e.prototype.isVertexBufferUpdatable = function(i) {
        var o, s;
        return this._geometry ? ((s = (o = this._userInstancedBuffersStorage) === null || o === void 0 ? void 0 : o.vertexBuffers[i]) === null || s === void 0 ? void 0 : s.isUpdatable()) || this._geometry.isVertexBufferUpdatable(i) : this._delayInfo ? this._delayInfo.indexOf(i) !== -1 : !1
    }
    ,
    e.prototype.getVerticesDataKinds = function() {
        if (!this._geometry) {
            var i = new Array;
            return this._delayInfo && this._delayInfo.forEach(function(c) {
                i.push(c)
            }),
            i
        }
        var o = this._geometry.getVerticesDataKinds();
        if (this._userInstancedBuffersStorage)
            for (var s in this._userInstancedBuffersStorage.vertexBuffers)
                o.push(s);
        return o
    }
    ,
    e.prototype.getTotalIndices = function() {
        return this._geometry ? this._geometry.getTotalIndices() : 0
    }
    ,
    e.prototype.getIndices = function(i, o) {
        return this._geometry ? this._geometry.getIndices(i, o) : []
    }
    ,
    Object.defineProperty(e.prototype, "isBlocked", {
        get: function() {
            return this._masterMesh !== null && this._masterMesh !== void 0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.isReady = function(i, o) {
        var s, c, d, _, b, k;
        if (i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        this.delayLoadState === 2 || !a.prototype.isReady.call(this, i))
            return !1;
        if (!this.subMeshes || this.subMeshes.length === 0 || !i)
            return !0;
        var j = this.getEngine()
          , $ = this.getScene()
          , _e = o || j.getCaps().instancedArrays && (this.instances.length > 0 || this.hasThinInstances);
        this.computeWorldMatrix();
        var et = this.material || $.defaultMaterial;
        if (et) {
            if (et._storeEffectOnSubMeshes)
                for (var tt = 0, rt = this.subMeshes; tt < rt.length; tt++) {
                    var it = rt[tt]
                      , nt = it.getMaterial();
                    if (nt) {
                        if (nt._storeEffectOnSubMeshes) {
                            if (!nt.isReadyForSubMesh(this, it, _e))
                                return !1
                        } else if (!nt.isReady(this, _e))
                            return !1
                    }
                }
            else if (!et.isReady(this, _e))
                return !1
        }
        for (var ot = j.currentRenderPassId, at = 0, st = this.lightSources; at < st.length; at++) {
            var ut = st[at]
              , ct = ut.getShadowGenerator();
            if (ct && (!(!((s = ct.getShadowMap()) === null || s === void 0) && s.renderList) || ((c = ct.getShadowMap()) === null || c === void 0 ? void 0 : c.renderList) && ((_ = (d = ct.getShadowMap()) === null || d === void 0 ? void 0 : d.renderList) === null || _ === void 0 ? void 0 : _.indexOf(this)) !== -1)) {
                ct.getShadowMap() && (j.currentRenderPassId = ct.getShadowMap().renderPassId);
                for (var lt = 0, ft = this.subMeshes; lt < ft.length; lt++) {
                    var it = ft[lt];
                    if (!ct.isReady(it, _e, (k = (b = it.getMaterial()) === null || b === void 0 ? void 0 : b.needAlphaBlendingForMesh(this)) !== null && k !== void 0 ? k : !1))
                        return j.currentRenderPassId = ot,
                        !1
                }
                j.currentRenderPassId = ot
            }
        }
        for (var ht = 0, pt = this._internalMeshDataInfo._LODLevels; ht < pt.length; ht++) {
            var dt = pt[ht];
            if (dt.mesh && !dt.mesh.isReady(_e))
                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(i) {
            this._instanceDataStorage.overridenInstanceCount = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._preActivate = function() {
        var i = this._internalMeshDataInfo
          , o = this.getScene().getRenderId();
        return i._preActivateId === o ? this : (i._preActivateId = o,
        this._instanceDataStorage.visibleInstances = null,
        this)
    }
    ,
    e.prototype._preActivateForIntermediateRendering = function(i) {
        return this._instanceDataStorage.visibleInstances && (this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = i),
        this
    }
    ,
    e.prototype._registerInstanceForRenderId = function(i, o) {
        return this._instanceDataStorage.visibleInstances || (this._instanceDataStorage.visibleInstances = {
            defaultRenderId: o,
            selfDefaultRenderId: this._renderId
        }),
        this._instanceDataStorage.visibleInstances[o] || (this._instanceDataStorage.previousRenderId !== void 0 && this._instanceDataStorage.isFrozen && (this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId] = null),
        this._instanceDataStorage.previousRenderId = o,
        this._instanceDataStorage.visibleInstances[o] = new Array),
        this._instanceDataStorage.visibleInstances[o].push(i),
        this
    }
    ,
    e.prototype._afterComputeWorldMatrix = function() {
        a.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(i, o) {
        if (i === void 0 && (i = !1),
        o === void 0 && (o = !0),
        this.hasBoundingInfo && this.getBoundingInfo().isLocked)
            return this;
        var s = this.geometry ? this.geometry.boundingBias : null;
        return this._refreshBoundingInfo(this._getPositionData(i, o), s),
        this
    }
    ,
    e.prototype._createGlobalSubMesh = function(i) {
        var o = this.getTotalVertices();
        if (!o || !this.getIndices())
            return null;
        if (this.subMeshes && this.subMeshes.length > 0) {
            var s = this.getIndices();
            if (!s)
                return null;
            var c = s.length
              , d = !1;
            if (i)
                d = !0;
            else
                for (var _ = 0, b = this.subMeshes; _ < b.length; _++) {
                    var k = b[_];
                    if (k.indexStart + k.indexCount > c) {
                        d = !0;
                        break
                    }
                    if (k.verticesStart + k.verticesCount > o) {
                        d = !0;
                        break
                    }
                }
            if (!d)
                return this.subMeshes[0]
        }
        return this.releaseSubMeshes(),
        new SubMesh(0,0,o,0,this.getTotalIndices(),this)
    }
    ,
    e.prototype.subdivide = function(i) {
        if (!(i < 1)) {
            for (var o = this.getTotalIndices(), s = o / i | 0, c = 0; s % 3 !== 0; )
                s++;
            this.releaseSubMeshes();
            for (var d = 0; d < i && !(c >= o); d++)
                SubMesh.CreateFromIndices(0, c, d === i - 1 ? o - c : s, this),
                c += s;
            this.synchronizeInstances()
        }
    }
    ,
    e.prototype.setVerticesData = function(i, o, s, c) {
        if (s === void 0 && (s = !1),
        this._geometry)
            this._geometry.setVerticesData(i, o, s, c);
        else {
            var d = new VertexData;
            d.set(o, i);
            var _ = this.getScene();
            new Geometry(Geometry.RandomId(),_,d,s,this)
        }
        return this
    }
    ,
    e.prototype.removeVerticesData = function(i) {
        !this._geometry || this._geometry.removeVerticesData(i)
    }
    ,
    e.prototype.markVerticesDataAsUpdatable = function(i, o) {
        o === void 0 && (o = !0);
        var s = this.getVertexBuffer(i);
        !s || s.isUpdatable() === o || this.setVerticesData(i, this.getVerticesData(i), o)
    }
    ,
    e.prototype.setVerticesBuffer = function(i, o) {
        return o === void 0 && (o = !0),
        this._geometry || (this._geometry = Geometry.CreateGeometryForMesh(this)),
        this._geometry.setVerticesBuffer(i, null, o),
        this
    }
    ,
    e.prototype.updateVerticesData = function(i, o, s, c) {
        return this._geometry ? (c ? (this.makeGeometryUnique(),
        this.updateVerticesData(i, o, s, !1)) : this._geometry.updateVerticesData(i, o, s),
        this) : this
    }
    ,
    e.prototype.updateMeshPositions = function(i, o) {
        o === void 0 && (o = !0);
        var s = this.getVerticesData(VertexBuffer.PositionKind);
        if (!s)
            return this;
        if (i(s),
        this.updateVerticesData(VertexBuffer.PositionKind, s, !1, !1),
        o) {
            var c = this.getIndices()
              , d = this.getVerticesData(VertexBuffer.NormalKind);
            if (!d)
                return this;
            VertexData.ComputeNormals(s, c, d),
            this.updateVerticesData(VertexBuffer.NormalKind, d, !1, !1)
        }
        return this
    }
    ,
    e.prototype.makeGeometryUnique = function() {
        if (!this._geometry)
            return this;
        if (this._geometry.meshes.length === 1)
            return this;
        var i = this._geometry
          , o = this._geometry.copy(Geometry.RandomId());
        return i.releaseForMesh(this, !0),
        o.applyToMesh(this),
        this
    }
    ,
    e.prototype.setIndices = function(i, o, s) {
        if (o === void 0 && (o = null),
        s === void 0 && (s = !1),
        this._geometry)
            this._geometry.setIndices(i, o, s);
        else {
            var c = new VertexData;
            c.indices = i;
            var d = this.getScene();
            new Geometry(Geometry.RandomId(),d,c,s,this)
        }
        return this
    }
    ,
    e.prototype.updateIndices = function(i, o, s) {
        return s === void 0 && (s = !1),
        this._geometry ? (this._geometry.updateIndices(i, o, s),
        this) : this
    }
    ,
    e.prototype.toLeftHanded = function() {
        return this._geometry ? (this._geometry.toLeftHanded(),
        this) : this
    }
    ,
    e.prototype._bind = function(i, o, s) {
        if (!this._geometry)
            return this;
        var c = this.getScene().getEngine();
        this.morphTargetManager && this.morphTargetManager.isUsingTextureForTargets && this.morphTargetManager._bind(o);
        var d;
        if (this._unIndexed)
            d = null;
        else
            switch (s) {
            case Material.PointFillMode:
                d = null;
                break;
            case Material.WireFrameFillMode:
                d = i._getLinesIndexBuffer(this.getIndices(), c);
                break;
            default:
            case Material.TriangleFillMode:
                d = this._geometry.getIndexBuffer();
                break
            }
        return !this._userInstancedBuffersStorage || this.hasThinInstances ? this._geometry._bind(o, d) : this._geometry._bind(o, d, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects),
        this
    }
    ,
    e.prototype._draw = function(i, o, s) {
        if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer())
            return this;
        this._internalMeshDataInfo._onBeforeDrawObservable && this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);
        var c = this.getScene()
          , d = c.getEngine();
        return this._unIndexed || o == Material.PointFillMode ? d.drawArraysType(o, i.verticesStart, i.verticesCount, this.forcedInstanceCount || s) : o == Material.WireFrameFillMode ? d.drawElementsType(o, 0, i._linesIndexCount, this.forcedInstanceCount || s) : d.drawElementsType(o, i.indexStart, i.indexCount, this.forcedInstanceCount || s),
        this
    }
    ,
    e.prototype.registerBeforeRender = function(i) {
        return this.onBeforeRenderObservable.add(i),
        this
    }
    ,
    e.prototype.unregisterBeforeRender = function(i) {
        return this.onBeforeRenderObservable.removeCallback(i),
        this
    }
    ,
    e.prototype.registerAfterRender = function(i) {
        return this.onAfterRenderObservable.add(i),
        this
    }
    ,
    e.prototype.unregisterAfterRender = function(i) {
        return this.onAfterRenderObservable.removeCallback(i),
        this
    }
    ,
    e.prototype._getInstancesRenderList = function(i, o) {
        if (o === void 0 && (o = !1),
        this._instanceDataStorage.isFrozen) {
            if (o)
                return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[i] = !1,
                this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[i] = !0,
                this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;
            if (this._instanceDataStorage.previousBatch)
                return this._instanceDataStorage.previousBatch
        }
        var s = this.getScene()
          , c = s._isInIntermediateRendering()
          , d = c ? this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate : this._internalAbstractMeshDataInfo._onlyForInstances
          , _ = this._instanceDataStorage.batchCache;
        if (_.mustReturn = !1,
        _.renderSelf[i] = o || !d && this.isEnabled() && this.isVisible,
        _.visibleInstances[i] = null,
        this._instanceDataStorage.visibleInstances && !o) {
            var b = this._instanceDataStorage.visibleInstances
              , k = s.getRenderId()
              , j = c ? b.intermediateDefaultRenderId : b.defaultRenderId;
            _.visibleInstances[i] = b[k],
            !_.visibleInstances[i] && j && (_.visibleInstances[i] = b[j])
        }
        return _.hardwareInstancedRendering[i] = !o && this._instanceDataStorage.hardwareInstancedRendering && _.visibleInstances[i] !== null && _.visibleInstances[i] !== void 0,
        this._instanceDataStorage.previousBatch = _,
        _
    }
    ,
    e.prototype._renderWithInstances = function(i, o, s, c, d) {
        var _, b = s.visibleInstances[i._id];
        if (!b)
            return this;
        for (var k = this._instanceDataStorage, j = k.instancesBufferSize, $ = k.instancesBuffer, _e = k.instancesPreviousBuffer, et = b.length + 1, tt = et * 16 * 4; k.instancesBufferSize < tt; )
            k.instancesBufferSize *= 2;
        (!k.instancesData || j != k.instancesBufferSize) && (k.instancesData = new Float32Array(k.instancesBufferSize / 4)),
        (this._scene.needsPreviousWorldMatrices && !k.instancesPreviousData || j != k.instancesBufferSize) && (k.instancesPreviousData = new Float32Array(k.instancesBufferSize / 4));
        var rt = 0
          , it = 0
          , nt = s.renderSelf[i._id]
          , ot = !$ || j !== k.instancesBufferSize || this._scene.needsPreviousWorldMatrices && !k.instancesPreviousBuffer;
        if (!this._instanceDataStorage.manualUpdate && (!k.isFrozen || ot)) {
            var at = this._effectiveMesh.getWorldMatrix();
            if (nt && (this._scene.needsPreviousWorldMatrices && (k.masterMeshPreviousWorldMatrix ? (k.masterMeshPreviousWorldMatrix.copyToArray(k.instancesPreviousData, rt),
            k.masterMeshPreviousWorldMatrix.copyFrom(at)) : (k.masterMeshPreviousWorldMatrix = at.clone(),
            k.masterMeshPreviousWorldMatrix.copyToArray(k.instancesPreviousData, rt))),
            at.copyToArray(k.instancesData, rt),
            rt += 16,
            it++),
            b) {
                if (e.INSTANCEDMESH_SORT_TRANSPARENT && this._scene.activeCamera && ((_ = i.getMaterial()) === null || _ === void 0 ? void 0 : _.needAlphaBlendingForMesh(i.getRenderingMesh()))) {
                    for (var st = this._scene.activeCamera.globalPosition, ut = 0; ut < b.length; ut++) {
                        var ct = b[ut];
                        ct._distanceToCamera = Vector3.Distance(ct.getBoundingInfo().boundingSphere.centerWorld, st)
                    }
                    b.sort(function(pt, dt) {
                        return pt._distanceToCamera > dt._distanceToCamera ? -1 : pt._distanceToCamera < dt._distanceToCamera ? 1 : 0
                    })
                }
                for (var lt = 0; lt < b.length; lt++) {
                    var ft = b[lt]
                      , ht = ft.getWorldMatrix();
                    ht.copyToArray(k.instancesData, rt),
                    this._scene.needsPreviousWorldMatrices && (ft._previousWorldMatrix ? (ft._previousWorldMatrix.copyToArray(k.instancesPreviousData, rt),
                    ft._previousWorldMatrix.copyFrom(ht)) : (ft._previousWorldMatrix = ht.clone(),
                    ft._previousWorldMatrix.copyToArray(k.instancesPreviousData, rt))),
                    rt += 16,
                    it++
                }
            }
        } else
            it = (nt ? 1 : 0) + b.length;
        return ot ? ($ && $.dispose(),
        _e && _e.dispose(),
        $ = new Buffer(d,k.instancesData,!0,16,!1,!0),
        k.instancesBuffer = $,
        this._userInstancedBuffersStorage || (this._userInstancedBuffersStorage = {
            data: {},
            vertexBuffers: {},
            strides: {},
            sizes: {},
            vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : void 0
        }),
        this._userInstancedBuffersStorage.vertexBuffers.world0 = $.createVertexBuffer("world0", 0, 4),
        this._userInstancedBuffersStorage.vertexBuffers.world1 = $.createVertexBuffer("world1", 4, 4),
        this._userInstancedBuffersStorage.vertexBuffers.world2 = $.createVertexBuffer("world2", 8, 4),
        this._userInstancedBuffersStorage.vertexBuffers.world3 = $.createVertexBuffer("world3", 12, 4),
        this._scene.needsPreviousWorldMatrices && (_e = new Buffer(d,k.instancesPreviousData,!0,16,!1,!0),
        k.instancesPreviousBuffer = _e,
        this._userInstancedBuffersStorage.vertexBuffers.previousWorld0 = _e.createVertexBuffer("previousWorld0", 0, 4),
        this._userInstancedBuffersStorage.vertexBuffers.previousWorld1 = _e.createVertexBuffer("previousWorld1", 4, 4),
        this._userInstancedBuffersStorage.vertexBuffers.previousWorld2 = _e.createVertexBuffer("previousWorld2", 8, 4),
        this._userInstancedBuffersStorage.vertexBuffers.previousWorld3 = _e.createVertexBuffer("previousWorld3", 12, 4)),
        this._invalidateInstanceVertexArrayObject()) : this._instanceDataStorage.isFrozen || ($.updateDirectly(k.instancesData, 0, it),
        this._scene.needsPreviousWorldMatrices && (!this._instanceDataStorage.manualUpdate || this._instanceDataStorage.previousManualUpdate) && _e.updateDirectly(k.instancesPreviousData, 0, it)),
        this._processInstancedBuffers(b, nt),
        this.getScene()._activeIndices.addCount(i.indexCount * it, !1),
        d._currentDrawContext && (d._currentDrawContext.useInstancing = !0),
        this._bind(i, c, o),
        this._draw(i, o, it),
        this._scene.needsPreviousWorldMatrices && !ot && this._instanceDataStorage.manualUpdate && !this._instanceDataStorage.isFrozen && !this._instanceDataStorage.previousManualUpdate && _e.updateDirectly(k.instancesData, 0, it),
        d.unbindInstanceAttributes(),
        this
    }
    ,
    e.prototype._renderWithThinInstances = function(i, o, s, c) {
        var d, _, b = (_ = (d = this._thinInstanceDataStorage) === null || d === void 0 ? void 0 : d.instancesCount) !== null && _ !== void 0 ? _ : 0;
        this.getScene()._activeIndices.addCount(i.indexCount * b, !1),
        c._currentDrawContext && (c._currentDrawContext.useInstancing = !0),
        this._bind(i, s, o),
        this._draw(i, o, b),
        this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData && this._thinInstanceDataStorage.matrixData && (this._thinInstanceDataStorage.previousMatrixBuffer ? this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, b) : this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.matrixData, !1)),
        c.unbindInstanceAttributes()
    }
    ,
    e.prototype._processInstancedBuffers = function(i, o) {}
    ,
    e.prototype._processRendering = function(i, o, s, c, d, _, b, k) {
        var j = this.getScene()
          , $ = j.getEngine();
        if (_ && o.getRenderingMesh().hasThinInstances)
            return this._renderWithThinInstances(o, c, s, $),
            this;
        if (_)
            this._renderWithInstances(o, c, d, s, $);
        else {
            $._currentDrawContext && ($._currentDrawContext.useInstancing = !1);
            var _e = 0;
            d.renderSelf[o._id] && (b && b(!1, i._effectiveMesh.getWorldMatrix(), k, i._effectiveMesh),
            _e++,
            this._draw(o, c, this._instanceDataStorage.overridenInstanceCount));
            var et = d.visibleInstances[o._id];
            if (et) {
                var tt = et.length;
                _e += tt;
                for (var rt = 0; rt < tt; rt++) {
                    var it = et[rt]
                      , nt = it.getWorldMatrix();
                    b && b(!0, nt, k),
                    this._draw(o, c)
                }
            }
            j._activeIndices.addCount(o.indexCount * _e, !1)
        }
        return this
    }
    ,
    e.prototype._rebuild = function(i) {
        if (i === void 0 && (i = !1),
        this._instanceDataStorage.instancesBuffer && (i && this._instanceDataStorage.instancesBuffer.dispose(),
        this._instanceDataStorage.instancesBuffer = null),
        this._userInstancedBuffersStorage) {
            for (var o in this._userInstancedBuffersStorage.vertexBuffers) {
                var s = this._userInstancedBuffersStorage.vertexBuffers[o];
                s && (i && s.dispose(),
                this._userInstancedBuffersStorage.vertexBuffers[o] = null)
            }
            this._userInstancedBuffersStorage.vertexArrayObjects && (this._userInstancedBuffersStorage.vertexArrayObjects = {})
        }
        this._internalMeshDataInfo._effectiveMaterial = null,
        a.prototype._rebuild.call(this, i)
    }
    ,
    e.prototype._freeze = function() {
        if (!!this.subMeshes) {
            for (var i = 0; i < this.subMeshes.length; i++)
                this._getInstancesRenderList(i);
            this._internalMeshDataInfo._effectiveMaterial = null,
            this._instanceDataStorage.isFrozen = !0
        }
    }
    ,
    e.prototype._unFreeze = function() {
        this._instanceDataStorage.isFrozen = !1,
        this._instanceDataStorage.previousBatch = null
    }
    ,
    e.prototype.render = function(i, o, s) {
        var c, d, _, b = this.getScene();
        if (this._internalAbstractMeshDataInfo._isActiveIntermediate ? this._internalAbstractMeshDataInfo._isActiveIntermediate = !1 : this._internalAbstractMeshDataInfo._isActive = !1,
        this._checkOcclusionQuery())
            return this;
        var k = this._getInstancesRenderList(i._id, !!s);
        if (k.mustReturn)
            return this;
        if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer())
            return this;
        var j = b.getEngine()
          , $ = 0
          , _e = null;
        this.ignoreCameraMaxZ && b.activeCamera && !b._isInIntermediateRendering() && ($ = b.activeCamera.maxZ,
        _e = b.activeCamera,
        b.activeCamera.maxZ = 0,
        b.updateTransformMatrix(!0)),
        this._internalMeshDataInfo._onBeforeRenderObservable && this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);
        var et = k.hardwareInstancedRendering[i._id] || i.getRenderingMesh().hasThinInstances
          , tt = this._instanceDataStorage
          , rt = i.getMaterial();
        if (!rt)
            return _e && (_e.maxZ = $,
            b.updateTransformMatrix(!0)),
            this;
        if (!tt.isFrozen || !this._internalMeshDataInfo._effectiveMaterial || this._internalMeshDataInfo._effectiveMaterial !== rt) {
            if (rt._storeEffectOnSubMeshes) {
                if (!rt.isReadyForSubMesh(this, i, et))
                    return _e && (_e.maxZ = $,
                    b.updateTransformMatrix(!0)),
                    this
            } else if (!rt.isReady(this, et))
                return _e && (_e.maxZ = $,
                b.updateTransformMatrix(!0)),
                this;
            this._internalMeshDataInfo._effectiveMaterial = rt
        } else if (rt._storeEffectOnSubMeshes && !(!((c = i.effect) === null || c === void 0) && c._wasPreviouslyReady) || !rt._storeEffectOnSubMeshes && !(!((d = rt.getEffect()) === null || d === void 0) && d._wasPreviouslyReady))
            return _e && (_e.maxZ = $,
            b.updateTransformMatrix(!0)),
            this;
        o && j.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);
        var it;
        this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes ? it = i._drawWrapper : it = this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();
        for (var nt = (_ = it == null ? void 0 : it.effect) !== null && _ !== void 0 ? _ : null, ot = 0, at = b._beforeRenderingMeshStage; ot < at.length; ot++) {
            var st = at[ot];
            st.action(this, i, k, nt)
        }
        if (!it || !nt)
            return _e && (_e.maxZ = $,
            b.updateTransformMatrix(!0)),
            this;
        var ut = s || this._effectiveMesh, ct;
        if (!tt.isFrozen && (this._internalMeshDataInfo._effectiveMaterial.backFaceCulling || this.overrideMaterialSideOrientation !== null)) {
            var lt = ut._getWorldMatrixDeterminant();
            ct = this.overrideMaterialSideOrientation,
            ct == null && (ct = this._internalMeshDataInfo._effectiveMaterial.sideOrientation),
            lt < 0 && (ct = ct === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation),
            tt.sideOrientation = ct
        } else
            ct = tt.sideOrientation;
        var ft = this._internalMeshDataInfo._effectiveMaterial._preBind(it, ct);
        this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite && j.setDepthWrite(!0);
        var ht = b.forcePointsCloud ? Material.PointFillMode : b.forceWireframe ? Material.WireFrameFillMode : this._internalMeshDataInfo._effectiveMaterial.fillMode;
        this._internalMeshDataInfo._onBeforeBindObservable && this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),
        et || this._bind(i, nt, ht);
        var pt = this._internalMeshDataInfo._effectiveMaterial
          , dt = ut.getWorldMatrix();
        pt._storeEffectOnSubMeshes ? pt.bindForSubMesh(dt, this, i) : pt.bind(dt, this),
        !pt.backFaceCulling && pt.separateCullingPass && (j.setState(!0, pt.zOffset, !1, !ft, pt.cullBackFaces, pt.stencil, pt.zOffsetUnits),
        this._processRendering(this, i, nt, ht, k, et, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial),
        j.setState(!0, pt.zOffset, !1, ft, pt.cullBackFaces, pt.stencil, pt.zOffsetUnits),
        this._internalMeshDataInfo._onBetweenPassObservable && this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(i)),
        this._processRendering(this, i, nt, ht, k, et, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial),
        this._internalMeshDataInfo._effectiveMaterial.unbind();
        for (var _t = 0, mt = b._afterRenderingMeshStage; _t < mt.length; _t++) {
            var st = mt[_t];
            st.action(this, i, k, nt)
        }
        return this._internalMeshDataInfo._onAfterRenderObservable && this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),
        _e && (_e.maxZ = $,
        b.updateTransformMatrix(!0)),
        this
    }
    ,
    e.prototype._onBeforeDraw = function(i, o, s) {
        i && s && s.bindOnlyWorldMatrix(o)
    }
    ,
    e.prototype.cleanMatrixWeights = function() {
        this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind) && (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind) ? this.normalizeSkinWeightsAndExtra() : this.normalizeSkinFourWeights())
    }
    ,
    e.prototype.normalizeSkinFourWeights = function() {
        for (var i = this.getVerticesData(VertexBuffer.MatricesWeightsKind), o = i.length, s = 0; s < o; s += 4) {
            var c = i[s] + i[s + 1] + i[s + 2] + i[s + 3];
            if (c === 0)
                i[s] = 1;
            else {
                var d = 1 / c;
                i[s] *= d,
                i[s + 1] *= d,
                i[s + 2] *= d,
                i[s + 3] *= d
            }
        }
        this.setVerticesData(VertexBuffer.MatricesWeightsKind, i)
    }
    ,
    e.prototype.normalizeSkinWeightsAndExtra = function() {
        for (var i = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind), o = this.getVerticesData(VertexBuffer.MatricesWeightsKind), s = o.length, c = 0; c < s; c += 4) {
            var d = o[c] + o[c + 1] + o[c + 2] + o[c + 3];
            if (d += i[c] + i[c + 1] + i[c + 2] + i[c + 3],
            d === 0)
                o[c] = 1;
            else {
                var _ = 1 / d;
                o[c] *= _,
                o[c + 1] *= _,
                o[c + 2] *= _,
                o[c + 3] *= _,
                i[c] *= _,
                i[c + 1] *= _,
                i[c + 2] *= _,
                i[c + 3] *= _
            }
        }
        this.setVerticesData(VertexBuffer.MatricesWeightsKind, o),
        this.setVerticesData(VertexBuffer.MatricesWeightsKind, i)
    }
    ,
    e.prototype.validateSkinning = function() {
        var i = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind)
          , o = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
        if (o === null || this.skeleton == null)
            return {
                skinned: !1,
                valid: !0,
                report: "not skinned"
            };
        for (var s = o.length, c = 0, d = 0, _ = 0, b = 0, k = i === null ? 4 : 8, j = new Array, $ = 0; $ <= k; $++)
            j[$] = 0;
        for (var _e = .001, $ = 0; $ < s; $ += 4) {
            for (var et = o[$], tt = et, rt = tt === 0 ? 0 : 1, it = 1; it < k; it++) {
                var nt = it < 4 ? o[$ + it] : i[$ + it - 4];
                nt > et && c++,
                nt !== 0 && rt++,
                tt += nt,
                et = nt
            }
            if (j[rt]++,
            rt > _ && (_ = rt),
            tt === 0)
                d++;
            else {
                var ot = 1 / tt
                  , at = 0;
                for (it = 0; it < k; it++)
                    it < 4 ? at += Math.abs(o[$ + it] - o[$ + it] * ot) : at += Math.abs(i[$ + it - 4] - i[$ + it - 4] * ot);
                at > _e && b++
            }
        }
        for (var st = this.skeleton.bones.length, ut = this.getVerticesData(VertexBuffer.MatricesIndicesKind), ct = this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind), lt = 0, $ = 0; $ < s; $ += 4)
            for (var it = 0; it < k; it++) {
                var ft = it < 4 ? ut[$ + it] : ct[$ + it - 4];
                (ft >= st || ft < 0) && lt++
            }
        var ht = "Number of Weights = " + s / 4 + `
Maximum influences = ` + _ + `
Missing Weights = ` + d + `
Not Sorted = ` + c + `
Not Normalized = ` + b + `
WeightCounts = [` + j + `]
Number of bones = ` + st + `
Bad Bone Indices = ` + lt;
        return {
            skinned: !0,
            valid: d === 0 && b === 0 && lt === 0,
            report: ht
        }
    }
    ,
    e.prototype._checkDelayState = function() {
        var i = this.getScene();
        return this._geometry ? this._geometry.load(i) : this.delayLoadState === 4 && (this.delayLoadState = 2,
        this._queueLoad(i)),
        this
    }
    ,
    e.prototype._queueLoad = function(i) {
        var o = this;
        i._addPendingData(this);
        var s = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1;
        return Tools.LoadFile(this.delayLoadingFile, function(c) {
            c instanceof ArrayBuffer ? o._delayLoadingFunction(c, o) : o._delayLoadingFunction(JSON.parse(c), o),
            o.instances.forEach(function(d) {
                d.refreshBoundingInfo(),
                d._syncSubMeshes()
            }),
            o.delayLoadState = 1,
            i._removePendingData(o)
        }, function() {}, i.offlineProvider, s),
        this
    }
    ,
    e.prototype.isInFrustum = function(i) {
        return this.delayLoadState === 2 || !a.prototype.isInFrustum.call(this, i) ? !1 : (this._checkDelayState(),
        !0)
    }
    ,
    e.prototype.setMaterialById = function(i) {
        var o = this.getScene().materials, s;
        for (s = o.length - 1; s > -1; s--)
            if (o[s].id === i)
                return this.material = o[s],
                this;
        var c = this.getScene().multiMaterials;
        for (s = c.length - 1; s > -1; s--)
            if (c[s].id === i)
                return this.material = c[s],
                this;
        return this
    }
    ,
    e.prototype.getAnimatables = function() {
        var i = new Array;
        return this.material && i.push(this.material),
        this.skeleton && i.push(this.skeleton),
        i
    }
    ,
    e.prototype.bakeTransformIntoVertices = function(i) {
        if (!this.isVerticesDataPresent(VertexBuffer.PositionKind))
            return this;
        var o = this.subMeshes.splice(0);
        this._resetPointsArrayCache();
        var s = this.getVerticesData(VertexBuffer.PositionKind), c = new Array, d;
        for (d = 0; d < s.length; d += 3)
            Vector3.TransformCoordinates(Vector3.FromArray(s, d), i).toArray(c, d);
        if (this.setVerticesData(VertexBuffer.PositionKind, c, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()),
        this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
            for (s = this.getVerticesData(VertexBuffer.NormalKind),
            c = [],
            d = 0; d < s.length; d += 3)
                Vector3.TransformNormal(Vector3.FromArray(s, d), i).normalize().toArray(c, d);
            this.setVerticesData(VertexBuffer.NormalKind, c, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable())
        }
        return i.determinant() < 0 && this.flipFaces(),
        this.releaseSubMeshes(),
        this.subMeshes = o,
        this
    }
    ,
    e.prototype.bakeCurrentTransformIntoVertices = function(i) {
        return i === void 0 && (i = !0),
        this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),
        this.resetLocalMatrix(i),
        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(i, o, s, c) {
        return i === void 0 && (i = ""),
        o === void 0 && (o = null),
        c === void 0 && (c = !0),
        new e(i,this.getScene(),o,this,s,c)
    }
    ,
    e.prototype.dispose = function(i, o) {
        o === void 0 && (o = !1),
        this.morphTargetManager = null,
        this._geometry && this._geometry.releaseForMesh(this, !0);
        var s = this._internalMeshDataInfo;
        if (s._onBeforeDrawObservable && s._onBeforeDrawObservable.clear(),
        s._onBeforeBindObservable && s._onBeforeBindObservable.clear(),
        s._onBeforeRenderObservable && s._onBeforeRenderObservable.clear(),
        s._onAfterRenderObservable && s._onAfterRenderObservable.clear(),
        s._onBetweenPassObservable && s._onBetweenPassObservable.clear(),
        this._scene.useClonedMeshMap) {
            if (s.meshMap)
                for (var c in s.meshMap) {
                    var d = s.meshMap[c];
                    d && (d._internalMeshDataInfo._source = null,
                    s.meshMap[c] = void 0)
                }
            s._source && s._source._internalMeshDataInfo.meshMap && (s._source._internalMeshDataInfo.meshMap[this.uniqueId] = void 0)
        } else
            for (var _ = this.getScene().meshes, b = 0, k = _; b < k.length; b++) {
                var j = k[b]
                  , d = j;
                d._internalMeshDataInfo && d._internalMeshDataInfo._source && d._internalMeshDataInfo._source === this && (d._internalMeshDataInfo._source = null)
            }
        s._source = null,
        this._disposeInstanceSpecificData(),
        this._disposeThinInstanceSpecificData(),
        this._internalMeshDataInfo._checkReadinessObserver && this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),
        a.prototype.dispose.call(this, i, o)
    }
    ,
    e.prototype._disposeInstanceSpecificData = function() {}
    ,
    e.prototype._disposeThinInstanceSpecificData = function() {}
    ,
    e.prototype._invalidateInstanceVertexArrayObject = function() {}
    ,
    e.prototype.applyDisplacementMap = function(i, o, s, c, d, _, b) {
        var k = this;
        b === void 0 && (b = !1);
        var j = this.getScene()
          , $ = function(_e) {
            var et = _e.width
              , tt = _e.height
              , rt = k.getEngine().createCanvas(et, tt)
              , it = rt.getContext("2d");
            it.drawImage(_e, 0, 0);
            var nt = it.getImageData(0, 0, et, tt).data;
            k.applyDisplacementMapFromBuffer(nt, et, tt, o, s, d, _, b),
            c && c(k)
        };
        return Tools.LoadImage(i, $, function() {}, j.offlineProvider),
        this
    }
    ,
    e.prototype.applyDisplacementMapFromBuffer = function(i, o, s, c, d, _, b, k) {
        if (k === void 0 && (k = !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 j = this.getVerticesData(VertexBuffer.PositionKind, !0, !0)
          , $ = this.getVerticesData(VertexBuffer.NormalKind)
          , _e = this.getVerticesData(VertexBuffer.UVKind)
          , et = Vector3.Zero()
          , tt = Vector3.Zero()
          , rt = Vector2.Zero();
        _ = _ || Vector2.Zero(),
        b = b || new Vector2(1,1);
        for (var it = 0; it < j.length; it += 3) {
            Vector3.FromArrayToRef(j, it, et),
            Vector3.FromArrayToRef($, it, tt),
            Vector2.FromArrayToRef(_e, it / 3 * 2, rt);
            var nt = Math.abs(rt.x * b.x + _.x % 1) * (o - 1) % o | 0
              , ot = Math.abs(rt.y * b.y + _.y % 1) * (s - 1) % s | 0
              , at = (nt + ot * o) * 4
              , st = i[at] / 255
              , ut = i[at + 1] / 255
              , ct = i[at + 2] / 255
              , lt = st * .3 + ut * .59 + ct * .11;
            tt.normalize(),
            tt.scaleInPlace(c + (d - c) * lt),
            et = et.add(tt),
            et.toArray(j, it)
        }
        return VertexData.ComputeNormals(j, this.getIndices(), $),
        k ? (this.setVerticesData(VertexBuffer.PositionKind, j),
        this.setVerticesData(VertexBuffer.NormalKind, $),
        this.setVerticesData(VertexBuffer.UVKind, _e)) : (this.updateVerticesData(VertexBuffer.PositionKind, j),
        this.updateVerticesData(VertexBuffer.NormalKind, $)),
        this
    }
    ,
    e.prototype.convertToFlatShadedMesh = function() {
        var i = this.getVerticesDataKinds(), o = {}, s = {}, c = {}, d = !1, _, b;
        for (_ = 0; _ < i.length; _++) {
            b = i[_];
            var k = this.getVertexBuffer(b);
            if (b === VertexBuffer.NormalKind) {
                d = k.isUpdatable(),
                i.splice(_, 1),
                _--;
                continue
            }
            o[b] = k,
            s[b] = this.getVerticesData(b),
            c[b] = []
        }
        var j = this.subMeshes.slice(0), $ = this.getIndices(), _e = this.getTotalIndices(), et;
        for (et = 0; et < _e; et++) {
            var tt = $[et];
            for (_ = 0; _ < i.length; _++) {
                b = i[_];
                for (var rt = o[b].getStrideSize(), it = 0; it < rt; it++)
                    c[b].push(s[b][tt * rt + it])
            }
        }
        var nt = [], ot = c[VertexBuffer.PositionKind], at = this.getScene().useRightHandedSystem, st;
        for (at ? st = this.overrideMaterialSideOrientation === 1 : st = this.overrideMaterialSideOrientation === 0,
        et = 0; et < _e; et += 3) {
            $[et] = et,
            $[et + 1] = et + 1,
            $[et + 2] = et + 2;
            var ut = Vector3.FromArray(ot, et * 3)
              , ct = Vector3.FromArray(ot, (et + 1) * 3)
              , lt = Vector3.FromArray(ot, (et + 2) * 3)
              , ft = ut.subtract(ct)
              , ht = lt.subtract(ct)
              , pt = Vector3.Normalize(Vector3.Cross(ft, ht));
            st && pt.scaleInPlace(-1);
            for (var dt = 0; dt < 3; dt++)
                nt.push(pt.x),
                nt.push(pt.y),
                nt.push(pt.z)
        }
        for (this.setIndices($),
        this.setVerticesData(VertexBuffer.NormalKind, nt, d),
        _ = 0; _ < i.length; _++)
            b = i[_],
            this.setVerticesData(b, c[b], o[b].isUpdatable());
        this.releaseSubMeshes();
        for (var _t = 0; _t < j.length; _t++) {
            var mt = j[_t];
            SubMesh.AddToMesh(mt.materialIndex, mt.indexStart, mt.indexCount, mt.indexStart, mt.indexCount, this)
        }
        return this.synchronizeInstances(),
        this
    }
    ,
    e.prototype.convertToUnIndexedMesh = function() {
        var i = this.getVerticesDataKinds(), o = {}, s = {}, c = {}, d, _;
        for (d = 0; d < i.length; d++) {
            _ = i[d];
            var b = this.getVertexBuffer(_);
            o[_] = b,
            s[_] = o[_].getData(),
            c[_] = []
        }
        var k = this.subMeshes.slice(0), j = this.getIndices(), $ = this.getTotalIndices(), _e;
        for (_e = 0; _e < $; _e++) {
            var et = j[_e];
            for (d = 0; d < i.length; d++) {
                _ = i[d];
                for (var tt = o[_].getStrideSize(), rt = 0; rt < tt; rt++)
                    c[_].push(s[_][et * tt + rt])
            }
        }
        for (_e = 0; _e < $; _e += 3)
            j[_e] = _e,
            j[_e + 1] = _e + 1,
            j[_e + 2] = _e + 2;
        for (this.setIndices(j),
        d = 0; d < i.length; d++)
            _ = i[d],
            this.setVerticesData(_, c[_], o[_].isUpdatable());
        this.releaseSubMeshes();
        for (var it = 0; it < k.length; it++) {
            var nt = k[it];
            SubMesh.AddToMesh(nt.materialIndex, nt.indexStart, nt.indexCount, nt.indexStart, nt.indexCount, this)
        }
        return this._unIndexed = !0,
        this.synchronizeInstances(),
        this
    }
    ,
    e.prototype.flipFaces = function(i) {
        i === void 0 && (i = !1);
        var o = VertexData.ExtractFromMesh(this), s;
        if (i && this.isVerticesDataPresent(VertexBuffer.NormalKind) && o.normals)
            for (s = 0; s < o.normals.length; s++)
                o.normals[s] *= -1;
        if (o.indices) {
            var c;
            for (s = 0; s < o.indices.length; s += 3)
                c = o.indices[s + 1],
                o.indices[s + 1] = o.indices[s + 2],
                o.indices[s + 2] = c
        }
        return o.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind)),
        this
    }
    ,
    e.prototype.increaseVertices = function(i) {
        var o = VertexData.ExtractFromMesh(this)
          , s = o.uvs && !Array.isArray(o.uvs) && Array.from ? Array.from(o.uvs) : o.uvs
          , c = o.indices && !Array.isArray(o.indices) && Array.from ? Array.from(o.indices) : o.indices
          , d = o.positions && !Array.isArray(o.positions) && Array.from ? Array.from(o.positions) : o.positions
          , _ = o.normals && !Array.isArray(o.normals) && Array.from ? Array.from(o.normals) : o.normals;
        if (!c || !d || !_ || !s)
            Logger$2.Warn("VertexData contains null entries");
        else {
            o.indices = c,
            o.positions = d,
            o.normals = _,
            o.uvs = s;
            for (var b = i + 1, k = new Array, j = 0; j < b + 1; j++)
                k[j] = new Array;
            for (var $, _e, et = new Vector3(0,0,0), tt = new Vector3(0,0,0), rt = new Vector2(0,0), it = new Array, nt = new Array, ot = new Array, at, st = d.length, ut = s.length, j = 0; j < c.length; j += 3) {
                nt[0] = c[j],
                nt[1] = c[j + 1],
                nt[2] = c[j + 2];
                for (var ct = 0; ct < 3; ct++)
                    if ($ = nt[ct],
                    _e = nt[(ct + 1) % 3],
                    ot[$] === void 0 && ot[_e] === void 0 ? (ot[$] = new Array,
                    ot[_e] = new Array) : (ot[$] === void 0 && (ot[$] = new Array),
                    ot[_e] === void 0 && (ot[_e] = new Array)),
                    ot[$][_e] === void 0 && ot[_e][$] === void 0) {
                        ot[$][_e] = [],
                        et.x = (d[3 * _e] - d[3 * $]) / b,
                        et.y = (d[3 * _e + 1] - d[3 * $ + 1]) / b,
                        et.z = (d[3 * _e + 2] - d[3 * $ + 2]) / b,
                        tt.x = (_[3 * _e] - _[3 * $]) / b,
                        tt.y = (_[3 * _e + 1] - _[3 * $ + 1]) / b,
                        tt.z = (_[3 * _e + 2] - _[3 * $ + 2]) / b,
                        rt.x = (s[2 * _e] - s[2 * $]) / b,
                        rt.y = (s[2 * _e + 1] - s[2 * $ + 1]) / b,
                        ot[$][_e].push($);
                        for (var lt = 1; lt < b; lt++)
                            ot[$][_e].push(d.length / 3),
                            d[st] = d[3 * $] + lt * et.x,
                            _[st++] = _[3 * $] + lt * tt.x,
                            d[st] = d[3 * $ + 1] + lt * et.y,
                            _[st++] = _[3 * $ + 1] + lt * tt.y,
                            d[st] = d[3 * $ + 2] + lt * et.z,
                            _[st++] = _[3 * $ + 2] + lt * tt.z,
                            s[ut++] = s[2 * $] + lt * rt.x,
                            s[ut++] = s[2 * $ + 1] + lt * rt.y;
                        ot[$][_e].push(_e),
                        ot[_e][$] = new Array,
                        at = ot[$][_e].length;
                        for (var ft = 0; ft < at; ft++)
                            ot[_e][$][ft] = ot[$][_e][at - 1 - ft]
                    }
                k[0][0] = c[j],
                k[1][0] = ot[c[j]][c[j + 1]][1],
                k[1][1] = ot[c[j]][c[j + 2]][1];
                for (var lt = 2; lt < b; lt++) {
                    k[lt][0] = ot[c[j]][c[j + 1]][lt],
                    k[lt][lt] = ot[c[j]][c[j + 2]][lt],
                    et.x = (d[3 * k[lt][lt]] - d[3 * k[lt][0]]) / lt,
                    et.y = (d[3 * k[lt][lt] + 1] - d[3 * k[lt][0] + 1]) / lt,
                    et.z = (d[3 * k[lt][lt] + 2] - d[3 * k[lt][0] + 2]) / lt,
                    tt.x = (_[3 * k[lt][lt]] - _[3 * k[lt][0]]) / lt,
                    tt.y = (_[3 * k[lt][lt] + 1] - _[3 * k[lt][0] + 1]) / lt,
                    tt.z = (_[3 * k[lt][lt] + 2] - _[3 * k[lt][0] + 2]) / lt,
                    rt.x = (s[2 * k[lt][lt]] - s[2 * k[lt][0]]) / lt,
                    rt.y = (s[2 * k[lt][lt] + 1] - s[2 * k[lt][0] + 1]) / lt;
                    for (var ct = 1; ct < lt; ct++)
                        k[lt][ct] = d.length / 3,
                        d[st] = d[3 * k[lt][0]] + ct * et.x,
                        _[st++] = _[3 * k[lt][0]] + ct * tt.x,
                        d[st] = d[3 * k[lt][0] + 1] + ct * et.y,
                        _[st++] = _[3 * k[lt][0] + 1] + ct * tt.y,
                        d[st] = d[3 * k[lt][0] + 2] + ct * et.z,
                        _[st++] = _[3 * k[lt][0] + 2] + ct * tt.z,
                        s[ut++] = s[2 * k[lt][0]] + ct * rt.x,
                        s[ut++] = s[2 * k[lt][0] + 1] + ct * rt.y
                }
                k[b] = ot[c[j + 1]][c[j + 2]],
                it.push(k[0][0], k[1][0], k[1][1]);
                for (var lt = 1; lt < b; lt++) {
                    for (var ct = 0; ct < lt; ct++)
                        it.push(k[lt][ct], k[lt + 1][ct], k[lt + 1][ct + 1]),
                        it.push(k[lt][ct], k[lt + 1][ct + 1], k[lt][ct + 1]);
                    it.push(k[lt][ct], k[lt + 1][ct], k[lt + 1][ct + 1])
                }
            }
            o.indices = it,
            o.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind))
        }
    }
    ,
    e.prototype.forceSharedVertices = function() {
        var i = VertexData.ExtractFromMesh(this)
          , o = i.uvs
          , s = i.indices
          , c = i.positions
          , d = i.colors;
        if (s === void 0 || c === void 0 || s === null || c === null)
            Logger$2.Warn("VertexData contains empty entries");
        else {
            for (var _ = new Array, b = new Array, k = new Array, j = new Array, $ = new Array, _e = 0, et = {}, tt, rt, it = 0; it < s.length; it += 3) {
                rt = [s[it], s[it + 1], s[it + 2]],
                $ = new Array;
                for (var nt = 0; nt < 3; nt++) {
                    $[nt] = "";
                    for (var ot = 0; ot < 3; ot++)
                        Math.abs(c[3 * rt[nt] + ot]) < 1e-8 && (c[3 * rt[nt] + ot] = 0),
                        $[nt] += c[3 * rt[nt] + ot] + "|"
                }
                if (!($[0] == $[1] || $[0] == $[2] || $[1] == $[2]))
                    for (var nt = 0; nt < 3; nt++) {
                        if (tt = et[$[nt]],
                        tt === void 0) {
                            et[$[nt]] = _e,
                            tt = _e++;
                            for (var ot = 0; ot < 3; ot++)
                                _.push(c[3 * rt[nt] + ot]);
                            if (d != null)
                                for (var ot = 0; ot < 4; ot++)
                                    j.push(d[4 * rt[nt] + ot]);
                            if (o != null)
                                for (var ot = 0; ot < 2; ot++)
                                    k.push(o[2 * rt[nt] + ot])
                        }
                        b.push(tt)
                    }
            }
            var at = new Array;
            VertexData.ComputeNormals(_, b, at),
            i.positions = _,
            i.indices = b,
            i.normals = at,
            o != null && (i.uvs = k),
            d != null && (i.colors = j),
            i.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind))
        }
    }
    ,
    e._instancedMeshFactory = function(i, o) {
        throw _WarnImport("InstancedMesh")
    }
    ,
    e._PhysicsImpostorParser = function(i, o, s) {
        throw _WarnImport("PhysicsImpostor")
    }
    ,
    e.prototype.createInstance = function(i) {
        return e._instancedMeshFactory(i, this)
    }
    ,
    e.prototype.synchronizeInstances = function() {
        for (var i = 0; i < this.instances.length; i++) {
            var o = this.instances[i];
            o._syncSubMeshes()
        }
        return this
    }
    ,
    e.prototype.optimizeIndices = function(i) {
        var o = this
          , s = this.getIndices()
          , c = this.getVerticesData(VertexBuffer.PositionKind);
        if (!c || !s)
            return this;
        for (var d = new Array, _ = 0; _ < c.length; _ = _ + 3)
            d.push(Vector3.FromArray(c, _));
        var b = new Array;
        return AsyncLoop.SyncAsyncForLoop(d.length, 40, function(k) {
            for (var j = d.length - 1 - k, $ = d[j], _e = 0; _e < j; ++_e) {
                var et = d[_e];
                if ($.equals(et)) {
                    b[j] = _e;
                    break
                }
            }
        }, function() {
            for (var k = 0; k < s.length; ++k)
                s[k] = b[s[k]] || s[k];
            var j = o.subMeshes.slice(0);
            o.setIndices(s),
            o.subMeshes = j,
            i && i(o)
        }),
        this
    }
    ,
    e.prototype.serialize = function(i) {
        i.name = this.name,
        i.id = this.id,
        i.uniqueId = this.uniqueId,
        i.type = this.getClassName(),
        Tags && Tags.HasTags(this) && (i.tags = Tags.GetTags(this)),
        i.position = this.position.asArray(),
        this.rotationQuaternion ? i.rotationQuaternion = this.rotationQuaternion.asArray() : this.rotation && (i.rotation = this.rotation.asArray()),
        i.scaling = this.scaling.asArray(),
        this._postMultiplyPivotMatrix ? i.pivotMatrix = this.getPivotMatrix().asArray() : i.localMatrix = this.getPivotMatrix().asArray(),
        i.isEnabled = this.isEnabled(!1),
        i.isVisible = this.isVisible,
        i.infiniteDistance = this.infiniteDistance,
        i.pickable = this.isPickable,
        i.receiveShadows = this.receiveShadows,
        i.billboardMode = this.billboardMode,
        i.visibility = this.visibility,
        i.checkCollisions = this.checkCollisions,
        i.isBlocker = this.isBlocker,
        i.overrideMaterialSideOrientation = this.overrideMaterialSideOrientation,
        this.parent && (i.parentId = this.parent.uniqueId),
        i.isUnIndexed = this.isUnIndexed;
        var o = this._geometry;
        if (o && this.subMeshes) {
            i.geometryUniqueId = o.uniqueId,
            i.geometryId = o.id,
            i.subMeshes = [];
            for (var s = 0; s < this.subMeshes.length; s++) {
                var c = this.subMeshes[s];
                i.subMeshes.push({
                    materialIndex: c.materialIndex,
                    verticesStart: c.verticesStart,
                    verticesCount: c.verticesCount,
                    indexStart: c.indexStart,
                    indexCount: c.indexCount
                })
            }
        }
        if (this.material ? this.material.doNotSerialize || (i.materialId = this.material.id) : (this.material = null,
        i.materialId = this._scene.defaultMaterial.id),
        this.morphTargetManager && (i.morphTargetManagerId = this.morphTargetManager.uniqueId),
        this.skeleton && (i.skeletonId = this.skeleton.id,
        i.numBoneInfluencers = this.numBoneInfluencers),
        this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) {
            var d = this.getPhysicsImpostor();
            d && (i.physicsMass = d.getParam("mass"),
            i.physicsFriction = d.getParam("friction"),
            i.physicsRestitution = d.getParam("mass"),
            i.physicsImpostor = d.type)
        }
        this.metadata && (i.metadata = this.metadata),
        i.instances = [];
        for (var _ = 0; _ < this.instances.length; _++) {
            var b = this.instances[_];
            if (!b.doNotSerialize) {
                var k = {
                    name: b.name,
                    id: b.id,
                    isEnabled: b.isEnabled(!1),
                    isVisible: b.isVisible,
                    isPickable: b.isPickable,
                    checkCollisions: b.checkCollisions,
                    position: b.position.asArray(),
                    scaling: b.scaling.asArray()
                };
                if (b.parent && (k.parentId = b.parent.uniqueId),
                b.rotationQuaternion ? k.rotationQuaternion = b.rotationQuaternion.asArray() : b.rotation && (k.rotation = b.rotation.asArray()),
                this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) {
                    var d = b.getPhysicsImpostor();
                    d && (k.physicsMass = d.getParam("mass"),
                    k.physicsFriction = d.getParam("friction"),
                    k.physicsRestitution = d.getParam("mass"),
                    k.physicsImpostor = d.type)
                }
                b.metadata && (k.metadata = b.metadata),
                i.instances.push(k),
                SerializationHelper.AppendSerializedAnimations(b, k),
                k.ranges = b.serializeAnimationRanges()
            }
        }
        if (this._thinInstanceDataStorage.instancesCount && this._thinInstanceDataStorage.matrixData && (i.thinInstances = {
            instancesCount: this._thinInstanceDataStorage.instancesCount,
            matrixData: Tools.SliceToArray(this._thinInstanceDataStorage.matrixData),
            matrixBufferSize: this._thinInstanceDataStorage.matrixBufferSize,
            enablePicking: this.thinInstanceEnablePicking
        },
        this._userThinInstanceBuffersStorage)) {
            var j = {
                data: {},
                sizes: {},
                strides: {}
            };
            for (var $ in this._userThinInstanceBuffersStorage.data)
                j.data[$] = Tools.SliceToArray(this._userThinInstanceBuffersStorage.data[$]),
                j.sizes[$] = this._userThinInstanceBuffersStorage.sizes[$],
                j.strides[$] = this._userThinInstanceBuffersStorage.strides[$];
            i.thinInstances.userThinInstance = j
        }
        SerializationHelper.AppendSerializedAnimations(this, i),
        i.ranges = this.serializeAnimationRanges(),
        i.layerMask = this.layerMask,
        i.alphaIndex = this.alphaIndex,
        i.hasVertexAlpha = this.hasVertexAlpha,
        i.overlayAlpha = this.overlayAlpha,
        i.overlayColor = this.overlayColor.asArray(),
        i.renderOverlay = this.renderOverlay,
        i.applyFog = this.applyFog,
        this.actionManager && (i.actions = this.actionManager.serialize(this.name))
    }
    ,
    e.prototype._syncGeometryWithMorphTargetManager = function() {
        if (!!this.geometry) {
            this._markSubMeshesAsAttributesDirty();
            var i = this._internalAbstractMeshDataInfo._morphTargetManager;
            if (i && i.vertexCount) {
                if (i.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 (i.isUsingTextureForTargets)
                    return;
                for (var o = 0; o < i.numInfluencers; o++) {
                    var s = i.getActiveTarget(o)
                      , c = s.getPositions();
                    if (!c) {
                        Logger$2.Error("Invalid morph target. Target must have positions.");
                        return
                    }
                    this.geometry.setVerticesData(VertexBuffer.PositionKind + o, c, !1, 3);
                    var d = s.getNormals();
                    d && this.geometry.setVerticesData(VertexBuffer.NormalKind + o, d, !1, 3);
                    var _ = s.getTangents();
                    _ && this.geometry.setVerticesData(VertexBuffer.TangentKind + o, _, !1, 3);
                    var b = s.getUVs();
                    b && this.geometry.setVerticesData(VertexBuffer.UVKind + "_" + o, b, !1, 2)
                }
            } else
                for (var o = 0; this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + o); )
                    this.geometry.removeVerticesData(VertexBuffer.PositionKind + o),
                    this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + o) && this.geometry.removeVerticesData(VertexBuffer.NormalKind + o),
                    this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + o) && this.geometry.removeVerticesData(VertexBuffer.TangentKind + o),
                    this.geometry.isVerticesDataPresent(VertexBuffer.UVKind + o) && this.geometry.removeVerticesData(VertexBuffer.UVKind + "_" + o),
                    o++
        }
    }
    ,
    e.Parse = function(i, o, s) {
        var c;
        if (i.type && i.type === "LinesMesh" ? c = e._LinesMeshParser(i, o) : i.type && i.type === "GroundMesh" ? c = e._GroundMeshParser(i, o) : c = new e(i.name,o),
        c.id = i.id,
        Tags && Tags.AddTagsTo(c, i.tags),
        c.position = Vector3.FromArray(i.position),
        i.metadata !== void 0 && (c.metadata = i.metadata),
        i.rotationQuaternion ? c.rotationQuaternion = Quaternion.FromArray(i.rotationQuaternion) : i.rotation && (c.rotation = Vector3.FromArray(i.rotation)),
        c.scaling = Vector3.FromArray(i.scaling),
        i.localMatrix ? c.setPreTransformMatrix(Matrix.FromArray(i.localMatrix)) : i.pivotMatrix && c.setPivotMatrix(Matrix.FromArray(i.pivotMatrix)),
        c.setEnabled(i.isEnabled),
        c.isVisible = i.isVisible,
        c.infiniteDistance = i.infiniteDistance,
        c.showBoundingBox = i.showBoundingBox,
        c.showSubMeshesBoundingBox = i.showSubMeshesBoundingBox,
        i.applyFog !== void 0 && (c.applyFog = i.applyFog),
        i.pickable !== void 0 && (c.isPickable = i.pickable),
        i.alphaIndex !== void 0 && (c.alphaIndex = i.alphaIndex),
        c.receiveShadows = i.receiveShadows,
        c.billboardMode = i.billboardMode,
        i.visibility !== void 0 && (c.visibility = i.visibility),
        c.checkCollisions = i.checkCollisions,
        c.overrideMaterialSideOrientation = i.overrideMaterialSideOrientation,
        i.isBlocker !== void 0 && (c.isBlocker = i.isBlocker),
        c._shouldGenerateFlatShading = i.useFlatShading,
        i.freezeWorldMatrix && (c._waitingData.freezeWorldMatrix = i.freezeWorldMatrix),
        i.parentId && (c._waitingParentId = i.parentId),
        i.actions !== void 0 && (c._waitingData.actions = i.actions),
        i.overlayAlpha !== void 0 && (c.overlayAlpha = i.overlayAlpha),
        i.overlayColor !== void 0 && (c.overlayColor = Color3.FromArray(i.overlayColor)),
        i.renderOverlay !== void 0 && (c.renderOverlay = i.renderOverlay),
        c.isUnIndexed = !!i.isUnIndexed,
        c.hasVertexAlpha = i.hasVertexAlpha,
        i.delayLoadingFile ? (c.delayLoadState = 4,
        c.delayLoadingFile = s + i.delayLoadingFile,
        c.buildBoundingInfo(Vector3.FromArray(i.boundingBoxMinimum), Vector3.FromArray(i.boundingBoxMaximum)),
        i._binaryInfo && (c._binaryInfo = i._binaryInfo),
        c._delayInfo = [],
        i.hasUVs && c._delayInfo.push(VertexBuffer.UVKind),
        i.hasUVs2 && c._delayInfo.push(VertexBuffer.UV2Kind),
        i.hasUVs3 && c._delayInfo.push(VertexBuffer.UV3Kind),
        i.hasUVs4 && c._delayInfo.push(VertexBuffer.UV4Kind),
        i.hasUVs5 && c._delayInfo.push(VertexBuffer.UV5Kind),
        i.hasUVs6 && c._delayInfo.push(VertexBuffer.UV6Kind),
        i.hasColors && c._delayInfo.push(VertexBuffer.ColorKind),
        i.hasMatricesIndices && c._delayInfo.push(VertexBuffer.MatricesIndicesKind),
        i.hasMatricesWeights && c._delayInfo.push(VertexBuffer.MatricesWeightsKind),
        c._delayLoadingFunction = Geometry._ImportGeometry,
        SceneLoaderFlags.ForceFullSceneLoadingForIncremental && c._checkDelayState()) : Geometry._ImportGeometry(i, c),
        i.materialId ? c.setMaterialById(i.materialId) : c.material = null,
        i.morphTargetManagerId > -1 && (c.morphTargetManager = o.getMorphTargetManagerById(i.morphTargetManagerId)),
        i.skeletonId !== void 0 && i.skeletonId !== null && (c.skeleton = o.getLastSkeletonById(i.skeletonId),
        i.numBoneInfluencers && (c.numBoneInfluencers = i.numBoneInfluencers)),
        i.animations) {
            for (var d = 0; d < i.animations.length; d++) {
                var _ = i.animations[d]
                  , b = GetClass("BABYLON.Animation");
                b && c.animations.push(b.Parse(_))
            }
            Node$2.ParseAnimationRanges(c, i, o)
        }
        if (i.autoAnimate && o.beginAnimation(c, i.autoAnimateFrom, i.autoAnimateTo, i.autoAnimateLoop, i.autoAnimateSpeed || 1),
        i.layerMask && !isNaN(i.layerMask) ? c.layerMask = Math.abs(parseInt(i.layerMask)) : c.layerMask = 268435455,
        i.physicsImpostor && e._PhysicsImpostorParser(o, c, i),
        i.lodMeshIds && (c._waitingData.lods = {
            ids: i.lodMeshIds,
            distances: i.lodDistances ? i.lodDistances : null,
            coverages: i.lodCoverages ? i.lodCoverages : null
        }),
        i.instances)
            for (var k = 0; k < i.instances.length; k++) {
                var j = i.instances[k]
                  , $ = c.createInstance(j.name);
                if (j.id && ($.id = j.id),
                Tags && (j.tags ? Tags.AddTagsTo($, j.tags) : Tags.AddTagsTo($, i.tags)),
                $.position = Vector3.FromArray(j.position),
                j.metadata !== void 0 && ($.metadata = j.metadata),
                j.parentId && ($._waitingParentId = j.parentId),
                j.isEnabled !== void 0 && j.isEnabled !== null && $.setEnabled(j.isEnabled),
                j.isVisible !== void 0 && j.isVisible !== null && ($.isVisible = j.isVisible),
                j.isPickable !== void 0 && j.isPickable !== null && ($.isPickable = j.isPickable),
                j.rotationQuaternion ? $.rotationQuaternion = Quaternion.FromArray(j.rotationQuaternion) : j.rotation && ($.rotation = Vector3.FromArray(j.rotation)),
                $.scaling = Vector3.FromArray(j.scaling),
                j.checkCollisions != null && j.checkCollisions != null && ($.checkCollisions = j.checkCollisions),
                j.pickable != null && j.pickable != null && ($.isPickable = j.pickable),
                j.showBoundingBox != null && j.showBoundingBox != null && ($.showBoundingBox = j.showBoundingBox),
                j.showSubMeshesBoundingBox != null && j.showSubMeshesBoundingBox != null && ($.showSubMeshesBoundingBox = j.showSubMeshesBoundingBox),
                j.alphaIndex != null && j.showSubMeshesBoundingBox != null && ($.alphaIndex = j.alphaIndex),
                j.physicsImpostor && e._PhysicsImpostorParser(o, $, j),
                j.animations) {
                    for (d = 0; d < j.animations.length; d++) {
                        _ = j.animations[d];
                        var b = GetClass("BABYLON.Animation");
                        b && $.animations.push(b.Parse(_))
                    }
                    Node$2.ParseAnimationRanges($, j, o),
                    j.autoAnimate && o.beginAnimation($, j.autoAnimateFrom, j.autoAnimateTo, j.autoAnimateLoop, j.autoAnimateSpeed || 1)
                }
            }
        if (i.thinInstances) {
            var _e = i.thinInstances;
            if (c.thinInstanceEnablePicking = !!_e.enablePicking,
            _e.matrixData ? (c.thinInstanceSetBuffer("matrix", new Float32Array(_e.matrixData), 16, !1),
            c._thinInstanceDataStorage.matrixBufferSize = _e.matrixBufferSize,
            c._thinInstanceDataStorage.instancesCount = _e.instancesCount) : c._thinInstanceDataStorage.matrixBufferSize = _e.matrixBufferSize,
            i.thinInstances.userThinInstance) {
                var et = i.thinInstances.userThinInstance;
                for (var tt in et.data)
                    c.thinInstanceSetBuffer(tt, new Float32Array(et.data[tt]), et.strides[tt], !1),
                    c._userThinInstanceBuffersStorage.sizes[tt] = et.sizes[tt]
            }
        }
        return c
    }
    ,
    e.prototype.setPositionsForCPUSkinning = function() {
        var i = this._internalMeshDataInfo;
        if (!i._sourcePositions) {
            var o = this.getVerticesData(VertexBuffer.PositionKind);
            if (!o)
                return i._sourcePositions;
            i._sourcePositions = new Float32Array(o),
            this.isVertexBufferUpdatable(VertexBuffer.PositionKind) || this.setVerticesData(VertexBuffer.PositionKind, o, !0)
        }
        return i._sourcePositions
    }
    ,
    e.prototype.setNormalsForCPUSkinning = function() {
        var i = this._internalMeshDataInfo;
        if (!i._sourceNormals) {
            var o = this.getVerticesData(VertexBuffer.NormalKind);
            if (!o)
                return i._sourceNormals;
            i._sourceNormals = new Float32Array(o),
            this.isVertexBufferUpdatable(VertexBuffer.NormalKind) || this.setVerticesData(VertexBuffer.NormalKind, o, !0)
        }
        return i._sourceNormals
    }
    ,
    e.prototype.applySkeleton = function(i) {
        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 o = this.isVerticesDataPresent(VertexBuffer.NormalKind)
          , s = this._internalMeshDataInfo;
        if (!s._sourcePositions) {
            var c = this.subMeshes.slice();
            this.setPositionsForCPUSkinning(),
            this.subMeshes = c
        }
        o && !s._sourceNormals && this.setNormalsForCPUSkinning();
        var d = this.getVerticesData(VertexBuffer.PositionKind);
        if (!d)
            return this;
        d instanceof Float32Array || (d = new Float32Array(d));
        var _ = this.getVerticesData(VertexBuffer.NormalKind);
        if (o) {
            if (!_)
                return this;
            _ instanceof Float32Array || (_ = new Float32Array(_))
        }
        var b = this.getVerticesData(VertexBuffer.MatricesIndicesKind)
          , k = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
        if (!k || !b)
            return this;
        for (var j = this.numBoneInfluencers > 4, $ = j ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null, _e = j ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null, et = i.getTransformMatrices(this), tt = Vector3.Zero(), rt = new Matrix, it = new Matrix, nt = 0, ot, at = 0; at < d.length; at += 3,
        nt += 4) {
            var st;
            for (ot = 0; ot < 4; ot++)
                st = k[nt + ot],
                st > 0 && (Matrix.FromFloat32ArrayToRefScaled(et, Math.floor(b[nt + ot] * 16), st, it),
                rt.addToSelf(it));
            if (j)
                for (ot = 0; ot < 4; ot++)
                    st = _e[nt + ot],
                    st > 0 && (Matrix.FromFloat32ArrayToRefScaled(et, Math.floor($[nt + ot] * 16), st, it),
                    rt.addToSelf(it));
            Vector3.TransformCoordinatesFromFloatsToRef(s._sourcePositions[at], s._sourcePositions[at + 1], s._sourcePositions[at + 2], rt, tt),
            tt.toArray(d, at),
            o && (Vector3.TransformNormalFromFloatsToRef(s._sourceNormals[at], s._sourceNormals[at + 1], s._sourceNormals[at + 2], rt, tt),
            tt.toArray(_, at)),
            rt.reset()
        }
        return this.updateVerticesData(VertexBuffer.PositionKind, d),
        o && this.updateVerticesData(VertexBuffer.NormalKind, _),
        this
    }
    ,
    e.MinMax = function(i) {
        var o = null
          , s = null;
        return i.forEach(function(c) {
            var d = c.getBoundingInfo()
              , _ = d.boundingBox;
            !o || !s ? (o = _.minimumWorld,
            s = _.maximumWorld) : (o.minimizeInPlace(_.minimumWorld),
            s.maximizeInPlace(_.maximumWorld))
        }),
        !o || !s ? {
            min: Vector3.Zero(),
            max: Vector3.Zero()
        } : {
            min: o,
            max: s
        }
    }
    ,
    e.Center = function(i) {
        var o = i instanceof Array ? e.MinMax(i) : i;
        return Vector3.Center(o.min, o.max)
    }
    ,
    e.MergeMeshes = function(i, o, s, c, d, _) {
        return o === void 0 && (o = !0),
        runCoroutineSync(e._MergeMeshesCoroutine(i, o, s, c, d, _, !1))
    }
    ,
    e.MergeMeshesAsync = function(i, o, s, c, d, _) {
        return o === void 0 && (o = !0),
        runCoroutineAsync(e._MergeMeshesCoroutine(i, o, s, c, d, _, !0), createYieldingScheduler())
    }
    ,
    e._MergeMeshesCoroutine = function(i, o, s, c, d, _, b) {
        var k, j, $, _e, et, tt, rt, it, nt, ot, at, st, ut, ct, lt, ft, ht, pt, dt, _t, mt, vt, yt, Et;
        return o === void 0 && (o = !0),
        __generator(this, function(At) {
            switch (At.label) {
            case 0:
                if (i = i.filter(Boolean),
                i.length === 0)
                    return [2, null];
                if (!s) {
                    for (j = 0,
                    k = 0; k < i.length; k++)
                        if (j += i[k].getTotalVertices(),
                        j >= 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 (_ && ($ = null,
                d = !1),
                tt = new Array,
                rt = new Array,
                it = new Array,
                k = 0; k < i.length; k++) {
                    if (nt = i[k],
                    nt.isAnInstance)
                        return Logger$2.Warn("Cannot merge instance meshes."),
                        [2, null];
                    if (d && it.push(nt.getTotalIndices()),
                    _)
                        if (nt.material)
                            if (ot = nt.material,
                            ot instanceof MultiMaterial) {
                                for (et = 0; et < ot.subMaterials.length; et++)
                                    tt.indexOf(ot.subMaterials[et]) < 0 && tt.push(ot.subMaterials[et]);
                                for (_e = 0; _e < nt.subMeshes.length; _e++)
                                    rt.push(tt.indexOf(ot.subMaterials[nt.subMeshes[_e].materialIndex])),
                                    it.push(nt.subMeshes[_e].indexCount)
                            } else
                                for (tt.indexOf(ot) < 0 && tt.push(ot),
                                _e = 0; _e < nt.subMeshes.length; _e++)
                                    rt.push(tt.indexOf(ot)),
                                    it.push(nt.subMeshes[_e].indexCount);
                        else
                            for (_e = 0; _e < nt.subMeshes.length; _e++)
                                rt.push(0),
                                it.push(nt.subMeshes[_e].indexCount)
                }
                return at = i[0],
                st = function(gt) {
                    var St = gt.computeWorldMatrix(!0)
                      , xt = VertexData.ExtractFromMesh(gt, !0, !0);
                    return xt.transform(St),
                    xt
                }
                ,
                ut = st(at),
                b ? [4] : [3, 2];
            case 1:
                At.sent(),
                At.label = 2;
            case 2:
                ct = new Array(i.length - 1),
                lt = 1,
                At.label = 3;
            case 3:
                return lt < i.length ? (ct[lt - 1] = st(i[lt]),
                b ? [4] : [3, 5]) : [3, 6];
            case 4:
                At.sent(),
                At.label = 5;
            case 5:
                return lt++,
                [3, 3];
            case 6:
                ft = ut._mergeCoroutine(ct, s, b),
                ht = ft.next(),
                At.label = 7;
            case 7:
                return ht.done ? [3, 10] : b ? [4] : [3, 9];
            case 8:
                At.sent(),
                At.label = 9;
            case 9:
                return ht = ft.next(),
                [3, 7];
            case 10:
                pt = ht.value,
                c || (c = new e(at.name + "_merged",at.getScene())),
                dt = pt._applyToCoroutine(c, void 0, b),
                _t = dt.next(),
                At.label = 11;
            case 11:
                return _t.done ? [3, 14] : b ? [4] : [3, 13];
            case 12:
                At.sent(),
                At.label = 13;
            case 13:
                return _t = dt.next(),
                [3, 11];
            case 14:
                if (c.checkCollisions = at.checkCollisions,
                c.overrideMaterialSideOrientation = at.overrideMaterialSideOrientation,
                o)
                    for (k = 0; k < i.length; k++)
                        i[k].dispose();
                if (d || _) {
                    for (c.releaseSubMeshes(),
                    k = 0,
                    mt = 0; k < it.length; )
                        SubMesh.CreateFromIndices(0, mt, it[k], c, void 0, !1),
                        mt += it[k],
                        k++;
                    for (vt = 0,
                    yt = c.subMeshes; vt < yt.length; vt++)
                        Et = yt[vt],
                        Et.refreshBoundingInfo();
                    c.computeWorldMatrix(!0)
                }
                if (_) {
                    for ($ = new MultiMaterial(at.name + "_merged",at.getScene()),
                    $.subMaterials = tt,
                    _e = 0; _e < c.subMeshes.length; _e++)
                        c.subMeshes[_e].materialIndex = rt[_e];
                    c.material = $
                } else
                    c.material = at.material;
                return [2, c]
            }
        })
    }
    ,
    e.prototype.addInstance = function(i) {
        i._indexInSourceMeshInstanceArray = this.instances.length,
        this.instances.push(i)
    }
    ,
    e.prototype.removeInstance = function(i) {
        var o = i._indexInSourceMeshInstanceArray;
        if (o != -1) {
            if (o !== this.instances.length - 1) {
                var s = this.instances[this.instances.length - 1];
                this.instances[o] = s,
                s._indexInSourceMeshInstanceArray = o
            }
            i._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(i, o) {
        throw _WarnImport("GroundMesh")
    }
    ,
    e._LinesMeshParser = function(i, o) {
        throw _WarnImport("LinesMesh")
    }
    ,
    e
}(AbstractMesh);
RegisterClass("BABYLON.Mesh", Mesh);
_injectLTSMesh(Mesh);
var AutoRotationBehavior = function() {
    function a() {
        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(a.prototype, "name", {
        get: function() {
            return "AutoRotation"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "zoomStopsAnimation", {
        get: function() {
            return this._zoomStopsAnimation
        },
        set: function(e) {
            this._zoomStopsAnimation = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "idleRotationSpeed", {
        get: function() {
            return this._idleRotationSpeed
        },
        set: function(e) {
            this._idleRotationSpeed = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "idleRotationWaitTime", {
        get: function() {
            return this._idleRotationWaitTime
        },
        set: function(e) {
            this._idleRotationWaitTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "idleRotationSpinupTime", {
        get: function() {
            return this._idleRotationSpinupTime
        },
        set: function(e) {
            this._idleRotationSpinupTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rotationInProgress", {
        get: function() {
            return Math.abs(this._cameraRotationSpeed) > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.init = function() {}
    ,
    a.prototype.attach = function(e) {
        var i = this;
        this._attachedCamera = e;
        var o = this._attachedCamera.getScene();
        this._onPrePointerObservableObserver = o.onPrePointerObservable.add(function(s) {
            if (s.type === PointerEventTypes.POINTERDOWN) {
                i._isPointerDown = !0;
                return
            }
            s.type === PointerEventTypes.POINTERUP && (i._isPointerDown = !1)
        }),
        this._onAfterCheckInputsObserver = e.onAfterCheckInputsObservable.add(function() {
            var s = PrecisionDate.Now
              , c = 0;
            i._lastFrameTime != null && (c = s - i._lastFrameTime),
            i._lastFrameTime = s,
            i._applyUserInteraction();
            var d = s - i._lastInteractionTime - i._idleRotationWaitTime
              , _ = Math.max(Math.min(d / i._idleRotationSpinupTime, 1), 0);
            i._cameraRotationSpeed = i._idleRotationSpeed * _,
            i._attachedCamera && (i._attachedCamera.alpha -= i._cameraRotationSpeed * (c / 1e3))
        })
    }
    ,
    a.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
        }
    }
    ,
    a.prototype.resetLastInteractionTime = function(e) {
        this._lastInteractionTime = e != null ? e : PrecisionDate.Now
    }
    ,
    a.prototype._userIsZooming = function() {
        return this._attachedCamera ? this._attachedCamera.inertialRadiusOffset !== 0 : !1
    }
    ,
    a.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()
    }
    ,
    a.prototype._applyUserInteraction = function() {
        this._userIsMoving() && !this._shouldAnimationStopForInteraction() && (this._lastInteractionTime = PrecisionDate.Now)
    }
    ,
    a.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
    }
    ,
    a
}()
  , EasingFunction = function() {
    function a() {
        this._easingMode = a.EASINGMODE_EASEIN
    }
    return a.prototype.setEasingMode = function(e) {
        var i = Math.min(Math.max(e, 0), 2);
        this._easingMode = i
    }
    ,
    a.prototype.getEasingMode = function() {
        return this._easingMode
    }
    ,
    a.prototype.easeInCore = function(e) {
        throw new Error("You must implement this method")
    }
    ,
    a.prototype.ease = function(e) {
        switch (this._easingMode) {
        case a.EASINGMODE_EASEIN:
            return this.easeInCore(e);
        case a.EASINGMODE_EASEOUT:
            return 1 - this.easeInCore(1 - e)
        }
        return e >= .5 ? (1 - this.easeInCore((1 - e) * 2)) * .5 + .5 : this.easeInCore(e * 2) * .5
    }
    ,
    a.EASINGMODE_EASEIN = 0,
    a.EASINGMODE_EASEOUT = 1,
    a.EASINGMODE_EASEINOUT = 2,
    a
}()
  , CircleEase = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(i) {
        return i = Math.max(0, Math.min(1, i)),
        1 - Math.sqrt(1 - i * i)
    }
    ,
    e
}(EasingFunction)
  , BackEase = function(a) {
    __extends(e, a);
    function e(i) {
        i === void 0 && (i = 1);
        var o = a.call(this) || this;
        return o.amplitude = i,
        o
    }
    return e.prototype.easeInCore = function(i) {
        var o = Math.max(0, this.amplitude);
        return Math.pow(i, 3) - i * o * Math.sin(3.141592653589793 * i)
    }
    ,
    e
}(EasingFunction);
(function(a) {
    __extends(e, a);
    function e(i, o) {
        i === void 0 && (i = 3),
        o === void 0 && (o = 2);
        var s = a.call(this) || this;
        return s.bounces = i,
        s.bounciness = o,
        s
    }
    return e.prototype.easeInCore = function(i) {
        var o = Math.max(0, this.bounces)
          , s = this.bounciness;
        s <= 1 && (s = 1.001);
        var c = Math.pow(s, o)
          , d = 1 - s
          , _ = (1 - c) / d + c * .5
          , b = i * _
          , k = Math.log(-b * (1 - s) + 1) / Math.log(s)
          , j = Math.floor(k)
          , $ = j + 1
          , _e = (1 - Math.pow(s, j)) / (d * _)
          , et = (1 - Math.pow(s, $)) / (d * _)
          , tt = (_e + et) * .5
          , rt = i - tt
          , it = tt - _e;
        return -Math.pow(1 / s, o - j) / (it * it) * (rt - it) * (rt + it)
    }
    ,
    e
}
)(EasingFunction);
(function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(i) {
        return i * i * i
    }
    ,
    e
}
)(EasingFunction);
(function(a) {
    __extends(e, a);
    function e(i, o) {
        i === void 0 && (i = 3),
        o === void 0 && (o = 3);
        var s = a.call(this) || this;
        return s.oscillations = i,
        s.springiness = o,
        s
    }
    return e.prototype.easeInCore = function(i) {
        var o, s = Math.max(0, this.oscillations), c = Math.max(0, this.springiness);
        return c == 0 ? o = i : o = (Math.exp(c * i) - 1) / (Math.exp(c) - 1),
        o * Math.sin((6.283185307179586 * s + 1.5707963267948966) * i)
    }
    ,
    e
}
)(EasingFunction);
var ExponentialEase = function(a) {
    __extends(e, a);
    function e(i) {
        i === void 0 && (i = 2);
        var o = a.call(this) || this;
        return o.exponent = i,
        o
    }
    return e.prototype.easeInCore = function(i) {
        return this.exponent <= 0 ? i : (Math.exp(this.exponent * i) - 1) / (Math.exp(this.exponent) - 1)
    }
    ,
    e
}(EasingFunction);
(function(a) {
    __extends(e, a);
    function e(i) {
        i === void 0 && (i = 2);
        var o = a.call(this) || this;
        return o.power = i,
        o
    }
    return e.prototype.easeInCore = function(i) {
        var o = Math.max(0, this.power);
        return Math.pow(i, o)
    }
    ,
    e
}
)(EasingFunction);
(function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(i) {
        return i * i
    }
    ,
    e
}
)(EasingFunction);
(function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(i) {
        return i * i * i * i
    }
    ,
    e
}
)(EasingFunction);
(function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(i) {
        return i * i * i * i * i
    }
    ,
    e
}
)(EasingFunction);
var SineEase = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(i) {
        return 1 - Math.sin(1.5707963267948966 * (1 - i))
    }
    ,
    e
}(EasingFunction);
(function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        i === void 0 && (i = 0),
        o === void 0 && (o = 0),
        s === void 0 && (s = 1),
        c === void 0 && (c = 1);
        var d = a.call(this) || this;
        return d.x1 = i,
        d.y1 = o,
        d.x2 = s,
        d.y2 = c,
        d
    }
    return e.prototype.easeInCore = function(i) {
        return BezierCurve.Interpolate(i, this.x1, this.y1, this.x2, this.y2)
    }
    ,
    e
}
)(EasingFunction);
var BouncingBehavior = function() {
    function a() {
        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(a.prototype, "name", {
        get: function() {
            return "Bouncing"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "autoTransitionRange", {
        get: function() {
            return this._autoTransitionRange
        },
        set: function(e) {
            var i = this;
            if (this._autoTransitionRange !== e) {
                this._autoTransitionRange = e;
                var o = this._attachedCamera;
                !o || (e ? this._onMeshTargetChangedObserver = o.onMeshTargetChangedObservable.add(function(s) {
                    if (!!s) {
                        s.computeWorldMatrix(!0);
                        var c = s.getBoundingInfo().diagonalLength;
                        i.lowerRadiusTransitionRange = c * .05,
                        i.upperRadiusTransitionRange = c * .05
                    }
                }) : this._onMeshTargetChangedObserver && o.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.init = function() {}
    ,
    a.prototype.attach = function(e) {
        var i = this;
        this._attachedCamera = e,
        this._onAfterCheckInputsObserver = e.onAfterCheckInputsObservable.add(function() {
            !i._attachedCamera || (i._isRadiusAtLimit(i._attachedCamera.lowerRadiusLimit) && i._applyBoundRadiusAnimation(i.lowerRadiusTransitionRange),
            i._isRadiusAtLimit(i._attachedCamera.upperRadiusLimit) && i._applyBoundRadiusAnimation(i.upperRadiusTransitionRange))
        })
    }
    ,
    a.prototype.detach = function() {
        !this._attachedCamera || (this._onAfterCheckInputsObserver && this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),
        this._onMeshTargetChangedObserver && this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),
        this._attachedCamera = null)
    }
    ,
    a.prototype._isRadiusAtLimit = function(e) {
        return this._attachedCamera ? this._attachedCamera.radius === e && !this._radiusIsAnimating : !1
    }
    ,
    a.prototype._applyBoundRadiusAnimation = function(e) {
        var i = this;
        if (!!this._attachedCamera) {
            this._radiusBounceTransition || (a.EasingFunction.setEasingMode(a.EasingMode),
            this._radiusBounceTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, a.EasingFunction)),
            this._cachedWheelPrecision = this._attachedCamera.wheelPrecision,
            this._attachedCamera.wheelPrecision = 1 / 0,
            this._attachedCamera.inertialRadiusOffset = 0,
            this.stopAllAnimations(),
            this._radiusIsAnimating = !0;
            var o = Animation.TransitionTo("radius", this._attachedCamera.radius + e, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function() {
                return i._clearAnimationLocks()
            });
            o && this._animatables.push(o)
        }
    }
    ,
    a.prototype._clearAnimationLocks = function() {
        this._radiusIsAnimating = !1,
        this._attachedCamera && (this._attachedCamera.wheelPrecision = this._cachedWheelPrecision)
    }
    ,
    a.prototype.stopAllAnimations = function() {
        for (this._attachedCamera && (this._attachedCamera.animations = []); this._animatables.length; )
            this._animatables[0].onAnimationEnd = null,
            this._animatables[0].stop(),
            this._animatables.shift()
    }
    ,
    a.EasingFunction = new BackEase(.3),
    a.EasingMode = EasingFunction.EASINGMODE_EASEOUT,
    a
}()
  , FramingBehavior = function() {
    function a() {
        this.onTargetFramingAnimationEndObservable = new Observable,
        this._mode = a.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(a.prototype, "name", {
        get: function() {
            return "Framing"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "mode", {
        get: function() {
            return this._mode
        },
        set: function(e) {
            this._mode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "radiusScale", {
        get: function() {
            return this._radiusScale
        },
        set: function(e) {
            this._radiusScale = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "positionScale", {
        get: function() {
            return this._positionScale
        },
        set: function(e) {
            this._positionScale = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "defaultElevation", {
        get: function() {
            return this._defaultElevation
        },
        set: function(e) {
            this._defaultElevation = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "elevationReturnTime", {
        get: function() {
            return this._elevationReturnTime
        },
        set: function(e) {
            this._elevationReturnTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "elevationReturnWaitTime", {
        get: function() {
            return this._elevationReturnWaitTime
        },
        set: function(e) {
            this._elevationReturnWaitTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "zoomStopsAnimation", {
        get: function() {
            return this._zoomStopsAnimation
        },
        set: function(e) {
            this._zoomStopsAnimation = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "framingTime", {
        get: function() {
            return this._framingTime
        },
        set: function(e) {
            this._framingTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.init = function() {}
    ,
    a.prototype.attach = function(e) {
        var i = this;
        this._attachedCamera = e;
        var o = this._attachedCamera.getScene();
        a.EasingFunction.setEasingMode(a.EasingMode),
        this._onPrePointerObservableObserver = o.onPrePointerObservable.add(function(s) {
            if (s.type === PointerEventTypes.POINTERDOWN) {
                i._isPointerDown = !0;
                return
            }
            s.type === PointerEventTypes.POINTERUP && (i._isPointerDown = !1)
        }),
        this._onMeshTargetChangedObserver = e.onMeshTargetChangedObservable.add(function(s) {
            s && i.zoomOnMesh(s, void 0, function() {
                i.onTargetFramingAnimationEndObservable.notifyObservers()
            })
        }),
        this._onAfterCheckInputsObserver = e.onAfterCheckInputsObservable.add(function() {
            i._applyUserInteraction(),
            i._maintainCameraAboveGround()
        })
    }
    ,
    a.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
        }
    }
    ,
    a.prototype.zoomOnMesh = function(e, i, o) {
        i === void 0 && (i = !1),
        o === void 0 && (o = null),
        e.computeWorldMatrix(!0);
        var s = e.getBoundingInfo().boundingBox;
        this.zoomOnBoundingInfo(s.minimumWorld, s.maximumWorld, i, o)
    }
    ,
    a.prototype.zoomOnMeshHierarchy = function(e, i, o) {
        i === void 0 && (i = !1),
        o === void 0 && (o = null),
        e.computeWorldMatrix(!0);
        var s = e.getHierarchyBoundingVectors(!0);
        this.zoomOnBoundingInfo(s.min, s.max, i, o)
    }
    ,
    a.prototype.zoomOnMeshesHierarchy = function(e, i, o) {
        i === void 0 && (i = !1),
        o === void 0 && (o = null);
        for (var s = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE), c = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE), d = 0; d < e.length; d++) {
            var _ = e[d].getHierarchyBoundingVectors(!0);
            Vector3.CheckExtends(_.min, s, c),
            Vector3.CheckExtends(_.max, s, c)
        }
        this.zoomOnBoundingInfo(s, c, i, o)
    }
    ,
    a.prototype.zoomOnBoundingInfo = function(e, i, o, s) {
        var c = this;
        o === void 0 && (o = !1),
        s === void 0 && (s = null);
        var d;
        if (!!this._attachedCamera) {
            var _ = e.y
              , b = i.y
              , k = _ + (b - _) * this._positionScale
              , j = i.subtract(e).scale(.5);
            if (o)
                d = new Vector3(0,k,0);
            else {
                var $ = e.add(j);
                d = new Vector3($.x,k,$.z)
            }
            this._vectorTransition || (this._vectorTransition = Animation.CreateAnimation("target", Animation.ANIMATIONTYPE_VECTOR3, 60, a.EasingFunction)),
            this._betaIsAnimating = !0;
            var _e = Animation.TransitionTo("target", d, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
            _e && this._animatables.push(_e);
            var et = 0;
            if (this._mode === a.FitFrustumSidesMode) {
                var tt = this._calculateLowerRadiusFromModelBoundingSphere(e, i);
                this.autoCorrectCameraLimitsAndSensibility && (this._attachedCamera.lowerRadiusLimit = j.length() + this._attachedCamera.minZ),
                et = tt
            } else
                this._mode === a.IgnoreBoundsSizeMode && (et = this._calculateLowerRadiusFromModelBoundingSphere(e, i),
                this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null && (this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ));
            if (this.autoCorrectCameraLimitsAndSensibility) {
                var rt = i.subtract(e).length();
                this._attachedCamera.panningSensibility = 5e3 / rt,
                this._attachedCamera.wheelPrecision = 100 / et
            }
            this._radiusTransition || (this._radiusTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, a.EasingFunction)),
            _e = Animation.TransitionTo("radius", et, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function() {
                c.stopAllAnimations(),
                s && s(),
                c._attachedCamera && c._attachedCamera.useInputToRestoreState && c._attachedCamera.storeState()
            }),
            _e && this._animatables.push(_e)
        }
    }
    ,
    a.prototype._calculateLowerRadiusFromModelBoundingSphere = function(e, i) {
        var o = i.subtract(e)
          , s = o.length()
          , c = this._getFrustumSlope()
          , d = s * .5
          , _ = d * this._radiusScale
          , b = _ * Math.sqrt(1 + 1 / (c.x * c.x))
          , k = _ * Math.sqrt(1 + 1 / (c.y * c.y))
          , j = Math.max(b, k)
          , $ = this._attachedCamera;
        return $ ? ($.lowerRadiusLimit && this._mode === a.IgnoreBoundsSizeMode && (j = j < $.lowerRadiusLimit ? $.lowerRadiusLimit : j),
        $.upperRadiusLimit && (j = j > $.upperRadiusLimit ? $.upperRadiusLimit : j),
        j) : 0
    }
    ,
    a.prototype._maintainCameraAboveGround = function() {
        var e = this;
        if (!(this._elevationReturnTime < 0)) {
            var i = PrecisionDate.Now - this._lastInteractionTime
              , o = Math.PI * .5 - this._defaultElevation
              , s = Math.PI * .5;
            if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > s && i >= this._elevationReturnWaitTime) {
                this._betaIsAnimating = !0,
                this.stopAllAnimations(),
                this._betaTransition || (this._betaTransition = Animation.CreateAnimation("beta", Animation.ANIMATIONTYPE_FLOAT, 60, a.EasingFunction));
                var c = Animation.TransitionTo("beta", o, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function() {
                    e._clearAnimationLocks(),
                    e.stopAllAnimations()
                });
                c && this._animatables.push(c)
            }
        }
    }
    ,
    a.prototype._getFrustumSlope = function() {
        var e = this._attachedCamera;
        if (!e)
            return Vector2.Zero();
        var i = e.getScene().getEngine()
          , o = i.getAspectRatio(e)
          , s = Math.tan(e.fov / 2)
          , c = s * o;
        return new Vector2(c,s)
    }
    ,
    a.prototype._clearAnimationLocks = function() {
        this._betaIsAnimating = !1
    }
    ,
    a.prototype._applyUserInteraction = function() {
        this.isUserIsMoving && (this._lastInteractionTime = PrecisionDate.Now,
        this.stopAllAnimations(),
        this._clearAnimationLocks())
    }
    ,
    a.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(a.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
    }),
    a.EasingFunction = new ExponentialEase,
    a.EasingMode = EasingFunction.EASINGMODE_EASEINOUT,
    a.IgnoreBoundsSizeMode = 0,
    a.FitFrustumSidesMode = 1,
    a
}()
  , TargetCamera = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        c === void 0 && (c = !0);
        var d = a.call(this, i, o, s, c) || this;
        return d._tmpUpVector = Vector3.Zero(),
        d._tmpTargetVector = Vector3.Zero(),
        d.cameraDirection = new Vector3(0,0,0),
        d.cameraRotation = new Vector2(0,0),
        d.ignoreParentScaling = !1,
        d.updateUpVectorFromRotation = !1,
        d._tmpQuaternion = new Quaternion,
        d.rotation = new Vector3(0,0,0),
        d.speed = 2,
        d.noRotationConstraint = !1,
        d.invertRotation = !1,
        d.inverseRotationSpeed = .2,
        d.lockedTarget = null,
        d._currentTarget = Vector3.Zero(),
        d._initialFocalDistance = 1,
        d._viewMatrix = Matrix.Zero(),
        d._camMatrix = Matrix.Zero(),
        d._cameraTransformMatrix = Matrix.Zero(),
        d._cameraRotationMatrix = Matrix.Zero(),
        d._referencePoint = new Vector3(0,0,1),
        d._transformedReferencePoint = Vector3.Zero(),
        d._defaultUp = Vector3.Up(),
        d._cachedRotationZ = 0,
        d._cachedQuaternionRotationZ = 0,
        d
    }
    return e.prototype.getFrontPosition = function(i) {
        this.getWorldMatrix();
        var o = this.getTarget().subtract(this.position);
        return o.normalize(),
        o.scaleInPlace(i),
        this.globalPosition.add(o)
    }
    ,
    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()),
        a.prototype.storeState.call(this)
    }
    ,
    e.prototype._restoreStateValues = function() {
        return a.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() {
        a.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(i) {
        i || a.prototype._updateCache.call(this);
        var o = this._getLockedTargetPosition();
        o ? this._cache.lockedTarget ? this._cache.lockedTarget.copyFrom(o) : this._cache.lockedTarget = o.clone() : this._cache.lockedTarget = null,
        this._cache.rotation.copyFrom(this.rotation),
        this.rotationQuaternion && this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)
    }
    ,
    e.prototype._isSynchronizedViewMatrix = function() {
        if (!a.prototype._isSynchronizedViewMatrix.call(this))
            return !1;
        var i = this._getLockedTargetPosition();
        return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(i) : !i) && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation))
    }
    ,
    e.prototype._computeLocalCameraSpeed = function() {
        var i = this.getEngine();
        return this.speed * Math.sqrt(i.getDeltaTime() / (i.getFps() * 100))
    }
    ,
    e.prototype.setTarget = function(i) {
        this.upVector.normalize(),
        this._initialFocalDistance = i.subtract(this.position).length(),
        this.position.z === i.z && (this.position.z += Epsilon),
        this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),
        Matrix.LookAtLHToRef(this.position, i, this._defaultUp, this._camMatrix),
        this._camMatrix.invert(),
        this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
        var o = i.subtract(this.position);
        o.x >= 0 ? this.rotation.y = -Math.atan(o.z / o.x) + Math.PI / 2 : this.rotation.y = -Math.atan(o.z / o.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(i) {
            this.setTarget(i)
        },
        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 i = this.invertRotation ? -this.inverseRotationSpeed : 1
          , o = this._decideIfNeedsToMove()
          , s = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
        if (o && this._updatePosition(),
        s) {
            if (this.rotationQuaternion && this.rotationQuaternion.toEulerAnglesToRef(this.rotation),
            this.rotation.x += this.cameraRotation.x * i,
            this.rotation.y += this.cameraRotation.y * i,
            !this.noRotationConstraint) {
                var c = 1.570796;
                this.rotation.x > c && (this.rotation.x = c),
                this.rotation.x < -c && (this.rotation.x = -c)
            }
            if (this.rotationQuaternion) {
                var d = this.rotation.lengthSquared();
                d && Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion)
            }
        }
        o && (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)),
        s && (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)),
        a.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(i, o, s) {
        if (this.ignoreParentScaling) {
            if (this.parent) {
                var c = this.parent.getWorldMatrix();
                Vector3.TransformCoordinatesToRef(i, c, this._globalPosition),
                Vector3.TransformCoordinatesToRef(o, c, this._tmpTargetVector),
                Vector3.TransformNormalToRef(s, c, this._tmpUpVector),
                this._markSyncedWithParent()
            } else
                this._globalPosition.copyFrom(i),
                this._tmpTargetVector.copyFrom(o),
                this._tmpUpVector.copyFrom(s);
            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(i, o, s, this._viewMatrix) : Matrix.LookAtLHToRef(i, o, s, this._viewMatrix),
        this.parent) {
            var c = this.parent.getWorldMatrix();
            this._viewMatrix.invert(),
            this._viewMatrix.multiplyToRef(c, this._viewMatrix),
            this._viewMatrix.getTranslationToRef(this._globalPosition),
            this._viewMatrix.invert(),
            this._markSyncedWithParent()
        } else
            this._globalPosition.copyFrom(i)
    }
    ,
    e.prototype.createRigCamera = function(i, o) {
        if (this.cameraRigMode !== Camera$1.RIG_MODE_NONE) {
            var s = new e(i,this.position.clone(),this.getScene());
            return s.isRigCamera = !0,
            s.rigParent = this,
            (this.cameraRigMode === Camera$1.RIG_MODE_VR || this.cameraRigMode === Camera$1.RIG_MODE_WEBVR) && (this.rotationQuaternion || (this.rotationQuaternion = new Quaternion),
            s._cameraRigParams = {},
            s.rotationQuaternion = new Quaternion),
            s
        }
        return null
    }
    ,
    e.prototype._updateRigCameras = function() {
        var i = this._rigCameras[0]
          , o = 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 s = this.cameraRigMode === Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1
              , c = this.cameraRigMode === Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1;
            this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * s, i),
            this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * c, o);
            break;
        case Camera$1.RIG_MODE_VR:
            i.rotationQuaternion ? (i.rotationQuaternion.copyFrom(this.rotationQuaternion),
            o.rotationQuaternion.copyFrom(this.rotationQuaternion)) : (i.rotation.copyFrom(this.rotation),
            o.rotation.copyFrom(this.rotation)),
            i.position.copyFrom(this.position),
            o.position.copyFrom(this.position);
            break
        }
        a.prototype._updateRigCameras.call(this)
    }
    ,
    e.prototype._getRigCamPositionAndTarget = function(i, o) {
        var s = this.getTarget();
        s.subtractToRef(this.position, e._TargetFocalPoint),
        e._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);
        var c = e._TargetFocalPoint.addInPlace(this.position);
        Matrix.TranslationToRef(-c.x, -c.y, -c.z, e._TargetTransformMatrix),
        e._TargetTransformMatrix.multiplyToRef(Matrix.RotationAxis(o.upVector, i), e._RigCamTransformMatrix),
        Matrix.TranslationToRef(c.x, c.y, c.z, e._TargetTransformMatrix),
        e._RigCamTransformMatrix.multiplyToRef(e._TargetTransformMatrix, e._RigCamTransformMatrix),
        Vector3.TransformCoordinatesToRef(this.position, e._RigCamTransformMatrix, o.position),
        o.setTarget(c)
    }
    ,
    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 a(e) {
        this.attachedToElement = !1,
        this.attached = {},
        this.camera = e,
        this.checkInputs = function() {}
    }
    return a.prototype.add = function(e) {
        var i = e.getSimpleName();
        if (this.attached[i]) {
            Logger$2.Warn("camera input of type " + i + " already exists on camera");
            return
        }
        this.attached[i] = e,
        e.camera = this.camera,
        e.checkInputs && (this.checkInputs = this._addCheckInputs(e.checkInputs.bind(e))),
        this.attachedToElement && e.attachControl()
    }
    ,
    a.prototype.remove = function(e) {
        for (var i in this.attached) {
            var o = this.attached[i];
            o === e && (o.detachControl(),
            o.camera = null,
            delete this.attached[i],
            this.rebuildInputCheck())
        }
    }
    ,
    a.prototype.removeByType = function(e) {
        for (var i in this.attached) {
            var o = this.attached[i];
            o.getClassName() === e && (o.detachControl(),
            o.camera = null,
            delete this.attached[i],
            this.rebuildInputCheck())
        }
    }
    ,
    a.prototype._addCheckInputs = function(e) {
        var i = this.checkInputs;
        return function() {
            i(),
            e()
        }
    }
    ,
    a.prototype.attachInput = function(e) {
        this.attachedToElement && e.attachControl(this.noPreventDefault)
    }
    ,
    a.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 i in this.attached)
                this.attached[i].attachControl(e)
        }
    }
    ,
    a.prototype.detachElement = function(e) {
        e === void 0 && (e = !1);
        for (var i in this.attached)
            this.attached[i].detachControl(),
            e && (this.attached[i].camera = null);
        this.attachedToElement = !1
    }
    ,
    a.prototype.rebuildInputCheck = function() {
        this.checkInputs = function() {}
        ;
        for (var e in this.attached) {
            var i = this.attached[e];
            i.checkInputs && (this.checkInputs = this._addCheckInputs(i.checkInputs.bind(i)))
        }
    }
    ,
    a.prototype.clear = function() {
        this.attachedToElement && this.detachElement(!0),
        this.attached = {},
        this.attachedToElement = !1,
        this.checkInputs = function() {}
    }
    ,
    a.prototype.serialize = function(e) {
        var i = {};
        for (var o in this.attached) {
            var s = this.attached[o]
              , c = SerializationHelper.Serialize(s);
            i[s.getClassName()] = c
        }
        e.inputsmgr = i
    }
    ,
    a.prototype.parse = function(e) {
        var i = e.inputsmgr;
        if (i) {
            this.clear();
            for (var o in i) {
                var s = CameraInputTypes[o];
                if (s) {
                    var c = i[o]
                      , d = SerializationHelper.Parse(function() {
                        return new s
                    }, c, null);
                    this.add(d)
                }
            }
        } else
            for (var o in this.attached) {
                var s = CameraInputTypes[this.attached[o].getClassName()];
                if (s) {
                    var d = SerializationHelper.Parse(function() {
                        return new s
                    }, e, null);
                    this.remove(this.attached[o]),
                    this.add(d)
                }
            }
    }
    ,
    a
}()
  , BaseCameraPointersInput = function() {
    function a() {
        this._currentActiveButton = -1,
        this.buttons = [0, 1, 2]
    }
    return a.prototype.attachControl = function(e) {
        var i = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments);
        var o = this.camera.getEngine()
          , s = o.getInputElement()
          , c = 0
          , d = 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(b, k) {
            var j = b.event
              , $ = j.pointerType === "touch";
            if (!o.isInVRExclusivePointerMode && !(b.type !== PointerEventTypes.POINTERMOVE && i.buttons.indexOf(j.button) === -1)) {
                var _e = j.srcElement || j.target;
                if (i._altKey = j.altKey,
                i._ctrlKey = j.ctrlKey,
                i._metaKey = j.metaKey,
                i._shiftKey = j.shiftKey,
                i._buttonsPressed = j.buttons,
                o.isPointerLock) {
                    var et = j.movementX || j.mozMovementX || j.webkitMovementX || j.msMovementX || 0
                      , tt = j.movementY || j.mozMovementY || j.webkitMovementY || j.msMovementY || 0;
                    i.onTouch(null, et, tt),
                    i.pointA = null,
                    i.pointB = null
                } else if (b.type === PointerEventTypes.POINTERDOWN && (i._currentActiveButton === -1 || $)) {
                    try {
                        _e == null || _e.setPointerCapture(j.pointerId)
                    } catch {}
                    i.pointA === null ? i.pointA = {
                        x: j.clientX,
                        y: j.clientY,
                        pointerId: j.pointerId,
                        type: j.pointerType
                    } : i.pointB === null && (i.pointB = {
                        x: j.clientX,
                        y: j.clientY,
                        pointerId: j.pointerId,
                        type: j.pointerType
                    }),
                    i._currentActiveButton === -1 && !$ && (i._currentActiveButton = j.button),
                    i.onButtonDown(j),
                    e || (j.preventDefault(),
                    s && s.focus())
                } else if (b.type === PointerEventTypes.POINTERDOUBLETAP)
                    i.onDoubleTap(j.pointerType);
                else if (b.type === PointerEventTypes.POINTERUP && (i._currentActiveButton === j.button || $)) {
                    try {
                        _e == null || _e.releasePointerCapture(j.pointerId)
                    } catch {}
                    $ || (i.pointB = null),
                    o._badOS ? i.pointA = i.pointB = null : i.pointB && i.pointA && i.pointA.pointerId == j.pointerId ? (i.pointA = i.pointB,
                    i.pointB = null) : i.pointA && i.pointB && i.pointB.pointerId == j.pointerId ? i.pointB = null : i.pointA = i.pointB = null,
                    (c !== 0 || d) && (i.onMultiTouch(i.pointA, i.pointB, c, 0, d, null),
                    c = 0,
                    d = null),
                    i._currentActiveButton = -1,
                    i.onButtonUp(j),
                    e || j.preventDefault()
                } else if (b.type === PointerEventTypes.POINTERMOVE) {
                    if (e || j.preventDefault(),
                    i.pointA && i.pointB === null) {
                        var et = j.clientX - i.pointA.x
                          , tt = j.clientY - i.pointA.y;
                        i.onTouch(i.pointA, et, tt),
                        i.pointA.x = j.clientX,
                        i.pointA.y = j.clientY
                    } else if (i.pointA && i.pointB) {
                        var rt = i.pointA.pointerId === j.pointerId ? i.pointA : i.pointB;
                        rt.x = j.clientX,
                        rt.y = j.clientY;
                        var it = i.pointA.x - i.pointB.x
                          , nt = i.pointA.y - i.pointB.y
                          , ot = it * it + nt * nt
                          , at = {
                            x: (i.pointA.x + i.pointB.x) / 2,
                            y: (i.pointA.y + i.pointB.y) / 2,
                            pointerId: j.pointerId,
                            type: b.type
                        };
                        i.onMultiTouch(i.pointA, i.pointB, c, ot, d, at),
                        d = at,
                        c = ot
                    }
                }
            }
        }
        ,
        this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE | PointerEventTypes.POINTERDOUBLETAP),
        this._onLostFocus = function() {
            i.pointA = i.pointB = null,
            c = 0,
            d = null,
            i.onLostFocus()
        }
        ,
        s && s.addEventListener("contextmenu", this.onContextMenu.bind(this), !1);
        var _ = this.camera.getScene().getEngine().getHostWindow();
        _ && Tools.RegisterTopRootEvents(_, [{
            name: "blur",
            handler: this._onLostFocus
        }])
    }
    ,
    a.prototype.detachControl = function(e) {
        if (this._onLostFocus) {
            var i = this.camera.getScene().getEngine().getHostWindow();
            i && Tools.UnregisterTopRootEvents(i, [{
                name: "blur",
                handler: this._onLostFocus
            }])
        }
        if (this._observer) {
            if (this.camera.getScene().onPointerObservable.remove(this._observer),
            this._observer = null,
            this.onContextMenu) {
                var o = this.camera.getScene().getEngine().getInputElement();
                o && o.removeEventListener("contextmenu", this.onContextMenu)
            }
            this._onLostFocus = null
        }
        this._altKey = !1,
        this._ctrlKey = !1,
        this._metaKey = !1,
        this._shiftKey = !1,
        this._buttonsPressed = 0
    }
    ,
    a.prototype.getClassName = function() {
        return "BaseCameraPointersInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "pointers"
    }
    ,
    a.prototype.onDoubleTap = function(e) {}
    ,
    a.prototype.onTouch = function(e, i, o) {}
    ,
    a.prototype.onMultiTouch = function(e, i, o, s, c, d) {}
    ,
    a.prototype.onContextMenu = function(e) {
        e.preventDefault()
    }
    ,
    a.prototype.onButtonDown = function(e) {}
    ,
    a.prototype.onButtonUp = function(e) {}
    ,
    a.prototype.onLostFocus = function() {}
    ,
    __decorate([serialize()], a.prototype, "buttons", void 0),
    a
}()
  , ArcRotateCameraPointersInput = function(a) {
    __extends(e, a);
    function e() {
        var i = a !== null && a.apply(this, arguments) || this;
        return i.buttons = [0, 1, 2],
        i.angularSensibilityX = 1e3,
        i.angularSensibilityY = 1e3,
        i.pinchPrecision = 12,
        i.pinchDeltaPercentage = 0,
        i.useNaturalPinchZoom = !1,
        i.pinchZoom = !0,
        i.panningSensibility = 1e3,
        i.multiTouchPanning = !0,
        i.multiTouchPanAndZoom = !0,
        i.pinchInwards = !0,
        i._isPanClick = !1,
        i._twoFingerActivityCount = 0,
        i._isPinching = !1,
        i
    }
    return e.prototype.getClassName = function() {
        return "ArcRotateCameraPointersInput"
    }
    ,
    e.prototype._computeMultiTouchPanning = function(i, o) {
        if (this.panningSensibility !== 0 && i && o) {
            var s = o.x - i.x
              , c = o.y - i.y;
            this.camera.inertialPanningX += -s / this.panningSensibility,
            this.camera.inertialPanningY += c / this.panningSensibility
        }
    }
    ,
    e.prototype._computePinchZoom = function(i, o) {
        var s = this.camera.radius || e.MinimumRadiusForPinch;
        this.useNaturalPinchZoom ? this.camera.radius = s * Math.sqrt(i) / Math.sqrt(o) : this.pinchDeltaPercentage ? this.camera.inertialRadiusOffset += (o - i) * .001 * s * this.pinchDeltaPercentage : this.camera.inertialRadiusOffset += (o - i) / (this.pinchPrecision * (this.pinchInwards ? 1 : -1) * (this.angularSensibilityX + this.angularSensibilityY) / 2)
    }
    ,
    e.prototype.onTouch = function(i, o, s) {
        this.panningSensibility !== 0 && (this._ctrlKey && this.camera._useCtrlForPanning || this._isPanClick) ? (this.camera.inertialPanningX += -o / this.panningSensibility,
        this.camera.inertialPanningY += s / this.panningSensibility) : (this.camera.inertialAlphaOffset -= o / this.angularSensibilityX,
        this.camera.inertialBetaOffset -= s / this.angularSensibilityY)
    }
    ,
    e.prototype.onDoubleTap = function(i) {
        this.camera.useInputToRestoreState && this.camera.restoreState()
    }
    ,
    e.prototype.onMultiTouch = function(i, o, s, c, d, _) {
        s === 0 && d === null || c === 0 && _ === null || (this.multiTouchPanAndZoom ? (this._computePinchZoom(s, c),
        this._computeMultiTouchPanning(d, _)) : this.multiTouchPanning && this.pinchZoom ? (this._twoFingerActivityCount++,
        this._isPinching || this._twoFingerActivityCount < 20 && Math.abs(Math.sqrt(c) - Math.sqrt(s)) > this.camera.pinchToPanMaxDistance ? (this._computePinchZoom(s, c),
        this._isPinching = !0) : this._computeMultiTouchPanning(d, _)) : this.multiTouchPanning ? this._computeMultiTouchPanning(d, _) : this.pinchZoom && this._computePinchZoom(s, c))
    }
    ,
    e.prototype.onButtonDown = function(i) {
        this._isPanClick = i.button === this.camera._panningMouseButton
    }
    ,
    e.prototype.onButtonUp = function(i) {
        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 a() {
        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 a.prototype.attachControl = function(e) {
        var i = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments),
        !this._onCanvasBlurObserver && (this._scene = this.camera.getScene(),
        this._engine = this._scene.getEngine(),
        this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function() {
            i._keys = []
        }),
        this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function(o) {
            var s = o.event;
            if (!s.metaKey) {
                if (o.type === KeyboardEventTypes.KEYDOWN) {
                    if (i._ctrlPressed = s.ctrlKey,
                    i._altPressed = s.altKey,
                    i.keysUp.indexOf(s.keyCode) !== -1 || i.keysDown.indexOf(s.keyCode) !== -1 || i.keysLeft.indexOf(s.keyCode) !== -1 || i.keysRight.indexOf(s.keyCode) !== -1 || i.keysReset.indexOf(s.keyCode) !== -1) {
                        var c = i._keys.indexOf(s.keyCode);
                        c === -1 && i._keys.push(s.keyCode),
                        s.preventDefault && (e || s.preventDefault())
                    }
                } else if (i.keysUp.indexOf(s.keyCode) !== -1 || i.keysDown.indexOf(s.keyCode) !== -1 || i.keysLeft.indexOf(s.keyCode) !== -1 || i.keysRight.indexOf(s.keyCode) !== -1 || i.keysReset.indexOf(s.keyCode) !== -1) {
                    var c = i._keys.indexOf(s.keyCode);
                    c >= 0 && i._keys.splice(c, 1),
                    s.preventDefault && (e || s.preventDefault())
                }
            }
        }))
    }
    ,
    a.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 = []
    }
    ,
    a.prototype.checkInputs = function() {
        if (this._onKeyboardObserver)
            for (var e = this.camera, i = 0; i < this._keys.length; i++) {
                var o = this._keys[i];
                this.keysLeft.indexOf(o) !== -1 ? this._ctrlPressed && this.camera._useCtrlForPanning ? e.inertialPanningX -= 1 / this.panningSensibility : e.inertialAlphaOffset -= this.angularSpeed : this.keysUp.indexOf(o) !== -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(o) !== -1 ? this._ctrlPressed && this.camera._useCtrlForPanning ? e.inertialPanningX += 1 / this.panningSensibility : e.inertialAlphaOffset += this.angularSpeed : this.keysDown.indexOf(o) !== -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(o) !== -1 && e.useInputToRestoreState && e.restoreState()
            }
    }
    ,
    a.prototype.getClassName = function() {
        return "ArcRotateCameraKeyboardMoveInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "keyboard"
    }
    ,
    __decorate([serialize()], a.prototype, "keysUp", void 0),
    __decorate([serialize()], a.prototype, "keysDown", void 0),
    __decorate([serialize()], a.prototype, "keysLeft", void 0),
    __decorate([serialize()], a.prototype, "keysRight", void 0),
    __decorate([serialize()], a.prototype, "keysReset", void 0),
    __decorate([serialize()], a.prototype, "panningSensibility", void 0),
    __decorate([serialize()], a.prototype, "zoomingSensibility", void 0),
    __decorate([serialize()], a.prototype, "useAltToZoom", void 0),
    __decorate([serialize()], a.prototype, "angularSpeed", void 0),
    a
}();
CameraInputTypes.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
var ffMultiplier = 40
  , ArcRotateCameraMouseWheelInput = function() {
    function a() {
        this.wheelPrecision = 3,
        this.zoomToMouseLocation = !1,
        this.wheelDeltaPercentage = 0,
        this.customComputeDeltaFromMouseWheel = null,
        this._inertialPanning = Vector3.Zero()
    }
    return a.prototype.computeDeltaFromMouseWheelLegacyEvent = function(e, i) {
        var o = 0
          , s = e * .01 * this.wheelDeltaPercentage * i;
        return e > 0 ? o = s / (1 + this.wheelDeltaPercentage) : o = s * (1 + this.wheelDeltaPercentage),
        o
    }
    ,
    a.prototype.attachControl = function(e) {
        var i = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments),
        this._wheel = function(o, s) {
            if (o.type === PointerEventTypes.POINTERWHEEL) {
                var c = o.event
                  , d = 0
                  , _ = c
                  , b = 0
                  , k = c.deltaMode === EventConstants.DOM_DELTA_LINE ? ffMultiplier : 1;
                if (c.deltaY !== void 0 ? b = -(c.deltaY * k) : c.wheelDeltaY !== void 0 ? b = -(c.wheelDeltaY * k) : b = _.wheelDelta,
                i.customComputeDeltaFromMouseWheel)
                    d = i.customComputeDeltaFromMouseWheel(b, i, c);
                else if (i.wheelDeltaPercentage) {
                    if (d = i.computeDeltaFromMouseWheelLegacyEvent(b, i.camera.radius),
                    d > 0) {
                        for (var j = i.camera.radius, $ = i.camera.inertialRadiusOffset + d, _e = 0; _e < 20 && Math.abs($) > .001; _e++)
                            j -= $,
                            $ *= i.camera.inertia;
                        j = Scalar.Clamp(j, 0, Number.MAX_VALUE),
                        d = i.computeDeltaFromMouseWheelLegacyEvent(b, j)
                    }
                } else
                    d = b / (i.wheelPrecision * 40);
                d && (i.zoomToMouseLocation && i._hitPlane ? i._zoomToMouse(d) : i.camera.inertialRadiusOffset += d),
                c.preventDefault && (e || c.preventDefault())
            }
        }
        ,
        this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, PointerEventTypes.POINTERWHEEL),
        this.zoomToMouseLocation && this._inertialPanning.setAll(0)
    }
    ,
    a.prototype.detachControl = function(e) {
        this._observer && (this.camera.getScene().onPointerObservable.remove(this._observer),
        this._observer = null,
        this._wheel = null)
    }
    ,
    a.prototype.checkInputs = function() {
        if (!!this.zoomToMouseLocation) {
            var e = this.camera
              , i = 0 + e.inertialAlphaOffset + e.inertialBetaOffset + e.inertialRadiusOffset;
            i && (this._updateHitPlane(),
            e.target.addInPlace(this._inertialPanning),
            this._inertialPanning.scaleInPlace(e.inertia),
            this._zeroIfClose(this._inertialPanning))
        }
    }
    ,
    a.prototype.getClassName = function() {
        return "ArcRotateCameraMouseWheelInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "mousewheel"
    }
    ,
    a.prototype._updateHitPlane = function() {
        var e = this.camera
          , i = e.target.subtract(e.position);
        this._hitPlane = Plane.FromPositionAndNormal(Vector3.Zero(), i)
    }
    ,
    a.prototype._getPosition = function() {
        var e, i = this.camera, o = i.getScene(), s = o.createPickingRay(o.pointerX, o.pointerY, Matrix.Identity(), i, !1), c = 0;
        return this._hitPlane && (c = (e = s.intersectsPlane(this._hitPlane)) !== null && e !== void 0 ? e : 0),
        s.origin.addInPlace(s.direction.scaleInPlace(c))
    }
    ,
    a.prototype._zoomToMouse = function(e) {
        var i, o, s = this.camera, c = 1 - s.inertia;
        if (s.lowerRadiusLimit) {
            var d = (i = s.lowerRadiusLimit) !== null && i !== void 0 ? i : 0;
            s.radius - (s.inertialRadiusOffset + e) / c < d && (e = (s.radius - d) * c - s.inertialRadiusOffset)
        }
        if (s.upperRadiusLimit) {
            var _ = (o = s.upperRadiusLimit) !== null && o !== void 0 ? o : 0;
            s.radius - (s.inertialRadiusOffset + e) / c > _ && (e = (s.radius - _) * c - s.inertialRadiusOffset)
        }
        var b = e / c
          , k = b / s.radius
          , j = this._getPosition()
          , $ = j.subtract(s.target)
          , _e = $.scale(k);
        _e.scaleInPlace(c),
        this._inertialPanning.addInPlace(_e),
        s.inertialRadiusOffset += e
    }
    ,
    a.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()], a.prototype, "wheelPrecision", void 0),
    __decorate([serialize()], a.prototype, "zoomToMouseLocation", void 0),
    __decorate([serialize()], a.prototype, "wheelDeltaPercentage", void 0),
    a
}();
CameraInputTypes.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
var ArcRotateCameraInputsManager = function(a) {
    __extends(e, a);
    function e(i) {
        return a.call(this, i) || 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(a, e) {
    return function() {
        return new ArcRotateCamera(a,0,0,1,Vector3.Zero(),e)
    }
});
var ArcRotateCamera = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b) {
        b === void 0 && (b = !0);
        var k = a.call(this, i, Vector3.Zero(), _, b) || this;
        return k.inertialAlphaOffset = 0,
        k.inertialBetaOffset = 0,
        k.inertialRadiusOffset = 0,
        k.lowerAlphaLimit = null,
        k.upperAlphaLimit = null,
        k.lowerBetaLimit = .01,
        k.upperBetaLimit = Math.PI - .01,
        k.lowerRadiusLimit = null,
        k.upperRadiusLimit = null,
        k.inertialPanningX = 0,
        k.inertialPanningY = 0,
        k.pinchToPanMaxDistance = 20,
        k.panningDistanceLimit = null,
        k.panningOriginTarget = Vector3.Zero(),
        k.panningInertia = .9,
        k.zoomOnFactor = 1,
        k.targetScreenOffset = Vector2.Zero(),
        k.allowUpsideDown = !0,
        k.useInputToRestoreState = !0,
        k._viewMatrix = new Matrix,
        k.panningAxis = new Vector3(1,1,0),
        k._transformedDirection = new Vector3,
        k.mapPanning = !1,
        k.onMeshTargetChangedObservable = new Observable,
        k.checkCollisions = !1,
        k.collisionRadius = new Vector3(.5,.5,.5),
        k._previousPosition = Vector3.Zero(),
        k._collisionVelocity = Vector3.Zero(),
        k._newPosition = Vector3.Zero(),
        k._computationVector = Vector3.Zero(),
        k._onCollisionPositionChange = function(j, $, _e) {
            _e === void 0 && (_e = null),
            _e ? (k.setPosition($),
            k.onCollide && k.onCollide(_e)) : k._previousPosition.copyFrom(k._position);
            var et = Math.cos(k.alpha)
              , tt = Math.sin(k.alpha)
              , rt = Math.cos(k.beta)
              , it = Math.sin(k.beta);
            it === 0 && (it = 1e-4);
            var nt = k._getTargetPosition();
            k._computationVector.copyFromFloats(k.radius * et * it, k.radius * rt, k.radius * tt * it),
            nt.addToRef(k._computationVector, k._newPosition),
            k._position.copyFrom(k._newPosition);
            var ot = k.upVector;
            k.allowUpsideDown && k.beta < 0 && (ot = ot.clone(),
            ot = ot.negate()),
            k._computeViewMatrix(k._position, nt, ot),
            k._viewMatrix.addAtIndex(12, k.targetScreenOffset.x),
            k._viewMatrix.addAtIndex(13, k.targetScreenOffset.y),
            k._collisionTriggered = !1
        }
        ,
        k._target = Vector3.Zero(),
        d && k.setTarget(d),
        k.alpha = o,
        k.beta = s,
        k.radius = c,
        k.getViewMatrix(),
        k.inputs = new ArcRotateCameraInputsManager(k),
        k.inputs.addKeyboard().addMouseWheel().addPointers(),
        k
    }
    return Object.defineProperty(e.prototype, "target", {
        get: function() {
            return this._target
        },
        set: function(i) {
            this.setTarget(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "targetHost", {
        get: function() {
            return this._targetHost
        },
        set: function(i) {
            i && this.setTarget(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getTarget = function() {
        return this.target
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(i) {
            this.setPosition(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "upVector", {
        get: function() {
            return this._upVector
        },
        set: function(i) {
            this._upToYMatrix || (this._YToUpMatrix = new Matrix,
            this._upToYMatrix = new Matrix,
            this._upVector = Vector3.Zero()),
            i.normalize(),
            this._upVector.copyFrom(i),
            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 i = this.inputs.attached.pointers;
            return i ? i.angularSensibilityX : 0
        },
        set: function(i) {
            var o = this.inputs.attached.pointers;
            o && (o.angularSensibilityX = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "angularSensibilityY", {
        get: function() {
            var i = this.inputs.attached.pointers;
            return i ? i.angularSensibilityY : 0
        },
        set: function(i) {
            var o = this.inputs.attached.pointers;
            o && (o.angularSensibilityY = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "pinchPrecision", {
        get: function() {
            var i = this.inputs.attached.pointers;
            return i ? i.pinchPrecision : 0
        },
        set: function(i) {
            var o = this.inputs.attached.pointers;
            o && (o.pinchPrecision = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "pinchDeltaPercentage", {
        get: function() {
            var i = this.inputs.attached.pointers;
            return i ? i.pinchDeltaPercentage : 0
        },
        set: function(i) {
            var o = this.inputs.attached.pointers;
            o && (o.pinchDeltaPercentage = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useNaturalPinchZoom", {
        get: function() {
            var i = this.inputs.attached.pointers;
            return i ? i.useNaturalPinchZoom : !1
        },
        set: function(i) {
            var o = this.inputs.attached.pointers;
            o && (o.useNaturalPinchZoom = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "panningSensibility", {
        get: function() {
            var i = this.inputs.attached.pointers;
            return i ? i.panningSensibility : 0
        },
        set: function(i) {
            var o = this.inputs.attached.pointers;
            o && (o.panningSensibility = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysUp", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysUp : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysUp = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysDown", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysDown : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysDown = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysLeft", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysLeft : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysLeft = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysRight", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysRight : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysRight = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelPrecision", {
        get: function() {
            var i = this.inputs.attached.mousewheel;
            return i ? i.wheelPrecision : 0
        },
        set: function(i) {
            var o = this.inputs.attached.mousewheel;
            o && (o.wheelPrecision = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "zoomToMouseLocation", {
        get: function() {
            var i = this.inputs.attached.mousewheel;
            return i ? i.zoomToMouseLocation : !1
        },
        set: function(i) {
            var o = this.inputs.attached.mousewheel;
            o && (o.zoomToMouseLocation = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelDeltaPercentage", {
        get: function() {
            var i = this.inputs.attached.mousewheel;
            return i ? i.wheelDeltaPercentage : 0
        },
        set: function(i) {
            var o = this.inputs.attached.mousewheel;
            o && (o.wheelDeltaPercentage = i)
        },
        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(i) {
            i !== this.useBouncingBehavior && (i ? (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(i) {
            i !== this.useFramingBehavior && (i ? (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(i) {
            i !== this.useAutoRotationBehavior && (i ? (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() {
        a.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(i) {
        i || a.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 i = this._targetHost.getAbsolutePosition();
            this._targetBoundingCenter ? i.addToRef(this._targetBoundingCenter, this._target) : this._target.copyFrom(i)
        }
        var o = this._getLockedTargetPosition();
        return o || 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(),
        a.prototype.storeState.call(this)
    }
    ,
    e.prototype._restoreStateValues = function() {
        return a.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 a.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(i, o, s, c) {
        var d = this;
        s === void 0 && (s = !0),
        c === void 0 && (c = 2),
        o = Tools.BackCompatCameraNoPreventDefault(arguments),
        this._useCtrlForPanning = s,
        this._panningMouseButton = c,
        typeof arguments[0] == "boolean" && (arguments.length > 1 && (this._useCtrlForPanning = arguments[1]),
        arguments.length > 2 && (this._panningMouseButton = arguments[2])),
        this.inputs.attachElement(o),
        this._reset = function() {
            d.inertialAlphaOffset = 0,
            d.inertialBetaOffset = 0,
            d.inertialRadiusOffset = 0,
            d.inertialPanningX = 0,
            d.inertialPanningY = 0
        }
    }
    ,
    e.prototype.detachControl = function(i) {
        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 i = this.inertialAlphaOffset;
                this.beta <= 0 && (i *= -1),
                this.getScene().useRightHandedSystem && (i *= -1),
                this.parent && this.parent._getWorldMatrixDeterminant() < 0 && (i *= -1),
                this.alpha += i,
                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 o = new Vector3(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);
                if (this._viewMatrix.invertToRef(this._cameraTransformMatrix),
                o.multiplyInPlace(this.panningAxis),
                Vector3.TransformNormalToRef(o, this._cameraTransformMatrix, this._transformedDirection),
                this.mapPanning && (this._transformedDirection.y = 0),
                !this._targetHost)
                    if (this.panningDistanceLimit) {
                        this._transformedDirection.addInPlace(this._target);
                        var s = Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
                        s <= 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(),
            a.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 i = 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 o = Math.round((i - this.alpha) / (2 * Math.PI));
        this.alpha += o * 2 * Math.PI,
        this.beta = Math.acos(this._computationVector.y / this.radius),
        this._checkLimits()
    }
    ,
    e.prototype.setPosition = function(i) {
        this._position.equals(i) || (this._position.copyFrom(i),
        this.rebuildAnglesAndRadius())
    }
    ,
    e.prototype.setTarget = function(i, o, s) {
        if (o === void 0 && (o = !1),
        s === void 0 && (s = !1),
        i.getBoundingInfo)
            o ? this._targetBoundingCenter = i.getBoundingInfo().boundingBox.centerWorld.clone() : this._targetBoundingCenter = null,
            i.computeWorldMatrix(),
            this._targetHost = i,
            this._target = this._getTargetPosition(),
            this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
        else {
            var c = i
              , d = this._getTargetPosition();
            if (d && !s && d.equals(c))
                return;
            this._targetHost = null,
            this._target = c,
            this._targetBoundingCenter = null,
            this.onMeshTargetChangedObservable.notifyObservers(null)
        }
        this.rebuildAnglesAndRadius()
    }
    ,
    e.prototype._getViewMatrix = function() {
        var i = Math.cos(this.alpha)
          , o = Math.sin(this.alpha)
          , s = Math.cos(this.beta)
          , c = Math.sin(this.beta);
        c === 0 && (c = 1e-4),
        this.radius === 0 && (this.radius = 1e-4);
        var d = this._getTargetPosition();
        if (this._computationVector.copyFromFloats(this.radius * i * c, this.radius * s, this.radius * o * c),
        (this._upVector.x !== 0 || this._upVector.y !== 1 || this._upVector.z !== 0) && Vector3.TransformCoordinatesToRef(this._computationVector, this._YToUpMatrix, this._computationVector),
        d.addToRef(this._computationVector, this._newPosition),
        this.getScene().collisionsEnabled && this.checkCollisions) {
            var _ = this.getScene().collisionCoordinator;
            this._collider || (this._collider = _.createCollider()),
            this._collider._radius = this.collisionRadius,
            this._newPosition.subtractToRef(this._position, this._collisionVelocity),
            this._collisionTriggered = !0,
            _.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId)
        } else {
            this._position.copyFrom(this._newPosition);
            var b = this.upVector;
            this.allowUpsideDown && c < 0 && (b = b.negate()),
            this._computeViewMatrix(this._position, d, b),
            this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x),
            this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y)
        }
        return this._currentTarget = d,
        this._viewMatrix
    }
    ,
    e.prototype.zoomOn = function(i, o) {
        o === void 0 && (o = !1),
        i = i || this.getScene().meshes;
        var s = Mesh.MinMax(i)
          , c = Vector3.Distance(s.min, s.max);
        this.radius = c * this.zoomOnFactor,
        this.focusOn({
            min: s.min,
            max: s.max,
            distance: c
        }, o)
    }
    ,
    e.prototype.focusOn = function(i, o) {
        o === void 0 && (o = !1);
        var s, c;
        if (i.min === void 0) {
            var d = i || this.getScene().meshes;
            s = Mesh.MinMax(d),
            c = Vector3.Distance(s.min, s.max)
        } else {
            var _ = i;
            s = _,
            c = _.distance
        }
        this._target = Mesh.Center(s),
        o || (this.maxZ = c * 2)
    }
    ,
    e.prototype.createRigCamera = function(i, o) {
        var s = 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:
            s = this._cameraRigParams.stereoHalfAngle * (o === 0 ? 1 : -1);
            break;
        case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
            s = this._cameraRigParams.stereoHalfAngle * (o === 0 ? -1 : 1);
            break
        }
        var c = new e(i,this.alpha + s,this.beta,this.radius,this._target,this.getScene());
        return c._cameraRigParams = {},
        c.isRigCamera = !0,
        c.rigParent = this,
        c.upVector = this.upVector,
        c
    }
    ,
    e.prototype._updateRigCameras = function() {
        var i = this._rigCameras[0]
          , o = this._rigCameras[1];
        switch (i.beta = o.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:
            i.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle,
            o.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
            break;
        case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
            i.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle,
            o.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
            break
        }
        a.prototype._updateRigCameras.call(this)
    }
    ,
    e.prototype.dispose = function() {
        this.inputs.clear(),
        a.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 a() {
        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 a.prototype.attachControl = function(e) {
        var i = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments),
        !this._onCanvasBlurObserver && (this._scene = this.camera.getScene(),
        this._engine = this._scene.getEngine(),
        this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function() {
            i._keys = []
        }),
        this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function(o) {
            var s = o.event;
            if (!s.metaKey) {
                if (o.type === KeyboardEventTypes.KEYDOWN) {
                    if (i.keysUp.indexOf(s.keyCode) !== -1 || i.keysDown.indexOf(s.keyCode) !== -1 || i.keysLeft.indexOf(s.keyCode) !== -1 || i.keysRight.indexOf(s.keyCode) !== -1 || i.keysUpward.indexOf(s.keyCode) !== -1 || i.keysDownward.indexOf(s.keyCode) !== -1 || i.keysRotateLeft.indexOf(s.keyCode) !== -1 || i.keysRotateRight.indexOf(s.keyCode) !== -1) {
                        var c = i._keys.indexOf(s.keyCode);
                        c === -1 && i._keys.push(s.keyCode),
                        e || s.preventDefault()
                    }
                } else if (i.keysUp.indexOf(s.keyCode) !== -1 || i.keysDown.indexOf(s.keyCode) !== -1 || i.keysLeft.indexOf(s.keyCode) !== -1 || i.keysRight.indexOf(s.keyCode) !== -1 || i.keysUpward.indexOf(s.keyCode) !== -1 || i.keysDownward.indexOf(s.keyCode) !== -1 || i.keysRotateLeft.indexOf(s.keyCode) !== -1 || i.keysRotateRight.indexOf(s.keyCode) !== -1) {
                    var c = i._keys.indexOf(s.keyCode);
                    c >= 0 && i._keys.splice(c, 1),
                    e || s.preventDefault()
                }
            }
        }))
    }
    ,
    a.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 = []
    }
    ,
    a.prototype.checkInputs = function() {
        if (this._onKeyboardObserver)
            for (var e = this.camera, i = 0; i < this._keys.length; i++) {
                var o = this._keys[i]
                  , s = e._computeLocalCameraSpeed();
                this.keysLeft.indexOf(o) !== -1 ? e._localDirection.copyFromFloats(-s, 0, 0) : this.keysUp.indexOf(o) !== -1 ? e._localDirection.copyFromFloats(0, 0, s) : this.keysRight.indexOf(o) !== -1 ? e._localDirection.copyFromFloats(s, 0, 0) : this.keysDown.indexOf(o) !== -1 ? e._localDirection.copyFromFloats(0, 0, -s) : this.keysUpward.indexOf(o) !== -1 ? e._localDirection.copyFromFloats(0, s, 0) : this.keysDownward.indexOf(o) !== -1 ? e._localDirection.copyFromFloats(0, -s, 0) : this.keysRotateLeft.indexOf(o) !== -1 ? (e._localDirection.copyFromFloats(0, 0, 0),
                e.cameraRotation.y -= this._getLocalRotation()) : this.keysRotateRight.indexOf(o) !== -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)
            }
    }
    ,
    a.prototype.getClassName = function() {
        return "FreeCameraKeyboardMoveInput"
    }
    ,
    a.prototype._onLostFocus = function() {
        this._keys = []
    }
    ,
    a.prototype.getSimpleName = function() {
        return "keyboard"
    }
    ,
    a.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()], a.prototype, "keysUp", void 0),
    __decorate([serialize()], a.prototype, "keysUpward", void 0),
    __decorate([serialize()], a.prototype, "keysDown", void 0),
    __decorate([serialize()], a.prototype, "keysDownward", void 0),
    __decorate([serialize()], a.prototype, "keysLeft", void 0),
    __decorate([serialize()], a.prototype, "keysRight", void 0),
    __decorate([serialize()], a.prototype, "rotationSpeed", void 0),
    __decorate([serialize()], a.prototype, "keysRotateLeft", void 0),
    __decorate([serialize()], a.prototype, "keysRotateRight", void 0),
    a
}();
CameraInputTypes.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
var FreeCameraMouseInput = function() {
    function a(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 a.prototype.attachControl = function(e) {
        var i = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments);
        var o = this.camera.getEngine()
          , s = o.getInputElement();
        this._pointerInput || (this._pointerInput = function(c) {
            var d = c.event
              , _ = d.pointerType === "touch";
            if (!o.isInVRExclusivePointerMode && !(!i.touchEnabled && _) && !(c.type !== PointerEventTypes.POINTERMOVE && i.buttons.indexOf(d.button) === -1)) {
                var b = d.srcElement || d.target;
                if (c.type === PointerEventTypes.POINTERDOWN && (i._currentActiveButton === -1 || _)) {
                    try {
                        b == null || b.setPointerCapture(d.pointerId)
                    } catch {}
                    i._currentActiveButton === -1 && (i._currentActiveButton = d.button),
                    i.previousPosition = {
                        x: d.clientX,
                        y: d.clientY
                    },
                    e || (d.preventDefault(),
                    s && s.focus()),
                    o.isPointerLock && i._onMouseMove && i._onMouseMove(c.event)
                } else if (c.type === PointerEventTypes.POINTERUP && (i._currentActiveButton === d.button || _)) {
                    try {
                        b == null || b.releasePointerCapture(d.pointerId)
                    } catch {}
                    i._currentActiveButton = -1,
                    i.previousPosition = null,
                    e || d.preventDefault()
                } else if (c.type === PointerEventTypes.POINTERMOVE) {
                    if (o.isPointerLock && i._onMouseMove)
                        i._onMouseMove(c.event);
                    else if (i.previousPosition) {
                        var k = d.clientX - i.previousPosition.x
                          , j = d.clientY - i.previousPosition.y;
                        i.camera.getScene().useRightHandedSystem && (k *= -1),
                        i.camera.parent && i.camera.parent._getWorldMatrixDeterminant() < 0 && (k *= -1),
                        i._allowCameraRotation && (i.camera.cameraRotation.y += k / i.angularSensibility,
                        i.camera.cameraRotation.x += j / i.angularSensibility),
                        i.onPointerMovedObservable.notifyObservers({
                            offsetX: k,
                            offsetY: j
                        }),
                        i.previousPosition = {
                            x: d.clientX,
                            y: d.clientY
                        },
                        e || d.preventDefault()
                    }
                }
            }
        }
        ),
        this._onMouseMove = function(c) {
            if (!!o.isPointerLock && !o.isInVRExclusivePointerMode) {
                var d = c.movementX || c.mozMovementX || c.webkitMovementX || c.msMovementX || 0;
                i.camera.getScene().useRightHandedSystem && (d *= -1),
                i.camera.parent && i.camera.parent._getWorldMatrixDeterminant() < 0 && (d *= -1),
                i.camera.cameraRotation.y += d / i.angularSensibility;
                var _ = c.movementY || c.mozMovementY || c.webkitMovementY || c.msMovementY || 0;
                i.camera.cameraRotation.x += _ / i.angularSensibility,
                i.previousPosition = null,
                e || c.preventDefault()
            }
        }
        ,
        this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE),
        s && s.addEventListener("contextmenu", this.onContextMenu.bind(this), !1)
    }
    ,
    a.prototype.onContextMenu = function(e) {
        e.preventDefault()
    }
    ,
    a.prototype.detachControl = function(e) {
        if (this._observer) {
            if (this.camera.getScene().onPointerObservable.remove(this._observer),
            this.onContextMenu) {
                var i = this.camera.getEngine()
                  , o = i.getInputElement();
                o && o.removeEventListener("contextmenu", this.onContextMenu)
            }
            this.onPointerMovedObservable && this.onPointerMovedObservable.clear(),
            this._observer = null,
            this._onMouseMove = null,
            this.previousPosition = null
        }
    }
    ,
    a.prototype.getClassName = function() {
        return "FreeCameraMouseInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "mouse"
    }
    ,
    __decorate([serialize()], a.prototype, "buttons", void 0),
    __decorate([serialize()], a.prototype, "angularSensibility", void 0),
    a
}();
CameraInputTypes.FreeCameraMouseInput = FreeCameraMouseInput;
var BaseCameraMouseWheelInput = function() {
    function a() {
        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 a.prototype.attachControl = function(e) {
        var i = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments),
        this._wheel = function(o) {
            if (o.type === PointerEventTypes.POINTERWHEEL) {
                var s = o.event
                  , c = s.deltaMode === EventConstants.DOM_DELTA_LINE ? i._ffMultiplier : 1;
                s.deltaY !== void 0 ? (i._wheelDeltaX += i.wheelPrecisionX * c * s.deltaX / i._normalize,
                i._wheelDeltaY -= i.wheelPrecisionY * c * s.deltaY / i._normalize,
                i._wheelDeltaZ += i.wheelPrecisionZ * c * s.deltaZ / i._normalize) : s.wheelDeltaY !== void 0 ? (i._wheelDeltaX += i.wheelPrecisionX * c * s.wheelDeltaX / i._normalize,
                i._wheelDeltaY -= i.wheelPrecisionY * c * s.wheelDeltaY / i._normalize,
                i._wheelDeltaZ += i.wheelPrecisionZ * c * s.wheelDeltaZ / i._normalize) : s.wheelDelta && (i._wheelDeltaY -= i.wheelPrecisionY * s.wheelDelta / i._normalize),
                s.preventDefault && (e || s.preventDefault())
            }
        }
        ,
        this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, PointerEventTypes.POINTERWHEEL)
    }
    ,
    a.prototype.detachControl = function(e) {
        this._observer && (this.camera.getScene().onPointerObservable.remove(this._observer),
        this._observer = null,
        this._wheel = null),
        this.onChangedObservable && this.onChangedObservable.clear()
    }
    ,
    a.prototype.checkInputs = function() {
        this.onChangedObservable.notifyObservers({
            wheelDeltaX: this._wheelDeltaX,
            wheelDeltaY: this._wheelDeltaY,
            wheelDeltaZ: this._wheelDeltaZ
        }),
        this._wheelDeltaX = 0,
        this._wheelDeltaY = 0,
        this._wheelDeltaZ = 0
    }
    ,
    a.prototype.getClassName = function() {
        return "BaseCameraMouseWheelInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "mousewheel"
    }
    ,
    __decorate([serialize()], a.prototype, "wheelPrecisionX", void 0),
    __decorate([serialize()], a.prototype, "wheelPrecisionY", void 0),
    __decorate([serialize()], a.prototype, "wheelPrecisionZ", void 0),
    a
}(), _CameraProperty;
(function(a) {
    a[a.MoveRelative = 0] = "MoveRelative",
    a[a.RotateRelative = 1] = "RotateRelative",
    a[a.MoveScene = 2] = "MoveScene"
}
)(_CameraProperty || (_CameraProperty = {}));
var FreeCameraMouseWheelInput = function(a) {
    __extends(e, a);
    function e() {
        var i = a !== null && a.apply(this, arguments) || this;
        return i._moveRelative = Vector3.Zero(),
        i._rotateRelative = Vector3.Zero(),
        i._moveScene = Vector3.Zero(),
        i._wheelXAction = _CameraProperty.MoveRelative,
        i._wheelXActionCoordinate = Coordinate.X,
        i._wheelYAction = _CameraProperty.MoveRelative,
        i._wheelYActionCoordinate = Coordinate.Z,
        i._wheelZAction = null,
        i._wheelZActionCoordinate = null,
        i
    }
    return e.prototype.getClassName = function() {
        return "FreeCameraMouseWheelInput"
    }
    ,
    Object.defineProperty(e.prototype, "wheelXMoveRelative", {
        get: function() {
            return this._wheelXAction !== _CameraProperty.MoveRelative ? null : this._wheelXActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelXAction !== _CameraProperty.MoveRelative || (this._wheelXAction = _CameraProperty.MoveRelative,
            this._wheelXActionCoordinate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelYMoveRelative", {
        get: function() {
            return this._wheelYAction !== _CameraProperty.MoveRelative ? null : this._wheelYActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelYAction !== _CameraProperty.MoveRelative || (this._wheelYAction = _CameraProperty.MoveRelative,
            this._wheelYActionCoordinate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelZMoveRelative", {
        get: function() {
            return this._wheelZAction !== _CameraProperty.MoveRelative ? null : this._wheelZActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelZAction !== _CameraProperty.MoveRelative || (this._wheelZAction = _CameraProperty.MoveRelative,
            this._wheelZActionCoordinate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelXRotateRelative", {
        get: function() {
            return this._wheelXAction !== _CameraProperty.RotateRelative ? null : this._wheelXActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelXAction !== _CameraProperty.RotateRelative || (this._wheelXAction = _CameraProperty.RotateRelative,
            this._wheelXActionCoordinate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelYRotateRelative", {
        get: function() {
            return this._wheelYAction !== _CameraProperty.RotateRelative ? null : this._wheelYActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelYAction !== _CameraProperty.RotateRelative || (this._wheelYAction = _CameraProperty.RotateRelative,
            this._wheelYActionCoordinate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelZRotateRelative", {
        get: function() {
            return this._wheelZAction !== _CameraProperty.RotateRelative ? null : this._wheelZActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelZAction !== _CameraProperty.RotateRelative || (this._wheelZAction = _CameraProperty.RotateRelative,
            this._wheelZActionCoordinate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelXMoveScene", {
        get: function() {
            return this._wheelXAction !== _CameraProperty.MoveScene ? null : this._wheelXActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelXAction !== _CameraProperty.MoveScene || (this._wheelXAction = _CameraProperty.MoveScene,
            this._wheelXActionCoordinate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelYMoveScene", {
        get: function() {
            return this._wheelYAction !== _CameraProperty.MoveScene ? null : this._wheelYActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelYAction !== _CameraProperty.MoveScene || (this._wheelYAction = _CameraProperty.MoveScene,
            this._wheelYActionCoordinate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelZMoveScene", {
        get: function() {
            return this._wheelZAction !== _CameraProperty.MoveScene ? null : this._wheelZActionCoordinate
        },
        set: function(i) {
            i === null && this._wheelZAction !== _CameraProperty.MoveScene || (this._wheelZAction = _CameraProperty.MoveScene,
            this._wheelZActionCoordinate = i)
        },
        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 i = Matrix.Zero();
            this.camera.getViewMatrix().invertToRef(i);
            var o = Vector3.Zero();
            Vector3.TransformNormalToRef(this._moveRelative, i, o),
            this.camera.cameraRotation.x += this._rotateRelative.x / 200,
            this.camera.cameraRotation.y += this._rotateRelative.y / 200,
            this.camera.cameraDirection.addInPlace(o),
            this.camera.cameraDirection.addInPlace(this._moveScene),
            a.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(i, o, s) {
        if (i !== 0 && !(o === null || s === null)) {
            var c = null;
            switch (o) {
            case _CameraProperty.MoveRelative:
                c = this._moveRelative;
                break;
            case _CameraProperty.RotateRelative:
                c = this._rotateRelative;
                break;
            case _CameraProperty.MoveScene:
                c = this._moveScene;
                break
            }
            switch (s) {
            case Coordinate.X:
                c.set(i, 0, 0);
                break;
            case Coordinate.Y:
                c.set(0, i, 0);
                break;
            case Coordinate.Z:
                c.set(0, 0, i);
                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 a(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 a.prototype.attachControl = function(e) {
        var i = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments);
        var o = null;
        if (this._pointerInput === void 0 && (this._onLostFocus = function() {
            i._offsetX = null,
            i._offsetY = null
        }
        ,
        this._pointerInput = function(d) {
            var _ = d.event
              , b = !i.camera.getEngine().hostInformation.isMobile && _ instanceof MouseEvent;
            if (!(!i.allowMouse && (_.pointerType === "mouse" || b))) {
                if (d.type === PointerEventTypes.POINTERDOWN) {
                    if (e || _.preventDefault(),
                    i._pointerPressed.push(_.pointerId),
                    i._pointerPressed.length !== 1)
                        return;
                    o = {
                        x: _.clientX,
                        y: _.clientY
                    }
                } else if (d.type === PointerEventTypes.POINTERUP) {
                    e || _.preventDefault();
                    var k = i._pointerPressed.indexOf(_.pointerId);
                    if (k === -1 || (i._pointerPressed.splice(k, 1),
                    k != 0))
                        return;
                    o = null,
                    i._offsetX = null,
                    i._offsetY = null
                } else if (d.type === PointerEventTypes.POINTERMOVE) {
                    if (e || _.preventDefault(),
                    !o)
                        return;
                    var k = i._pointerPressed.indexOf(_.pointerId);
                    if (k != 0)
                        return;
                    i._offsetX = _.clientX - o.x,
                    i._offsetY = -(_.clientY - o.y)
                }
            }
        }
        ),
        this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE),
        this._onLostFocus) {
            var s = this.camera.getEngine()
              , c = s.getInputElement();
            c && c.addEventListener("blur", this._onLostFocus)
        }
    }
    ,
    a.prototype.detachControl = function(e) {
        if (this._pointerInput) {
            if (this._observer && (this.camera.getScene().onPointerObservable.remove(this._observer),
            this._observer = null),
            this._onLostFocus) {
                var i = this.camera.getEngine()
                  , o = i.getInputElement();
                o && o.removeEventListener("blur", this._onLostFocus),
                this._onLostFocus = null
            }
            this._pointerPressed = [],
            this._offsetX = null,
            this._offsetY = null
        }
    }
    ,
    a.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 i = this.singleFingerRotate && this._pointerPressed.length === 1 || !this.singleFingerRotate && this._pointerPressed.length > 1;
            if (i)
                e.cameraRotation.x = -this._offsetY / this.touchAngularSensibility;
            else {
                var o = e._computeLocalCameraSpeed()
                  , s = new Vector3(0,0,o * this._offsetY / this.touchMoveSensibility);
                Matrix.RotationYawPitchRollToRef(e.rotation.y, e.rotation.x, 0, e._cameraRotationMatrix),
                e.cameraDirection.addInPlace(Vector3.TransformCoordinates(s, e._cameraRotationMatrix))
            }
        }
    }
    ,
    a.prototype.getClassName = function() {
        return "FreeCameraTouchInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "touch"
    }
    ,
    __decorate([serialize()], a.prototype, "touchAngularSensibility", void 0),
    __decorate([serialize()], a.prototype, "touchMoveSensibility", void 0),
    a
}();
CameraInputTypes.FreeCameraTouchInput = FreeCameraTouchInput;
var FreeCameraInputsManager = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i) || this;
        return o._mouseInput = null,
        o._mouseWheelInput = null,
        o
    }
    return e.prototype.addKeyboard = function() {
        return this.add(new FreeCameraKeyboardMoveInput),
        this
    }
    ,
    e.prototype.addMouse = function(i) {
        return i === void 0 && (i = !0),
        this._mouseInput || (this._mouseInput = new FreeCameraMouseInput(i),
        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() {
        a.prototype.clear.call(this),
        this._mouseInput = null
    }
    ,
    e
}(CameraInputsManager)
  , FreeCamera = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        c === void 0 && (c = !0);
        var d = a.call(this, i, o, s, c) || this;
        return d.ellipsoid = new Vector3(.5,1,.5),
        d.ellipsoidOffset = new Vector3(0,0,0),
        d.checkCollisions = !1,
        d.applyGravity = !1,
        d._needMoveForGravity = !1,
        d._oldPosition = Vector3.Zero(),
        d._diffPosition = Vector3.Zero(),
        d._newPosition = Vector3.Zero(),
        d._collisionMask = -1,
        d._onCollisionPositionChange = function(_, b, k) {
            k === void 0 && (k = null);
            var j = function($) {
                d._newPosition.copyFrom($),
                d._newPosition.subtractToRef(d._oldPosition, d._diffPosition),
                d._diffPosition.length() > Engine.CollisionsEpsilon && (d.position.addInPlace(d._diffPosition),
                d.onCollide && k && d.onCollide(k))
            };
            j(b)
        }
        ,
        d.inputs = new FreeCameraInputsManager(d),
        d.inputs.addKeyboard().addMouse(),
        d
    }
    return Object.defineProperty(e.prototype, "angularSensibility", {
        get: function() {
            var i = this.inputs.attached.mouse;
            return i ? i.angularSensibility : 0
        },
        set: function(i) {
            var o = this.inputs.attached.mouse;
            o && (o.angularSensibility = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysUp", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysUp : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysUp = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysUpward", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysUpward : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysUpward = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysDown", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysDown : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysDown = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysDownward", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysDownward : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysDownward = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysLeft", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysLeft : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysLeft = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysRight", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysRight : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysRight = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysRotateLeft", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysRotateLeft : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysRotateLeft = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysRotateRight", {
        get: function() {
            var i = this.inputs.attached.keyboard;
            return i ? i.keysRotateRight : []
        },
        set: function(i) {
            var o = this.inputs.attached.keyboard;
            o && (o.keysRotateRight = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.attachControl = function(i, o) {
        o = Tools.BackCompatCameraNoPreventDefault(arguments),
        this.inputs.attachElement(o)
    }
    ,
    e.prototype.detachControl = function(i) {
        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(i) {
            this._collisionMask = isNaN(i) ? -1 : i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._collideWithWorld = function(i) {
        var o;
        this.parent ? o = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix()) : o = this.position,
        o.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition),
        this._oldPosition.addInPlace(this.ellipsoidOffset);
        var s = this.getScene().collisionCoordinator;
        this._collider || (this._collider = s.createCollider()),
        this._collider._radius = this.ellipsoid,
        this._collider.collisionMask = this._collisionMask;
        var c = i;
        this.applyGravity && (c = i.add(this.getScene().gravity)),
        s.getNewPosition(this._oldPosition, c, 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(),
        a.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) : a.prototype._updatePosition.call(this)
    }
    ,
    e.prototype.dispose = function() {
        this.inputs.clear(),
        a.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(a) {
    __extends(e, a);
    function e() {
        var i = a !== null && a.apply(this, arguments) || this;
        return i._needProjectionMatrixCompute = !0,
        i
    }
    return e.prototype._setPosition = function(i) {
        this._position = i
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(i) {
            this._setPosition(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._setDirection = function(i) {
        this._direction = i
    }
    ,
    Object.defineProperty(e.prototype, "direction", {
        get: function() {
            return this._direction
        },
        set: function(i) {
            this._setDirection(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowMinZ", {
        get: function() {
            return this._shadowMinZ
        },
        set: function(i) {
            this._shadowMinZ = i,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowMaxZ", {
        get: function() {
            return this._shadowMaxZ
        },
        set: function(i) {
            this._shadowMaxZ = i,
            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(i) {
        return this.transformedDirection ? this.transformedDirection : this.direction
    }
    ,
    e.prototype.getAbsolutePosition = function() {
        return this.transformedPosition ? this.transformedPosition : this.position
    }
    ,
    e.prototype.setDirectionToTarget = function(i) {
        return this.direction = Vector3.Normalize(i.subtract(this.position)),
        this.direction
    }
    ,
    e.prototype.getRotation = function() {
        this.direction.normalize();
        var i = Vector3.Cross(this.direction, Axis.Y)
          , o = Vector3.Cross(i, this.direction);
        return Vector3.RotationFromAxis(i, o, 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() {
        a.prototype._initCache.call(this),
        this._cache.position = Vector3.Zero()
    }
    ,
    e.prototype._isSynchronized = function() {
        return !!this._cache.position.equals(this.position)
    }
    ,
    e.prototype.computeWorldMatrix = function(i) {
        return !i && 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(i) {
        return this.shadowMinZ !== void 0 ? this.shadowMinZ : i.minZ
    }
    ,
    e.prototype.getDepthMaxZ = function(i) {
        return this.shadowMaxZ !== void 0 ? this.shadowMaxZ : i.maxZ
    }
    ,
    e.prototype.setShadowProjectionMatrix = function(i, o, s) {
        return this.customProjectionMatrixBuilder ? this.customProjectionMatrixBuilder(o, s, i) : this._setDefaultShadowProjectionMatrix(i, o, s),
        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(a, e) {
    return function() {
        return new DirectionalLight(a,Vector3.Zero(),e)
    }
});
var DirectionalLight = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, s) || this;
        return c._shadowFrustumSize = 0,
        c._shadowOrthoScale = .1,
        c.autoUpdateExtends = !0,
        c.autoCalcShadowZBounds = !1,
        c._orthoLeft = Number.MAX_VALUE,
        c._orthoRight = Number.MIN_VALUE,
        c._orthoTop = Number.MIN_VALUE,
        c._orthoBottom = Number.MAX_VALUE,
        c.position = o.scale(-1),
        c.direction = o,
        c
    }
    return Object.defineProperty(e.prototype, "shadowFrustumSize", {
        get: function() {
            return this._shadowFrustumSize
        },
        set: function(i) {
            this._shadowFrustumSize = i,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowOrthoScale", {
        get: function() {
            return this._shadowOrthoScale
        },
        set: function(i) {
            this._shadowOrthoScale = i,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "orthoLeft", {
        get: function() {
            return this._orthoLeft
        },
        set: function(i) {
            this._orthoLeft = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "orthoRight", {
        get: function() {
            return this._orthoRight
        },
        set: function(i) {
            this._orthoRight = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "orthoTop", {
        get: function() {
            return this._orthoTop
        },
        set: function(i) {
            this._orthoTop = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "orthoBottom", {
        get: function() {
            return this._orthoBottom
        },
        set: function(i) {
            this._orthoBottom = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "DirectionalLight"
    }
    ,
    e.prototype.getTypeID = function() {
        return Light.LIGHTTYPEID_DIRECTIONALLIGHT
    }
    ,
    e.prototype._setDefaultShadowProjectionMatrix = function(i, o, s) {
        this.shadowFrustumSize > 0 ? this._setDefaultFixedFrustumShadowProjectionMatrix(i) : this._setDefaultAutoExtendShadowProjectionMatrix(i, o, s)
    }
    ,
    e.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function(i) {
        var o = this.getScene().activeCamera;
        !o || Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== void 0 ? this.shadowMinZ : o.minZ, this.shadowMaxZ !== void 0 ? this.shadowMaxZ : o.maxZ, i, this.getScene().getEngine().isNDCHalfZRange)
    }
    ,
    e.prototype._setDefaultAutoExtendShadowProjectionMatrix = function(i, o, s) {
        var c = this.getScene().activeCamera;
        if (!!c) {
            if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
                var d = Vector3.Zero();
                this._orthoLeft = Number.MAX_VALUE,
                this._orthoRight = Number.MIN_VALUE,
                this._orthoTop = Number.MIN_VALUE,
                this._orthoBottom = Number.MAX_VALUE;
                for (var _ = Number.MAX_VALUE, b = Number.MIN_VALUE, k = 0; k < s.length; k++) {
                    var j = s[k];
                    if (!!j)
                        for (var $ = j.getBoundingInfo(), _e = $.boundingBox, et = 0; et < _e.vectorsWorld.length; et++)
                            Vector3.TransformCoordinatesToRef(_e.vectorsWorld[et], o, d),
                            d.x < this._orthoLeft && (this._orthoLeft = d.x),
                            d.y < this._orthoBottom && (this._orthoBottom = d.y),
                            d.x > this._orthoRight && (this._orthoRight = d.x),
                            d.y > this._orthoTop && (this._orthoTop = d.y),
                            this.autoCalcShadowZBounds && (d.z < _ && (_ = d.z),
                            d.z > b && (b = d.z))
                }
                this.autoCalcShadowZBounds && (this._shadowMinZ = _,
                this._shadowMaxZ = b)
            }
            var tt = this._orthoRight - this._orthoLeft
              , rt = this._orthoTop - this._orthoBottom
              , it = this.shadowMinZ !== void 0 ? this.shadowMinZ : c.minZ
              , nt = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : c.maxZ
              , ot = this.getScene().getEngine().useReverseDepthBuffer;
            Matrix.OrthoOffCenterLHToRef(this._orthoLeft - tt * this.shadowOrthoScale, this._orthoRight + tt * this.shadowOrthoScale, this._orthoBottom - rt * this.shadowOrthoScale, this._orthoTop + rt * this.shadowOrthoScale, ot ? nt : it, ot ? it : nt, i, 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(i, o) {
        return this.computeTransformedInformation() ? (this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, o),
        this) : (this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, o),
        this)
    }
    ,
    e.prototype.transferToNodeMaterialEffect = function(i, o) {
        return this.computeTransformedInformation() ? (i.setFloat3(o, this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z),
        this) : (i.setFloat3(o, this.direction.x, this.direction.y, this.direction.z),
        this)
    }
    ,
    e.prototype.getDepthMinZ = function(i) {
        var o = this._scene.getEngine();
        return !o.useReverseDepthBuffer && o.isNDCHalfZRange ? 0 : 1
    }
    ,
    e.prototype.getDepthMaxZ = function(i) {
        var o = this._scene.getEngine();
        return o.useReverseDepthBuffer && o.isNDCHalfZRange ? 0 : 1
    }
    ,
    e.prototype.prepareLightSpecificDefines = function(i, o) {
        i["DIRLIGHT" + o] = !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(a, e) {
    return function() {
        return new HemisphericLight(a,Vector3.Zero(),e)
    }
});
var HemisphericLight = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, s) || this;
        return c.groundColor = new Color3(0,0,0),
        c.direction = o || Vector3.Up(),
        c
    }
    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(i) {
        return this.direction = Vector3.Normalize(i.subtract(Vector3.Zero())),
        this.direction
    }
    ,
    e.prototype.getShadowGenerator = function() {
        return null
    }
    ,
    e.prototype.transferToEffect = function(i, o) {
        var s = Vector3.Normalize(this.direction);
        return this._uniformBuffer.updateFloat4("vLightData", s.x, s.y, s.z, 0, o),
        this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), o),
        this
    }
    ,
    e.prototype.transferToNodeMaterialEffect = function(i, o) {
        var s = Vector3.Normalize(this.direction);
        return i.setFloat3(o, s.x, s.y, s.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(i, o) {
        i["HEMILIGHT" + o] = !0
    }
    ,
    __decorate([serializeAsColor3()], e.prototype, "groundColor", void 0),
    __decorate([serializeAsVector3()], e.prototype, "direction", void 0),
    e
}(Light)
  , name$2D = "kernelBlurVaryingDeclaration"
  , shader$2D = "varying vec2 sampleCoord{X};";
ShaderStore.IncludesShadersStore[name$2D] = shader$2D;
var name$2C = "packingFunctions"
  , shader$2C = `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$2C] = shader$2C;
var name$2B = "kernelBlurFragment"
  , shader$2B = `#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$2B] = shader$2B;
var name$2A = "kernelBlurFragment2"
  , shader$2A = `#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$2A] = shader$2A;
var name$2z = "kernelBlurPixelShader"
  , shader$2z = `
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$2z] = shader$2z;
var name$2y = "kernelBlurVertex"
  , shader$2y = "sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";
ShaderStore.IncludesShadersStore[name$2y] = shader$2y;
var name$2x = "kernelBlurVertexShader"
  , shader$2x = `
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$2x] = shader$2x;
var BlurPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $, _e) {
        _ === void 0 && (_ = Texture.BILINEAR_SAMPLINGMODE),
        j === void 0 && (j = 0),
        $ === void 0 && ($ = ""),
        _e === void 0 && (_e = !1);
        var et = a.call(this, i, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], c, d, _, b, k, null, j, "kernelBlur", {
            varyingCount: 0,
            depCount: 0
        }, !0) || this;
        return et.blockCompilation = _e,
        et._packedFloat = !1,
        et._staticDefines = "",
        et._staticDefines = $,
        et.direction = o,
        et.onApplyObservable.add(function(tt) {
            et._outputTexture ? tt.setFloat2("delta", 1 / et._outputTexture.width * et.direction.x, 1 / et._outputTexture.height * et.direction.y) : tt.setFloat2("delta", 1 / et.width * et.direction.x, 1 / et.height * et.direction.y)
        }),
        et.kernel = s,
        et
    }
    return Object.defineProperty(e.prototype, "kernel", {
        get: function() {
            return this._idealKernel
        },
        set: function(i) {
            this._idealKernel !== i && (i = Math.max(i, 1),
            this._idealKernel = i,
            this._kernel = this._nearestBestKernel(i),
            this.blockCompilation || this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "packedFloat", {
        get: function() {
            return this._packedFloat
        },
        set: function(i) {
            this._packedFloat !== i && (this._packedFloat = i,
            this.blockCompilation || this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "BlurPostProcess"
    }
    ,
    e.prototype.updateEffect = function(i, o, s, c, d, _) {
        this._updateParameters(d, _)
    }
    ,
    e.prototype._updateParameters = function(i, o) {
        for (var s = this._kernel, c = (s - 1) / 2, d = [], _ = [], b = 0, k = 0; k < s; k++) {
            var j = k / (s - 1)
              , $ = this._gaussianWeight(j * 2 - 1);
            d[k] = k - c,
            _[k] = $,
            b += $
        }
        for (var k = 0; k < _.length; k++)
            _[k] /= b;
        for (var _e = [], et = [], tt = [], k = 0; k <= c; k += 2) {
            var rt = Math.min(k + 1, Math.floor(c))
              , it = k === rt;
            if (it)
                tt.push({
                    o: d[k],
                    w: _[k]
                });
            else {
                var nt = rt === c
                  , ot = _[k] + _[rt] * (nt ? .5 : 1)
                  , at = d[k] + 1 / (1 + _[k] / _[rt]);
                at === 0 ? (tt.push({
                    o: d[k],
                    w: _[k]
                }),
                tt.push({
                    o: d[k + 1],
                    w: _[k + 1]
                })) : (tt.push({
                    o: at,
                    w: ot
                }),
                tt.push({
                    o: -at,
                    w: ot
                }))
            }
        }
        for (var k = 0; k < tt.length; k++)
            et[k] = tt[k].o,
            _e[k] = tt[k].w;
        d = et,
        _ = _e;
        var st = this.getEngine().getCaps().maxVaryingVectors
          , ut = Math.max(st, 0) - 1
          , ct = Math.min(d.length, ut)
          , lt = "";
        lt += this._staticDefines,
        this._staticDefines.indexOf("DOF") != -1 && (lt += "#define CENTER_WEIGHT " + this._glslFloat(_[ct - 1]) + `\r
`,
        ct--);
        for (var k = 0; k < ct; k++)
            lt += "#define KERNEL_OFFSET" + k + " " + this._glslFloat(d[k]) + `\r
`,
            lt += "#define KERNEL_WEIGHT" + k + " " + this._glslFloat(_[k]) + `\r
`;
        for (var ft = 0, k = ut; k < d.length; k++)
            lt += "#define KERNEL_DEP_OFFSET" + ft + " " + this._glslFloat(d[k]) + `\r
`,
            lt += "#define KERNEL_DEP_WEIGHT" + ft + " " + this._glslFloat(_[k]) + `\r
`,
            ft++;
        this.packedFloat && (lt += "#define PACKEDFLOAT 1"),
        this.blockCompilation = !1,
        a.prototype.updateEffect.call(this, lt, null, null, {
            varyingCount: ct,
            depCount: ft
        }, i, o)
    }
    ,
    e.prototype._nearestBestKernel = function(i) {
        for (var o = Math.round(i), s = 0, c = [o, o - 1, o + 1, o - 2, o + 2]; s < c.length; s++) {
            var d = c[s];
            if (d % 2 !== 0 && Math.floor(d / 2) % 2 === 0 && d > 0)
                return Math.max(d, 3)
        }
        return Math.max(o, 3)
    }
    ,
    e.prototype._gaussianWeight = function(i) {
        var o = .3333333333333333
          , s = Math.sqrt(2 * Math.PI) * o
          , c = -(i * i / (2 * o * o))
          , d = 1 / s * Math.exp(c);
        return d
    }
    ,
    e.prototype._glslFloat = function(i, o) {
        return o === void 0 && (o = 8),
        i.toFixed(o).replace(/0+$/, "")
    }
    ,
    e._Parse = function(i, o, s, c) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,i.direction,i.kernel,i.options,o,i.renderTargetSamplingMode,s.getEngine(),i.reusable,i.textureType,void 0,!1)
        }, i, s, c)
    }
    ,
    __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 a() {
        this._defines = {},
        this._currentRank = 32,
        this._maxRank = -1,
        this._mesh = null
    }
    return a.prototype.unBindMesh = function() {
        this._mesh = null
    }
    ,
    a.prototype.addFallback = function(e, i) {
        this._defines[e] || (e < this._currentRank && (this._currentRank = e),
        e > this._maxRank && (this._maxRank = e),
        this._defines[e] = new Array),
        this._defines[e].push(i)
    }
    ,
    a.prototype.addCPUSkinningFallback = function(e, i) {
        this._mesh = i,
        e < this._currentRank && (this._currentRank = e),
        e > this._maxRank && (this._maxRank = e)
    }
    ,
    Object.defineProperty(a.prototype, "hasMoreFallbacks", {
        get: function() {
            return this._currentRank <= this._maxRank
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.reduce = function(e, i) {
        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"),
            i._bonesComputationForcedToCPU = !0;
            for (var o = this._mesh.getScene(), s = 0; s < o.meshes.length; s++) {
                var c = o.meshes[s];
                if (!c.material) {
                    !this._mesh.material && c.computeBonesUsingShaders && c.numBoneInfluencers > 0 && (c.computeBonesUsingShaders = !1);
                    continue
                }
                if (!(!c.computeBonesUsingShaders || c.numBoneInfluencers === 0)) {
                    if (c.material.getEffect() === i)
                        c.computeBonesUsingShaders = !1;
                    else if (c.subMeshes)
                        for (var d = 0, _ = c.subMeshes; d < _.length; d++) {
                            var b = _[d]
                              , k = b.effect;
                            if (k === i) {
                                c.computeBonesUsingShaders = !1;
                                break
                            }
                        }
                }
            }
        } else {
            var j = this._defines[this._currentRank];
            if (j)
                for (var s = 0; s < j.length; s++)
                    e = e.replace("#define " + j[s], "");
            this._currentRank++
        }
        return e
    }
    ,
    a
}()
  , name$2w = "bayerDitherFunctions"
  , shader$2w = `




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$2w] = shader$2w;
var name$2v = "shadowMapFragmentExtraDeclaration"
  , shader$2v = `#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$2v] = shader$2v;
var name$2u = "clipPlaneFragmentDeclaration"
  , shader$2u = `#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$2u] = shader$2u;
var name$2t = "clipPlaneFragment"
  , shader$2t = `#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$2t] = shader$2t;
var name$2s = "shadowMapFragment"
  , shader$2s = ` 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$2s] = shader$2s;
var name$2r = "shadowMapPixelShader"
  , shader$2r = `#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$2r] = shader$2r;
var name$2q = "bonesDeclaration"
  , shader$2q = `#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$2q] = shader$2q;
var name$2p = "bakedVertexAnimationDeclaration"
  , shader$2p = `#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$2p] = shader$2p;
var name$2o = "morphTargetsVertexGlobalDeclaration"
  , shader$2o = `#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$2o] = shader$2o;
var name$2n = "morphTargetsVertexDeclaration"
  , shader$2n = `#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$2n] = shader$2n;
var name$2m = "sceneVertexDeclaration"
  , shader$2m = `uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
uniform mat4 view;
uniform mat4 projection;
uniform vec4 vEyePosition;
`;
ShaderStore.IncludesShadersStore[name$2m] = shader$2m;
var name$2l = "meshVertexDeclaration"
  , shader$2l = `uniform mat4 world;
uniform float visibility;
`;
ShaderStore.IncludesShadersStore[name$2l] = shader$2l;
var name$2k = "shadowMapVertexDeclaration"
  , shader$2k = `#include<sceneVertexDeclaration>
#include<meshVertexDeclaration>
`;
ShaderStore.IncludesShadersStore[name$2k] = shader$2k;
var name$2j = "sceneUboDeclaration"
  , shader$2j = `layout(std140,column_major) uniform;
uniform Scene {
mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif
mat4 view;
mat4 projection;
vec4 vEyePosition;
};
`;
ShaderStore.IncludesShadersStore[name$2j] = shader$2j;
var name$2i = "meshUboDeclaration"
  , shader$2i = `layout(std140,column_major) uniform;
uniform Mesh
{
mat4 world;
float visibility;
};
#define WORLD_UBO`;
ShaderStore.IncludesShadersStore[name$2i] = shader$2i;
var name$2h = "shadowMapUboDeclaration"
  , shader$2h = `layout(std140,column_major) uniform;
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
ShaderStore.IncludesShadersStore[name$2h] = shader$2h;
var name$2g = "shadowMapVertexExtraDeclaration"
  , shader$2g = `#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$2g] = shader$2g;
var name$2f = "clipPlaneVertexDeclaration"
  , shader$2f = `#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$2f] = shader$2f;
var name$2e = "morphTargetsVertexGlobal"
  , shader$2e = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
float vertexID;
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2e] = shader$2e;
var name$2d = "morphTargetsVertex"
  , shader$2d = `#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$2d] = shader$2d;
var name$2c = "instancesVertex"
  , shader$2c = `#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$2c] = shader$2c;
var name$2b = "bonesVertex"
  , shader$2b = `#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$2b] = shader$2b;
var name$2a = "bakedVertexAnimation"
  , shader$2a = `#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$2a] = shader$2a;
var name$29 = "shadowMapVertexNormalBias"
  , shader$29 = `
#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$29] = shader$29;
var name$28 = "shadowMapVertexMetric"
  , shader$28 = `#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$28] = shader$28;
var name$27 = "clipPlaneVertex"
  , shader$27 = `#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$27] = shader$27;
var name$26 = "shadowMapVertexShader"
  , shader$26 = `
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$26] = shader$26;
var name$25 = "depthBoxBlurPixelShader"
  , shader$25 = `
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$25] = shader$25;
var name$24 = "shadowMapFragmentSoftTransparentShadow"
  , shader$24 = `#if SM_SOFTTRANSPARENTSHADOW == 1
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;
#endif
`;
ShaderStore.IncludesShadersStore[name$24] = shader$24;
var ShadowGenerator = function() {
    function a(e, i, o) {
        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 = a.FILTER_NONE,
        this._filteringQuality = a.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 = i,
        this._scene = i.getScene(),
        i._shadowGenerator = this,
        this.id = i.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 + '")'))),
        a._SceneComponentInitialization(this._scene);
        var s = this._scene.getEngine().getCaps();
        o ? s.textureFloatRender && s.textureFloatLinearFiltering ? this._textureType = 1 : s.textureHalfFloatRender && s.textureHalfFloatLinearFiltering ? this._textureType = 2 : this._textureType = 0 : s.textureHalfFloatRender && s.textureHalfFloatLinearFiltering ? this._textureType = 2 : s.textureFloatRender && s.textureFloatLinearFiltering ? this._textureType = 1 : this._textureType = 0,
        this._initializeGenerator(),
        this._applyFilterValues()
    }
    return Object.defineProperty(a.prototype, "bias", {
        get: function() {
            return this._bias
        },
        set: function(e) {
            this._bias = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "normalBias", {
        get: function() {
            return this._normalBias
        },
        set: function(e) {
            this._normalBias = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "blurBoxOffset", {
        get: function() {
            return this._blurBoxOffset
        },
        set: function(e) {
            this._blurBoxOffset !== e && (this._blurBoxOffset = e,
            this._disposeBlurPostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "blurScale", {
        get: function() {
            return this._blurScale
        },
        set: function(e) {
            this._blurScale !== e && (this._blurScale = e,
            this._disposeBlurPostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "blurKernel", {
        get: function() {
            return this._blurKernel
        },
        set: function(e) {
            this._blurKernel !== e && (this._blurKernel = e,
            this._disposeBlurPostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "useKernelBlur", {
        get: function() {
            return this._useKernelBlur
        },
        set: function(e) {
            this._useKernelBlur !== e && (this._useKernelBlur = e,
            this._disposeBlurPostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "depthScale", {
        get: function() {
            return this._depthScale !== void 0 ? this._depthScale : this._light.getDepthScale()
        },
        set: function(e) {
            this._depthScale = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._validateFilter = function(e) {
        return e
    }
    ,
    Object.defineProperty(a.prototype, "filter", {
        get: function() {
            return this._filter
        },
        set: function(e) {
            if (e = this._validateFilter(e),
            this._light.needCube()) {
                if (e === a.FILTER_BLUREXPONENTIALSHADOWMAP) {
                    this.useExponentialShadowMap = !0;
                    return
                } else if (e === a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
                    this.useCloseExponentialShadowMap = !0;
                    return
                } else if (e === a.FILTER_PCF || e === a.FILTER_PCSS) {
                    this.usePoissonSampling = !0;
                    return
                }
            }
            if ((e === a.FILTER_PCF || e === a.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(a.prototype, "usePoissonSampling", {
        get: function() {
            return this.filter === a.FILTER_POISSONSAMPLING
        },
        set: function(e) {
            var i = this._validateFilter(a.FILTER_POISSONSAMPLING);
            !e && this.filter !== a.FILTER_POISSONSAMPLING || (this.filter = e ? i : a.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "useExponentialShadowMap", {
        get: function() {
            return this.filter === a.FILTER_EXPONENTIALSHADOWMAP
        },
        set: function(e) {
            var i = this._validateFilter(a.FILTER_EXPONENTIALSHADOWMAP);
            !e && this.filter !== a.FILTER_EXPONENTIALSHADOWMAP || (this.filter = e ? i : a.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "useBlurExponentialShadowMap", {
        get: function() {
            return this.filter === a.FILTER_BLUREXPONENTIALSHADOWMAP
        },
        set: function(e) {
            var i = this._validateFilter(a.FILTER_BLUREXPONENTIALSHADOWMAP);
            !e && this.filter !== a.FILTER_BLUREXPONENTIALSHADOWMAP || (this.filter = e ? i : a.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "useCloseExponentialShadowMap", {
        get: function() {
            return this.filter === a.FILTER_CLOSEEXPONENTIALSHADOWMAP
        },
        set: function(e) {
            var i = this._validateFilter(a.FILTER_CLOSEEXPONENTIALSHADOWMAP);
            !e && this.filter !== a.FILTER_CLOSEEXPONENTIALSHADOWMAP || (this.filter = e ? i : a.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "useBlurCloseExponentialShadowMap", {
        get: function() {
            return this.filter === a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP
        },
        set: function(e) {
            var i = this._validateFilter(a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);
            !e && this.filter !== a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP || (this.filter = e ? i : a.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "usePercentageCloserFiltering", {
        get: function() {
            return this.filter === a.FILTER_PCF
        },
        set: function(e) {
            var i = this._validateFilter(a.FILTER_PCF);
            !e && this.filter !== a.FILTER_PCF || (this.filter = e ? i : a.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "useContactHardeningShadow", {
        get: function() {
            return this.filter === a.FILTER_PCSS
        },
        set: function(e) {
            var i = this._validateFilter(a.FILTER_PCSS);
            !e && this.filter !== a.FILTER_PCSS || (this.filter = e ? i : a.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "contactHardeningLightSizeUVRatio", {
        get: function() {
            return this._contactHardeningLightSizeUVRatio
        },
        set: function(e) {
            this._contactHardeningLightSizeUVRatio = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "darkness", {
        get: function() {
            return this._darkness
        },
        set: function(e) {
            this.setDarkness(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getDarkness = function() {
        return this._darkness
    }
    ,
    a.prototype.setDarkness = function(e) {
        return e >= 1 ? this._darkness = 1 : e <= 0 ? this._darkness = 0 : this._darkness = e,
        this
    }
    ,
    Object.defineProperty(a.prototype, "transparencyShadow", {
        get: function() {
            return this._transparencyShadow
        },
        set: function(e) {
            this.setTransparencyShadow(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setTransparencyShadow = function(e) {
        return this._transparencyShadow = e,
        this
    }
    ,
    a.prototype.getShadowMap = function() {
        return this._shadowMap
    }
    ,
    a.prototype.getShadowMapForRendering = function() {
        return this._shadowMap2 ? this._shadowMap2 : this._shadowMap
    }
    ,
    a.prototype.getClassName = function() {
        return a.CLASSNAME
    }
    ,
    a.prototype.addShadowCaster = function(e, i) {
        if (i === void 0 && (i = !0),
        !this._shadowMap)
            return this;
        if (this._shadowMap.renderList || (this._shadowMap.renderList = []),
        this._shadowMap.renderList.indexOf(e) === -1 && this._shadowMap.renderList.push(e),
        i)
            for (var o = 0, s = e.getChildMeshes(); o < s.length; o++) {
                var c = s[o];
                this._shadowMap.renderList.indexOf(c) === -1 && this._shadowMap.renderList.push(c)
            }
        return this
    }
    ,
    a.prototype.removeShadowCaster = function(e, i) {
        if (i === void 0 && (i = !0),
        !this._shadowMap || !this._shadowMap.renderList)
            return this;
        var o = this._shadowMap.renderList.indexOf(e);
        if (o !== -1 && this._shadowMap.renderList.splice(o, 1),
        i)
            for (var s = 0, c = e.getChildren(); s < c.length; s++) {
                var d = c[s];
                this.removeShadowCaster(d)
            }
        return this
    }
    ,
    a.prototype.getLight = function() {
        return this._light
    }
    ,
    Object.defineProperty(a.prototype, "mapSize", {
        get: function() {
            return this._mapSize
        },
        set: function(e) {
            this._mapSize = e,
            this._light._markMeshesAsLightDirty(),
            this.recreateShadowMap()
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._initializeGenerator = function() {
        this._light._markMeshesAsLightDirty(),
        this._initializeShadowMap()
    }
    ,
    a.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())
    }
    ,
    a.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(d, _) {
                return !0
            }
            ;
            var i = this._scene.getEngine();
            this._shadowMap.onBeforeBindObservable.add(function() {
                var d;
                e._currentSceneUBO = e._scene.getSceneUniformBuffer(),
                (d = i._debugPushGroup) === null || d === void 0 || d.call(i, "shadow map generation for pass id " + i.currentRenderPassId, 1)
            }),
            this._shadowMap.onBeforeRenderObservable.add(function(d) {
                e._sceneUBOs && e._scene.setSceneUniformBuffer(e._sceneUBOs[0]),
                e._currentFaceIndex = d,
                e._filter === a.FILTER_PCF && i.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 d, _;
                if (e._sceneUBOs && e._scene.setSceneUniformBuffer(e._currentSceneUBO),
                e._scene.updateTransformMatrix(),
                e._filter === a.FILTER_PCF && i.setColorWrite(!0),
                !e.useBlurExponentialShadowMap && !e.useBlurCloseExponentialShadowMap) {
                    (d = i._debugPopGroup) === null || d === void 0 || d.call(i, 1);
                    return
                }
                var b = e.getShadowMapForRendering();
                b && (e._scene.postProcessManager.directRender(e._blurPostProcesses, b.renderTarget, !0),
                i.unBindFramebuffer(b.renderTarget, !0),
                (_ = i._debugPopGroup) === null || _ === void 0 || _.call(i, 1))
            });
            var o = new Color4(0,0,0,0)
              , s = new Color4(1,1,1,1);
            this._shadowMap.onClearObservable.add(function(d) {
                e._filter === a.FILTER_PCF ? d.clear(s, !1, !0, !1) : e.useExponentialShadowMap || e.useBlurExponentialShadowMap ? d.clear(o, !0, !0, !1) : d.clear(s, !0, !0, !1)
            }),
            this._shadowMap.onResizeObservable.add(function(d) {
                e._storedUniqueId = e._shadowMap.uniqueId,
                e._mapSize = d.getRenderSize(),
                e._light._markMeshesAsLightDirty(),
                e.recreateShadowMap()
            });
            for (var c = RenderingManager.MIN_RENDERINGGROUPS; c < RenderingManager.MAX_RENDERINGGROUPS; c++)
                this._shadowMap.setRenderingAutoClearDepthStencil(c, !1)
        }
    }
    ,
    a.prototype._initializeBlurRTTAndPostProcesses = function() {
        var e = this
          , i = this._scene.getEngine()
          , o = this._mapSize / this.blurScale;
        (!this.useKernelBlur || this.blurScale !== 1) && (this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2",o,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,i,!1,this._textureType),
        this._kernelBlurXPostprocess.width = o,
        this._kernelBlurXPostprocess.height = o,
        this._kernelBlurXPostprocess.externalTextureSamplerBinding = !0,
        this._kernelBlurXPostprocess.onApplyObservable.add(function(s) {
            s.setTexture("textureSampler", e._shadowMap)
        }),
        this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY",new Vector2(0,1),this.blurKernel,1,null,Texture.BILINEAR_SAMPLINGMODE,i,!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,i,!1,"#define OFFSET " + this._blurBoxOffset,this._textureType),
        this._boxBlurPostprocess.externalTextureSamplerBinding = !0,
        this._boxBlurPostprocess.onApplyObservable.add(function(s) {
            s.setFloat2("screenSize", o, o),
            s.setTexture("textureSampler", e._shadowMap)
        }),
        this._boxBlurPostprocess.autoClear = !1,
        this._blurPostProcesses = [this._boxBlurPostprocess])
    }
    ,
    a.prototype._renderForShadowMap = function(e, i, o, s) {
        var c;
        if (s.length)
            for (c = 0; c < s.length; c++)
                this._renderSubMeshForShadowMap(s.data[c]);
        for (c = 0; c < e.length; c++)
            this._renderSubMeshForShadowMap(e.data[c]);
        for (c = 0; c < i.length; c++)
            this._renderSubMeshForShadowMap(i.data[c]);
        if (this._transparencyShadow)
            for (c = 0; c < o.length; c++)
                this._renderSubMeshForShadowMap(o.data[c], !0);
        else
            for (c = 0; c < o.length; c++)
                o.data[c].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = !1
    }
    ,
    a.prototype._bindCustomEffectForRenderSubMeshForShadowMap = function(e, i, o) {
        i.setMatrix("viewProjection", this.getTransformMatrix())
    }
    ,
    a.prototype._renderSubMeshForShadowMap = function(e, i) {
        var o, s;
        i === void 0 && (i = !1);
        var c = e.getRenderingMesh()
          , d = e.getEffectiveMesh()
          , _ = this._scene
          , b = _.getEngine()
          , k = e.getMaterial();
        if (d._internalAbstractMeshDataInfo._isActiveIntermediate = !1,
        !(!k || e.verticesCount === 0 || e._renderId === _.getRenderId())) {
            var j = d._getWorldMatrixDeterminant() < 0
              , $ = (o = c.overrideMaterialSideOrientation) !== null && o !== void 0 ? o : k.sideOrientation;
            (_.useRightHandedSystem && !j || !_.useRightHandedSystem && j) && ($ = $ === 0 ? 1 : 0);
            var _e = $ === 0;
            b.setState(k.backFaceCulling, void 0, void 0, _e, k.cullBackFaces);
            var et = c._getInstancesRenderList(e._id, !!e.getReplacementMesh());
            if (!et.mustReturn) {
                var tt = b.getCaps().instancedArrays && (et.visibleInstances[e._id] !== null && et.visibleInstances[e._id] !== void 0 || c.hasThinInstances);
                if (!(this.customAllowRendering && !this.customAllowRendering(e)))
                    if (this.isReady(e, tt, i)) {
                        e._renderId = _.getRenderId();
                        var rt = k.shadowDepthWrapper
                          , it = (s = rt == null ? void 0 : rt.getEffect(e, this, b.currentRenderPassId)) !== null && s !== void 0 ? s : e._getDrawWrapper()
                          , nt = DrawWrapper.GetEffect(it);
                        if (b.enableEffect(it),
                        tt || c._bind(e, nt, k.fillMode),
                        this.getTransformMatrix(),
                        nt.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale),
                        this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? nt.setVector3("lightDataSM", this._cachedDirection) : nt.setVector3("lightDataSM", this._cachedPosition),
                        _.activeCamera && nt.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(_.activeCamera), this.getLight().getDepthMinZ(_.activeCamera) + this.getLight().getDepthMaxZ(_.activeCamera)),
                        i && this.enableSoftTransparentShadow && nt.setFloat("softTransparentShadowSM", d.visibility * k.alpha),
                        rt)
                            e._setMainDrawWrapperOverride(it),
                            rt.standalone ? rt.baseMaterial.bindForSubMesh(d.getWorldMatrix(), c, e) : k.bindForSubMesh(d.getWorldMatrix(), c, e),
                            e._setMainDrawWrapperOverride(null);
                        else {
                            if (k && k.needAlphaTesting()) {
                                var ot = k.getAlphaTestTexture();
                                ot && (nt.setTexture("diffuseSampler", ot),
                                nt.setMatrix("diffuseMatrix", ot.getTextureMatrix() || this._defaultTextureMatrix))
                            }
                            if (c.useBones && c.computeBonesUsingShaders && c.skeleton) {
                                var at = c.skeleton;
                                if (at.isUsingTextureForMatrices) {
                                    var st = at.getTransformMatrixTexture(c);
                                    if (!st)
                                        return;
                                    nt.setTexture("boneSampler", st),
                                    nt.setFloat("boneTextureWidth", 4 * (at.bones.length + 1))
                                } else
                                    nt.setMatrices("mBones", at.getTransformMatrices(c))
                            }
                            MaterialHelper.BindMorphTargetParameters(c, nt),
                            c.morphTargetManager && c.morphTargetManager.isUsingTextureForTargets && c.morphTargetManager._bind(nt),
                            MaterialHelper.BindClipPlane(nt, _)
                        }
                        !this._useUBO && !rt && this._bindCustomEffectForRenderSubMeshForShadowMap(e, nt, d),
                        MaterialHelper.BindSceneUniformBuffer(nt, this._scene.getSceneUniformBuffer()),
                        this._scene.getSceneUniformBuffer().bindUniformBuffer();
                        var ut = d.getWorldMatrix();
                        tt && (d.getMeshUniformBuffer().bindToEffect(nt, "Mesh"),
                        d.transferToEffect(ut)),
                        this.forceBackFacesOnly && b.setState(!0, 0, !1, !0, k.cullBackFaces),
                        this.onBeforeShadowMapRenderMeshObservable.notifyObservers(c),
                        this.onBeforeShadowMapRenderObservable.notifyObservers(nt),
                        c._processRendering(d, e, nt, k.fillMode, et, tt, function(ct, lt, ft, ht) {
                            ht && d !== ht ? (ht.getMeshUniformBuffer().bindToEffect(nt, "Mesh"),
                            ht.transferToEffect(lt)) : (d.getMeshUniformBuffer().bindToEffect(nt, "Mesh"),
                            d.transferToEffect(ut))
                        }),
                        this.forceBackFacesOnly && b.setState(!0, 0, !1, !1, k.cullBackFaces),
                        this.onAfterShadowMapRenderObservable.notifyObservers(nt),
                        this.onAfterShadowMapRenderMeshObservable.notifyObservers(c)
                    } else
                        this._shadowMap && this._shadowMap.resetRefreshCounter()
            }
        }
    }
    ,
    a.prototype._applyFilterValues = function() {
        !this._shadowMap || (this.filter === a.FILTER_NONE || this.filter === a.FILTER_PCSS ? this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE) : this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE))
    }
    ,
    a.prototype.forceCompilation = function(e, i) {
        var o = this
          , s = __assign({
            useInstances: !1
        }, i)
          , c = this.getShadowMap();
        if (!c) {
            e && e(this);
            return
        }
        var d = c.renderList;
        if (!d) {
            e && e(this);
            return
        }
        for (var _ = new Array, b = 0, k = d; b < k.length; b++) {
            var j = k[b];
            _.push.apply(_, j.subMeshes)
        }
        if (_.length === 0) {
            e && e(this);
            return
        }
        var $ = 0
          , _e = function() {
            var et, tt;
            if (!(!o._scene || !o._scene.getEngine())) {
                for (; o.isReady(_[$], s.useInstances, (tt = (et = _[$].getMaterial()) === null || et === void 0 ? void 0 : et.needAlphaBlendingForMesh(_[$].getMesh())) !== null && tt !== void 0 ? tt : !1); )
                    if ($++,
                    $ >= _.length) {
                        e && e(o);
                        return
                    }
                setTimeout(_e, 16)
            }
        };
        _e()
    }
    ,
    a.prototype.forceCompilationAsync = function(e) {
        var i = this;
        return new Promise(function(o) {
            i.forceCompilation(function() {
                o()
            }, e)
        }
        )
    }
    ,
    a.prototype._isReadyCustomDefines = function(e, i, o) {}
    ,
    a.prototype._prepareShadowDefines = function(e, i, o, s) {
        o.push("#define SM_FLOAT " + (this._textureType !== 0 ? "1" : "0")),
        o.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0")),
        o.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0"));
        var c = e.getMesh();
        return o.push("#define SM_NORMALBIAS " + (this.normalBias && c.isVerticesDataPresent(VertexBuffer.NormalKind) ? "1" : "0")),
        o.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0")),
        o.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0")),
        o.push("#define SM_SOFTTRANSPARENTSHADOW " + (this.enableSoftTransparentShadow && s ? "1" : "0")),
        this._isReadyCustomDefines(o, e, i),
        o
    }
    ,
    a.prototype.isReady = function(e, i, o) {
        var s = e.getMaterial()
          , c = s == null ? void 0 : s.shadowDepthWrapper
          , d = [];
        if (this._prepareShadowDefines(e, i, d, o),
        c) {
            if (!c.isReadyForSubMesh(e, d, this, i, this._scene.getEngine().currentRenderPassId))
                return !1
        } else {
            var _ = e._getDrawWrapper(void 0, !0)
              , b = _.effect
              , k = _.defines
              , j = [VertexBuffer.PositionKind]
              , $ = e.getMesh();
            if (this.normalBias && $.isVerticesDataPresent(VertexBuffer.NormalKind) && (j.push(VertexBuffer.NormalKind),
            d.push("#define NORMAL"),
            $.nonUniformScaling && d.push("#define NONUNIFORMSCALING")),
            s && s.needAlphaTesting()) {
                var _e = s.getAlphaTestTexture();
                if (_e) {
                    if (!_e.isReady())
                        return !1;
                    d.push("#define ALPHATEST"),
                    $.isVerticesDataPresent(VertexBuffer.UVKind) && (j.push(VertexBuffer.UVKind),
                    d.push("#define UV1")),
                    $.isVerticesDataPresent(VertexBuffer.UV2Kind) && _e.coordinatesIndex === 1 && (j.push(VertexBuffer.UV2Kind),
                    d.push("#define UV2"))
                }
            }
            var et = new EffectFallbacks;
            if ($.useBones && $.computeBonesUsingShaders && $.skeleton) {
                j.push(VertexBuffer.MatricesIndicesKind),
                j.push(VertexBuffer.MatricesWeightsKind),
                $.numBoneInfluencers > 4 && (j.push(VertexBuffer.MatricesIndicesExtraKind),
                j.push(VertexBuffer.MatricesWeightsExtraKind));
                var tt = $.skeleton;
                d.push("#define NUM_BONE_INFLUENCERS " + $.numBoneInfluencers),
                $.numBoneInfluencers > 0 && et.addCPUSkinningFallback(0, $),
                tt.isUsingTextureForMatrices ? d.push("#define BONETEXTURE") : d.push("#define BonesPerMesh " + (tt.bones.length + 1))
            } else
                d.push("#define NUM_BONE_INFLUENCERS 0");
            var rt = $.morphTargetManager
              , it = 0;
            rt && rt.numInfluencers > 0 && (d.push("#define MORPHTARGETS"),
            it = rt.numInfluencers,
            d.push("#define NUM_MORPH_INFLUENCERS " + it),
            rt.isUsingTextureForTargets && d.push("#define MORPHTARGETS_TEXTURE"),
            MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(j, $, it));
            var nt = this._scene;
            if (nt.clipPlane && d.push("#define CLIPPLANE"),
            nt.clipPlane2 && d.push("#define CLIPPLANE2"),
            nt.clipPlane3 && d.push("#define CLIPPLANE3"),
            nt.clipPlane4 && d.push("#define CLIPPLANE4"),
            nt.clipPlane5 && d.push("#define CLIPPLANE5"),
            nt.clipPlane6 && d.push("#define CLIPPLANE6"),
            i && (d.push("#define INSTANCES"),
            MaterialHelper.PushAttributesForInstances(j),
            e.getRenderingMesh().hasThinInstances && d.push("#define THIN_INSTANCES")),
            this.customShaderOptions && this.customShaderOptions.defines)
                for (var ot = 0, at = this.customShaderOptions.defines; ot < at.length; ot++) {
                    var st = at[ot];
                    d.indexOf(st) === -1 && d.push(st)
                }
            var ut = d.join(`
`);
            if (k !== ut) {
                k = ut;
                var ct = "shadowMap"
                  , lt = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightDataSM", "depthValuesSM", "biasAndScaleSM", "morphTargetInfluences", "boneTextureWidth", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "softTransparentShadowSM", "morphTargetTextureInfo", "morphTargetTextureIndices"]
                  , ft = ["diffuseSampler", "boneSampler", "morphTargets"]
                  , ht = ["Scene", "Mesh"];
                if (this.customShaderOptions) {
                    if (ct = this.customShaderOptions.shaderName,
                    this.customShaderOptions.attributes)
                        for (var pt = 0, dt = this.customShaderOptions.attributes; pt < dt.length; pt++) {
                            var _t = dt[pt];
                            j.indexOf(_t) === -1 && j.push(_t)
                        }
                    if (this.customShaderOptions.uniforms)
                        for (var mt = 0, vt = this.customShaderOptions.uniforms; mt < vt.length; mt++) {
                            var yt = vt[mt];
                            lt.indexOf(yt) === -1 && lt.push(yt)
                        }
                    if (this.customShaderOptions.samplers)
                        for (var Et = 0, At = this.customShaderOptions.samplers; Et < At.length; Et++) {
                            var gt = At[Et];
                            ft.indexOf(gt) === -1 && ft.push(gt)
                        }
                }
                var St = this._scene.getEngine();
                b = St.createEffect(ct, {
                    attributes: j,
                    uniformsNames: lt,
                    uniformBuffersNames: ht,
                    samplers: ft,
                    defines: ut,
                    fallbacks: et,
                    onCompiled: null,
                    onError: null,
                    indexParameters: {
                        maxSimultaneousMorphTargets: it
                    }
                }, St),
                _.setEffect(b, k)
            }
            if (!b.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())
    }
    ,
    a.prototype.prepareDefines = function(e, i) {
        var o = this._scene
          , s = this._light;
        !o.shadowsEnabled || !s.shadowEnabled || (e["SHADOW" + i] = !0,
        this.useContactHardeningShadow ? (e["SHADOWPCSS" + i] = !0,
        this._filteringQuality === a.QUALITY_LOW ? e["SHADOWLOWQUALITY" + i] = !0 : this._filteringQuality === a.QUALITY_MEDIUM && (e["SHADOWMEDIUMQUALITY" + i] = !0)) : this.usePercentageCloserFiltering ? (e["SHADOWPCF" + i] = !0,
        this._filteringQuality === a.QUALITY_LOW ? e["SHADOWLOWQUALITY" + i] = !0 : this._filteringQuality === a.QUALITY_MEDIUM && (e["SHADOWMEDIUMQUALITY" + i] = !0)) : this.usePoissonSampling ? e["SHADOWPOISSON" + i] = !0 : this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? e["SHADOWESM" + i] = !0 : (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) && (e["SHADOWCLOSEESM" + i] = !0),
        s.needCube() && (e["SHADOWCUBE" + i] = !0))
    }
    ,
    a.prototype.bindShadowLight = function(e, i) {
        var o = this._light
          , s = this._scene;
        if (!(!s.shadowsEnabled || !o.shadowEnabled)) {
            var c = s.activeCamera;
            if (!!c) {
                var d = this.getShadowMap();
                !d || (o.needCube() || i.setMatrix("lightMatrix" + e, this.getTransformMatrix()),
                this._filter === a.FILTER_PCF ? (i.setDepthStencilTexture("shadowSampler" + e, this.getShadowMapForRendering()),
                o._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), d.getSize().width, 1 / d.getSize().width, this.frustumEdgeFalloff, e)) : this._filter === a.FILTER_PCSS ? (i.setDepthStencilTexture("shadowSampler" + e, this.getShadowMapForRendering()),
                i.setTexture("depthSampler" + e, this.getShadowMapForRendering()),
                o._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / d.getSize().width, this._contactHardeningLightSizeUVRatio * d.getSize().width, this.frustumEdgeFalloff, e)) : (i.setTexture("shadowSampler" + e, this.getShadowMapForRendering()),
                o._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / d.getSize().width, this.depthScale, this.frustumEdgeFalloff, e)),
                o._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(c), this.getLight().getDepthMinZ(c) + this.getLight().getDepthMaxZ(c), e))
            }
        }
    }
    ,
    a.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 i = this._light.position;
        if (this._light.computeTransformedInformation() && (i = 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 || !i.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
            this._cachedPosition.copyFrom(i),
            this._cachedDirection.copyFrom(this._lightDirection),
            Matrix.LookAtLHToRef(i, i.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
            var o = this.getShadowMap();
            if (o) {
                var s = o.renderList;
                s && this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, s)
            }
            this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix)
        }
        return this._transformMatrix
    }
    ,
    a.prototype.recreateShadowMap = function() {
        var e = this._shadowMap;
        if (!!e) {
            var i = e.renderList;
            if (this._disposeRTTandPostProcesses(),
            this._initializeGenerator(),
            this.filter = this.filter,
            this._applyFilterValues(),
            i) {
                this._shadowMap.renderList || (this._shadowMap.renderList = []);
                for (var o = 0, s = i; o < s.length; o++) {
                    var c = s[o];
                    this._shadowMap.renderList.push(c)
                }
            } else
                this._shadowMap.renderList = null
        }
    }
    ,
    a.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 = []
    }
    ,
    a.prototype._disposeRTTandPostProcesses = function() {
        this._shadowMap && (this._shadowMap.dispose(),
        this._shadowMap = null),
        this._disposeBlurPostProcesses()
    }
    ,
    a.prototype._disposeSceneUBOs = function() {
        if (this._sceneUBOs) {
            for (var e = 0, i = this._sceneUBOs; e < i.length; e++) {
                var o = i[e];
                o.dispose()
            }
            this._sceneUBOs = []
        }
    }
    ,
    a.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()
    }
    ,
    a.prototype.serialize = function() {
        var e = {}
          , i = this.getShadowMap();
        if (!i)
            return e;
        if (e.className = this.getClassName(),
        e.lightId = this._light.id,
        e.id = this.id,
        e.mapSize = i.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 = [],
        i.renderList)
            for (var o = 0; o < i.renderList.length; o++) {
                var s = i.renderList[o];
                e.renderList.push(s.id)
            }
        return e
    }
    ,
    a.Parse = function(e, i, o) {
        for (var s = i.getLightById(e.lightId), c = o ? o(e.mapSize, s) : new a(e.mapSize,s), d = c.getShadowMap(), _ = 0; _ < e.renderList.length; _++) {
            var b = i.getMeshesById(e.renderList[_]);
            b.forEach(function(k) {
                !d || (d.renderList || (d.renderList = []),
                d.renderList.push(k))
            })
        }
        return e.id !== void 0 && (c.id = e.id),
        c.forceBackFacesOnly = !!e.forceBackFacesOnly,
        e.darkness !== void 0 && c.setDarkness(e.darkness),
        e.transparencyShadow && c.setTransparencyShadow(!0),
        e.frustumEdgeFalloff !== void 0 && (c.frustumEdgeFalloff = e.frustumEdgeFalloff),
        e.bias !== void 0 && (c.bias = e.bias),
        e.normalBias !== void 0 && (c.normalBias = e.normalBias),
        e.usePercentageCloserFiltering ? c.usePercentageCloserFiltering = !0 : e.useContactHardeningShadow ? c.useContactHardeningShadow = !0 : e.usePoissonSampling ? c.usePoissonSampling = !0 : e.useExponentialShadowMap ? c.useExponentialShadowMap = !0 : e.useBlurExponentialShadowMap ? c.useBlurExponentialShadowMap = !0 : e.useCloseExponentialShadowMap ? c.useCloseExponentialShadowMap = !0 : e.useBlurCloseExponentialShadowMap ? c.useBlurCloseExponentialShadowMap = !0 : e.useVarianceShadowMap ? c.useExponentialShadowMap = !0 : e.useBlurVarianceShadowMap && (c.useBlurExponentialShadowMap = !0),
        e.contactHardeningLightSizeUVRatio !== void 0 && (c.contactHardeningLightSizeUVRatio = e.contactHardeningLightSizeUVRatio),
        e.filteringQuality !== void 0 && (c.filteringQuality = e.filteringQuality),
        e.depthScale && (c.depthScale = e.depthScale),
        e.blurScale && (c.blurScale = e.blurScale),
        e.blurBoxOffset && (c.blurBoxOffset = e.blurBoxOffset),
        e.useKernelBlur && (c.useKernelBlur = e.useKernelBlur),
        e.blurKernel && (c.blurKernel = e.blurKernel),
        c
    }
    ,
    a.CLASSNAME = "ShadowGenerator",
    a.FILTER_NONE = 0,
    a.FILTER_EXPONENTIALSHADOWMAP = 1,
    a.FILTER_POISSONSAMPLING = 2,
    a.FILTER_BLUREXPONENTIALSHADOWMAP = 3,
    a.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4,
    a.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5,
    a.FILTER_PCF = 6,
    a.FILTER_PCSS = 7,
    a.QUALITY_HIGH = 0,
    a.QUALITY_MEDIUM = 1,
    a.QUALITY_LOW = 2,
    a._SceneComponentInitialization = function(e) {
        throw _WarnImport("ShadowGeneratorSceneComponent")
    }
    ,
    a
}()
  , PushMaterial = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        s === void 0 && (s = !0);
        var c = a.call(this, i, o) || this;
        return c._normalMatrix = new Matrix,
        c._storeEffectOnSubMeshes = s,
        c
    }
    return e.prototype.getEffect = function() {
        return this._storeEffectOnSubMeshes ? this._activeEffect : a.prototype.getEffect.call(this)
    }
    ,
    e.prototype.isReady = function(i, o) {
        return i ? !this._storeEffectOnSubMeshes || !i.subMeshes || i.subMeshes.length === 0 ? !0 : this.isReadyForSubMesh(i, i.subMeshes[0], o) : !1
    }
    ,
    e.prototype._isReadyForSubMesh = function(i) {
        var o = i.materialDefines;
        return !!(!this.checkReadyOnEveryCall && i.effect && o && o._renderId === this.getScene().getRenderId())
    }
    ,
    e.prototype.bindOnlyWorldMatrix = function(i) {
        this._activeEffect.setMatrix("world", i)
    }
    ,
    e.prototype.bindOnlyNormalMatrix = function(i) {
        this._activeEffect.setMatrix("normalMatrix", i)
    }
    ,
    e.prototype.bind = function(i, o) {
        !o || this.bindForSubMesh(i, o, o.subMeshes[0])
    }
    ,
    e.prototype._afterBind = function(i, o) {
        o === void 0 && (o = null),
        a.prototype._afterBind.call(this, i, o),
        this.getScene()._cachedEffect = o
    }
    ,
    e.prototype._mustRebind = function(i, o, s) {
        return s === void 0 && (s = 1),
        i.isCachedMaterialInvalid(this, o, s)
    }
    ,
    e
}(Material)
  , onCreatedEffectParameters$3 = {
    effect: null,
    subMesh: null
}
  , ShaderMaterial = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        c === void 0 && (c = {}),
        d === void 0 && (d = !0);
        var _ = a.call(this, i, o, d) || this;
        return _._textures = {},
        _._textureArrays = {},
        _._externalTextures = {},
        _._floats = {},
        _._ints = {},
        _._floatsArrays = {},
        _._colors3 = {},
        _._colors3Arrays = {},
        _._colors4 = {},
        _._colors4Arrays = {},
        _._vectors2 = {},
        _._vectors3 = {},
        _._vectors4 = {},
        _._matrices = {},
        _._matrixArrays = {},
        _._matrices3x3 = {},
        _._matrices2x2 = {},
        _._vectors2Arrays = {},
        _._vectors3Arrays = {},
        _._vectors4Arrays = {},
        _._uniformBuffers = {},
        _._textureSamplers = {},
        _._storageBuffers = {},
        _._cachedWorldViewMatrix = new Matrix,
        _._cachedWorldViewProjectionMatrix = new Matrix,
        _._multiview = !1,
        _._shaderPath = s,
        _._options = __assign({
            needAlphaBlending: !1,
            needAlphaTesting: !1,
            attributes: ["position", "normal", "uv"],
            uniforms: ["worldViewProjection"],
            uniformBuffers: [],
            samplers: [],
            externalTextures: [],
            samplerObjects: [],
            storageBuffers: [],
            defines: [],
            useClipPlane: !1
        }, c),
        _
    }
    return Object.defineProperty(e.prototype, "shaderPath", {
        get: function() {
            return this._shaderPath
        },
        set: function(i) {
            this._shaderPath = i
        },
        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(i) {
        this._options.uniforms.indexOf(i) === -1 && this._options.uniforms.push(i)
    }
    ,
    e.prototype.setTexture = function(i, o) {
        return this._options.samplers.indexOf(i) === -1 && this._options.samplers.push(i),
        this._textures[i] = o,
        this
    }
    ,
    e.prototype.setTextureArray = function(i, o) {
        return this._options.samplers.indexOf(i) === -1 && this._options.samplers.push(i),
        this._checkUniform(i),
        this._textureArrays[i] = o,
        this
    }
    ,
    e.prototype.setExternalTexture = function(i, o) {
        return this._options.externalTextures.indexOf(i) === -1 && this._options.externalTextures.push(i),
        this._externalTextures[i] = o,
        this
    }
    ,
    e.prototype.setFloat = function(i, o) {
        return this._checkUniform(i),
        this._floats[i] = o,
        this
    }
    ,
    e.prototype.setInt = function(i, o) {
        return this._checkUniform(i),
        this._ints[i] = o,
        this
    }
    ,
    e.prototype.setFloats = function(i, o) {
        return this._checkUniform(i),
        this._floatsArrays[i] = o,
        this
    }
    ,
    e.prototype.setColor3 = function(i, o) {
        return this._checkUniform(i),
        this._colors3[i] = o,
        this
    }
    ,
    e.prototype.setColor3Array = function(i, o) {
        return this._checkUniform(i),
        this._colors3Arrays[i] = o.reduce(function(s, c) {
            return c.toArray(s, s.length),
            s
        }, []),
        this
    }
    ,
    e.prototype.setColor4 = function(i, o) {
        return this._checkUniform(i),
        this._colors4[i] = o,
        this
    }
    ,
    e.prototype.setColor4Array = function(i, o) {
        return this._checkUniform(i),
        this._colors4Arrays[i] = o.reduce(function(s, c) {
            return c.toArray(s, s.length),
            s
        }, []),
        this
    }
    ,
    e.prototype.setVector2 = function(i, o) {
        return this._checkUniform(i),
        this._vectors2[i] = o,
        this
    }
    ,
    e.prototype.setVector3 = function(i, o) {
        return this._checkUniform(i),
        this._vectors3[i] = o,
        this
    }
    ,
    e.prototype.setVector4 = function(i, o) {
        return this._checkUniform(i),
        this._vectors4[i] = o,
        this
    }
    ,
    e.prototype.setMatrix = function(i, o) {
        return this._checkUniform(i),
        this._matrices[i] = o,
        this
    }
    ,
    e.prototype.setMatrices = function(i, o) {
        this._checkUniform(i);
        for (var s = new Float32Array(o.length * 16), c = 0; c < o.length; c++) {
            var d = o[c];
            d.copyToArray(s, c * 16)
        }
        return this._matrixArrays[i] = s,
        this
    }
    ,
    e.prototype.setMatrix3x3 = function(i, o) {
        return this._checkUniform(i),
        this._matrices3x3[i] = o,
        this
    }
    ,
    e.prototype.setMatrix2x2 = function(i, o) {
        return this._checkUniform(i),
        this._matrices2x2[i] = o,
        this
    }
    ,
    e.prototype.setArray2 = function(i, o) {
        return this._checkUniform(i),
        this._vectors2Arrays[i] = o,
        this
    }
    ,
    e.prototype.setArray3 = function(i, o) {
        return this._checkUniform(i),
        this._vectors3Arrays[i] = o,
        this
    }
    ,
    e.prototype.setArray4 = function(i, o) {
        return this._checkUniform(i),
        this._vectors4Arrays[i] = o,
        this
    }
    ,
    e.prototype.setUniformBuffer = function(i, o) {
        return this._options.uniformBuffers.indexOf(i) === -1 && this._options.uniformBuffers.push(i),
        this._uniformBuffers[i] = o,
        this
    }
    ,
    e.prototype.setTextureSampler = function(i, o) {
        return this._options.samplerObjects.indexOf(i) === -1 && this._options.samplerObjects.push(i),
        this._textureSamplers[i] = o,
        this
    }
    ,
    e.prototype.setStorageBuffer = function(i, o) {
        return this._options.storageBuffers.indexOf(i) === -1 && this._options.storageBuffers.push(i),
        this._storageBuffers[i] = o,
        this
    }
    ,
    e.prototype.isReadyForSubMesh = function(i, o, s) {
        return this.isReady(i, s, o)
    }
    ,
    e.prototype.isReady = function(i, o, s) {
        var c, d, _, b, k = s && this._storeEffectOnSubMeshes;
        if (this.isFrozen)
            if (k) {
                if (s.effect && s.effect._wasPreviouslyReady)
                    return !0
            } else {
                var j = this._drawWrapper.effect;
                if (j && j._wasPreviouslyReady && this._effectUsesInstances === o)
                    return !0
            }
        var $ = this.getScene()
          , _e = $.getEngine()
          , et = []
          , tt = []
          , rt = new EffectFallbacks
          , it = this._shaderPath
          , nt = this._options.uniforms
          , ot = this._options.uniformBuffers
          , at = this._options.samplers;
        _e.getCaps().multiview && $.activeCamera && $.activeCamera.outputRenderTarget && $.activeCamera.outputRenderTarget.getViewCount() > 1 && (this._multiview = !0,
        et.push("#define MULTIVIEW"),
        this._options.uniforms.indexOf("viewProjection") !== -1 && this._options.uniforms.indexOf("viewProjectionR") === -1 && this._options.uniforms.push("viewProjectionR"));
        for (var st = 0; st < this._options.defines.length; st++) {
            var ut = this._options.defines[st].indexOf("#define") === 0 ? this._options.defines[st] : "#define " + this._options.defines[st];
            et.push(ut)
        }
        for (var st = 0; st < this._options.attributes.length; st++)
            tt.push(this._options.attributes[st]);
        if (i && i.isVerticesDataPresent(VertexBuffer.ColorKind) && (tt.push(VertexBuffer.ColorKind),
        et.push("#define VERTEXCOLOR")),
        o && (et.push("#define INSTANCES"),
        MaterialHelper.PushAttributesForInstances(tt),
        i != null && i.hasThinInstances && et.push("#define THIN_INSTANCES")),
        i && i.useBones && i.computeBonesUsingShaders && i.skeleton) {
            tt.push(VertexBuffer.MatricesIndicesKind),
            tt.push(VertexBuffer.MatricesWeightsKind),
            i.numBoneInfluencers > 4 && (tt.push(VertexBuffer.MatricesIndicesExtraKind),
            tt.push(VertexBuffer.MatricesWeightsExtraKind));
            var ct = i.skeleton;
            et.push("#define NUM_BONE_INFLUENCERS " + i.numBoneInfluencers),
            rt.addCPUSkinningFallback(0, i),
            ct.isUsingTextureForMatrices ? (et.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")) : (et.push("#define BonesPerMesh " + (ct.bones.length + 1)),
            this._options.uniforms.indexOf("mBones") === -1 && this._options.uniforms.push("mBones"))
        } else
            et.push("#define NUM_BONE_INFLUENCERS 0");
        var lt = 0
          , ft = i ? i.morphTargetManager : null;
        if (ft) {
            var ht = ft.supportsUVs && et.indexOf("#define UV1") !== -1
              , pt = ft.supportsTangents && et.indexOf("#define TANGENT") !== -1
              , dt = ft.supportsNormals && et.indexOf("#define NORMAL") !== -1;
            lt = ft.numInfluencers,
            ht && et.push("#define MORPHTARGETS_UV"),
            pt && et.push("#define MORPHTARGETS_TANGENT"),
            dt && et.push("#define MORPHTARGETS_NORMAL"),
            lt > 0 && et.push("#define MORPHTARGETS"),
            ft.isUsingTextureForTargets && (et.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")),
            et.push("#define NUM_MORPH_INFLUENCERS " + lt);
            for (var st = 0; st < lt; st++)
                tt.push(VertexBuffer.PositionKind + st),
                dt && tt.push(VertexBuffer.NormalKind + st),
                pt && tt.push(VertexBuffer.TangentKind + st),
                ht && tt.push(VertexBuffer.UVKind + "_" + st);
            lt > 0 && (nt = nt.slice(),
            nt.push("morphTargetInfluences"),
            nt.push("morphTargetTextureInfo"),
            nt.push("morphTargetTextureIndices"))
        } else
            et.push("#define NUM_MORPH_INFLUENCERS 0");
        if (i) {
            var _t = i.bakedVertexAnimationManager;
            _t && _t.isEnabled && (et.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(tt, i, et)
        }
        for (var mt in this._textures)
            if (!this._textures[mt].isReady())
                return !1;
        i && this._shouldTurnAlphaTestOn(i) && et.push("#define ALPHATEST"),
        (this._options.useClipPlane === null && !!$.clipPlane || this._options.useClipPlane) && (et.push("#define CLIPPLANE"),
        nt.indexOf("vClipPlane") === -1 && nt.push("vClipPlane")),
        (this._options.useClipPlane === null && !!$.clipPlane2 || this._options.useClipPlane) && (et.push("#define CLIPPLANE2"),
        nt.indexOf("vClipPlane2") === -1 && nt.push("vClipPlane2")),
        (this._options.useClipPlane === null && !!$.clipPlane3 || this._options.useClipPlane) && (et.push("#define CLIPPLANE3"),
        nt.indexOf("vClipPlane3") === -1 && nt.push("vClipPlane3")),
        (this._options.useClipPlane === null && !!$.clipPlane4 || this._options.useClipPlane) && (et.push("#define CLIPPLANE4"),
        nt.indexOf("vClipPlane4") === -1 && nt.push("vClipPlane4")),
        (this._options.useClipPlane === null && !!$.clipPlane5 || this._options.useClipPlane) && (et.push("#define CLIPPLANE5"),
        nt.indexOf("vClipPlane5") === -1 && nt.push("vClipPlane5")),
        (this._options.useClipPlane === null && !!$.clipPlane6 || this._options.useClipPlane) && (et.push("#define CLIPPLANE6"),
        nt.indexOf("vClipPlane6") === -1 && nt.push("vClipPlane6")),
        this.customShaderNameResolve && (nt = nt.slice(),
        ot = ot.slice(),
        at = at.slice(),
        it = this.customShaderNameResolve(it, nt, ot, at, et, tt));
        var vt = k ? s._getDrawWrapper() : this._drawWrapper
          , yt = (c = vt == null ? void 0 : vt.effect) !== null && c !== void 0 ? c : null
          , Et = (d = vt == null ? void 0 : vt.defines) !== null && d !== void 0 ? d : null
          , At = et.join(`
`)
          , gt = yt;
        return Et !== At && (gt = _e.createEffect(it, {
            attributes: tt,
            uniformsNames: nt,
            uniformBuffersNames: ot,
            samplers: at,
            defines: At,
            fallbacks: rt,
            onCompiled: this.onCompiled,
            onError: this.onError,
            indexParameters: {
                maxSimultaneousMorphTargets: lt
            },
            shaderLanguage: this._options.shaderLanguage
        }, _e),
        k ? s.setEffect(gt, At, this._materialContext) : vt && vt.setEffect(gt, At),
        this._onEffectCreatedObservable && (onCreatedEffectParameters$3.effect = gt,
        onCreatedEffectParameters$3.subMesh = (_ = s != null ? s : i == null ? void 0 : i.subMeshes[0]) !== null && _ !== void 0 ? _ : null,
        this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$3))),
        this._effectUsesInstances = !!o,
        !((b = !(gt != null && gt.isReady())) !== null && b !== void 0) || b ? !1 : (yt !== gt && $.resetCachedMaterial(),
        gt._wasPreviouslyReady = !0,
        !0)
    }
    ,
    e.prototype.bindOnlyWorldMatrix = function(i, o) {
        var s = this.getScene()
          , c = o != null ? o : this.getEffect();
        !c || (this._options.uniforms.indexOf("world") !== -1 && c.setMatrix("world", i),
        this._options.uniforms.indexOf("worldView") !== -1 && (i.multiplyToRef(s.getViewMatrix(), this._cachedWorldViewMatrix),
        c.setMatrix("worldView", this._cachedWorldViewMatrix)),
        this._options.uniforms.indexOf("worldViewProjection") !== -1 && (i.multiplyToRef(s.getTransformMatrix(), this._cachedWorldViewProjectionMatrix),
        c.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix)))
    }
    ,
    e.prototype.bindForSubMesh = function(i, o, s) {
        var c;
        this.bind(i, o, (c = s._drawWrapperOverride) === null || c === void 0 ? void 0 : c.effect, s)
    }
    ,
    e.prototype.bind = function(i, o, s, c) {
        var d, _ = c && this._storeEffectOnSubMeshes, b = s != null ? s : _ ? c.effect : this.getEffect();
        if (!!b) {
            this._activeEffect = b,
            this.bindOnlyWorldMatrix(i, s);
            var k = this._options.uniformBuffers
              , j = !1;
            if (b && k && k.length > 0 && this.getScene().getEngine().supportsUniformBuffers)
                for (var $ = 0; $ < k.length; ++$) {
                    var _e = k[$];
                    switch (_e) {
                    case "Mesh":
                        o && (o.getMeshUniformBuffer().bindToEffect(b, "Mesh"),
                        o.transferToEffect(i));
                        break;
                    case "Scene":
                        MaterialHelper.BindSceneUniformBuffer(b, this.getScene().getSceneUniformBuffer()),
                        this.getScene().finalizeSceneUbo(),
                        j = !0;
                        break
                    }
                }
            var et = o && _ ? this._mustRebind(this.getScene(), b, o.visibility) : this.getScene().getCachedMaterial() !== this;
            if (b && et) {
                !j && this._options.uniforms.indexOf("view") !== -1 && b.setMatrix("view", this.getScene().getViewMatrix()),
                !j && this._options.uniforms.indexOf("projection") !== -1 && b.setMatrix("projection", this.getScene().getProjectionMatrix()),
                !j && this._options.uniforms.indexOf("viewProjection") !== -1 && (b.setMatrix("viewProjection", this.getScene().getTransformMatrix()),
                this._multiview && b.setMatrix("viewProjectionR", this.getScene()._transformMatrixR)),
                this.getScene().activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1 && b.setVector3("cameraPosition", this.getScene().activeCamera.globalPosition),
                MaterialHelper.BindBonesParameters(o, b),
                MaterialHelper.BindClipPlane(b, this.getScene());
                var tt;
                for (tt in this._textures)
                    b.setTexture(tt, this._textures[tt]);
                for (tt in this._textureArrays)
                    b.setTextureArray(tt, this._textureArrays[tt]);
                for (tt in this._externalTextures)
                    b.setExternalTexture(tt, this._externalTextures[tt]);
                for (tt in this._ints)
                    b.setInt(tt, this._ints[tt]);
                for (tt in this._floats)
                    b.setFloat(tt, this._floats[tt]);
                for (tt in this._floatsArrays)
                    b.setArray(tt, this._floatsArrays[tt]);
                for (tt in this._colors3)
                    b.setColor3(tt, this._colors3[tt]);
                for (tt in this._colors3Arrays)
                    b.setArray3(tt, this._colors3Arrays[tt]);
                for (tt in this._colors4) {
                    var rt = this._colors4[tt];
                    b.setFloat4(tt, rt.r, rt.g, rt.b, rt.a)
                }
                for (tt in this._colors4Arrays)
                    b.setArray4(tt, this._colors4Arrays[tt]);
                for (tt in this._vectors2)
                    b.setVector2(tt, this._vectors2[tt]);
                for (tt in this._vectors3)
                    b.setVector3(tt, this._vectors3[tt]);
                for (tt in this._vectors4)
                    b.setVector4(tt, this._vectors4[tt]);
                for (tt in this._matrices)
                    b.setMatrix(tt, this._matrices[tt]);
                for (tt in this._matrixArrays)
                    b.setMatrices(tt, this._matrixArrays[tt]);
                for (tt in this._matrices3x3)
                    b.setMatrix3x3(tt, this._matrices3x3[tt]);
                for (tt in this._matrices2x2)
                    b.setMatrix2x2(tt, this._matrices2x2[tt]);
                for (tt in this._vectors2Arrays)
                    b.setArray2(tt, this._vectors2Arrays[tt]);
                for (tt in this._vectors3Arrays)
                    b.setArray3(tt, this._vectors3Arrays[tt]);
                for (tt in this._vectors4Arrays)
                    b.setArray4(tt, this._vectors4Arrays[tt]);
                for (tt in this._uniformBuffers) {
                    var it = this._uniformBuffers[tt].getBuffer();
                    it && b.bindUniformBuffer(it, tt)
                }
                for (tt in this._textureSamplers)
                    b.setTextureSampler(tt, this._textureSamplers[tt]);
                for (tt in this._storageBuffers)
                    b.setStorageBuffer(tt, this._storageBuffers[tt])
            }
            if (b && o && (et || !this.isFrozen)) {
                var nt = o.morphTargetManager;
                nt && nt.numInfluencers > 0 && MaterialHelper.BindMorphTargetParameters(o, b);
                var ot = o.bakedVertexAnimationManager;
                ot && ot.isEnabled && ((d = o.bakedVertexAnimationManager) === null || d === void 0 || d.bind(b, this._effectUsesInstances))
            }
            this._afterBind(o, b)
        }
    }
    ,
    e.prototype.getActiveTextures = function() {
        var i = a.prototype.getActiveTextures.call(this);
        for (var o in this._textures)
            i.push(this._textures[o]);
        for (var o in this._textureArrays)
            for (var s = this._textureArrays[o], c = 0; c < s.length; c++)
                i.push(s[c]);
        return i
    }
    ,
    e.prototype.hasTexture = function(i) {
        if (a.prototype.hasTexture.call(this, i))
            return !0;
        for (var o in this._textures)
            if (this._textures[o] === i)
                return !0;
        for (var o in this._textureArrays)
            for (var s = this._textureArrays[o], c = 0; c < s.length; c++)
                if (s[c] === i)
                    return !0;
        return !1
    }
    ,
    e.prototype.clone = function(i) {
        var o = this
          , s = SerializationHelper.Clone(function() {
            return new e(i,o.getScene(),o._shaderPath,o._options,o._storeEffectOnSubMeshes)
        }, this);
        s.name = i,
        s.id = i,
        typeof s._shaderPath == "object" && (s._shaderPath = __assign({}, s._shaderPath)),
        this._options = __assign({}, this._options),
        Object.keys(this._options).forEach(function(d) {
            var _ = o._options[d];
            Array.isArray(_) && (o._options[d] = _.slice(0))
        }),
        this.stencil.copyTo(s.stencil);
        for (var c in this._textures)
            s.setTexture(c, this._textures[c]);
        for (var c in this._textureArrays)
            s.setTextureArray(c, this._textureArrays[c]);
        for (var c in this._externalTextures)
            s.setExternalTexture(c, this._externalTextures[c]);
        for (var c in this._ints)
            s.setInt(c, this._ints[c]);
        for (var c in this._floats)
            s.setFloat(c, this._floats[c]);
        for (var c in this._floatsArrays)
            s.setFloats(c, this._floatsArrays[c]);
        for (var c in this._colors3)
            s.setColor3(c, this._colors3[c]);
        for (var c in this._colors3Arrays)
            s._colors3Arrays[c] = this._colors3Arrays[c];
        for (var c in this._colors4)
            s.setColor4(c, this._colors4[c]);
        for (var c in this._colors4Arrays)
            s._colors4Arrays[c] = this._colors4Arrays[c];
        for (var c in this._vectors2)
            s.setVector2(c, this._vectors2[c]);
        for (var c in this._vectors3)
            s.setVector3(c, this._vectors3[c]);
        for (var c in this._vectors4)
            s.setVector4(c, this._vectors4[c]);
        for (var c in this._matrices)
            s.setMatrix(c, this._matrices[c]);
        for (var c in this._matrixArrays)
            s._matrixArrays[c] = this._matrixArrays[c].slice();
        for (var c in this._matrices3x3)
            s.setMatrix3x3(c, this._matrices3x3[c]);
        for (var c in this._matrices2x2)
            s.setMatrix2x2(c, this._matrices2x2[c]);
        for (var c in this._vectors2Arrays)
            s.setArray2(c, this._vectors2Arrays[c]);
        for (var c in this._vectors3Arrays)
            s.setArray3(c, this._vectors3Arrays[c]);
        for (var c in this._vectors4Arrays)
            s.setArray4(c, this._vectors4Arrays[c]);
        for (var c in this._uniformBuffers)
            s.setUniformBuffer(c, this._uniformBuffers[c]);
        for (var c in this._textureSamplers)
            s.setTextureSampler(c, this._textureSamplers[c]);
        for (var c in this._storageBuffers)
            s.setStorageBuffer(c, this._storageBuffers[c]);
        return s
    }
    ,
    e.prototype.dispose = function(i, o, s) {
        if (o) {
            var c;
            for (c in this._textures)
                this._textures[c].dispose();
            for (c in this._textureArrays)
                for (var d = this._textureArrays[c], _ = 0; _ < d.length; _++)
                    d[_].dispose()
        }
        this._textures = {},
        a.prototype.dispose.call(this, i, o, s)
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        i.customType = "BABYLON.ShaderMaterial",
        i.options = this._options,
        i.shaderPath = this._shaderPath,
        i.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes;
        var o;
        i.stencil = this.stencil.serialize(),
        i.textures = {};
        for (o in this._textures)
            i.textures[o] = this._textures[o].serialize();
        i.textureArrays = {};
        for (o in this._textureArrays) {
            i.textureArrays[o] = [];
            for (var s = this._textureArrays[o], c = 0; c < s.length; c++)
                i.textureArrays[o].push(s[c].serialize())
        }
        i.ints = {};
        for (o in this._ints)
            i.ints[o] = this._ints[o];
        i.floats = {};
        for (o in this._floats)
            i.floats[o] = this._floats[o];
        i.FloatArrays = {};
        for (o in this._floatsArrays)
            i.FloatArrays[o] = this._floatsArrays[o];
        i.colors3 = {};
        for (o in this._colors3)
            i.colors3[o] = this._colors3[o].asArray();
        i.colors3Arrays = {};
        for (o in this._colors3Arrays)
            i.colors3Arrays[o] = this._colors3Arrays[o];
        i.colors4 = {};
        for (o in this._colors4)
            i.colors4[o] = this._colors4[o].asArray();
        i.colors4Arrays = {};
        for (o in this._colors4Arrays)
            i.colors4Arrays[o] = this._colors4Arrays[o];
        i.vectors2 = {};
        for (o in this._vectors2)
            i.vectors2[o] = this._vectors2[o].asArray();
        i.vectors3 = {};
        for (o in this._vectors3)
            i.vectors3[o] = this._vectors3[o].asArray();
        i.vectors4 = {};
        for (o in this._vectors4)
            i.vectors4[o] = this._vectors4[o].asArray();
        i.matrices = {};
        for (o in this._matrices)
            i.matrices[o] = this._matrices[o].asArray();
        i.matrixArray = {};
        for (o in this._matrixArrays)
            i.matrixArray[o] = this._matrixArrays[o];
        i.matrices3x3 = {};
        for (o in this._matrices3x3)
            i.matrices3x3[o] = this._matrices3x3[o];
        i.matrices2x2 = {};
        for (o in this._matrices2x2)
            i.matrices2x2[o] = this._matrices2x2[o];
        i.vectors2Arrays = {};
        for (o in this._vectors2Arrays)
            i.vectors2Arrays[o] = this._vectors2Arrays[o];
        i.vectors3Arrays = {};
        for (o in this._vectors3Arrays)
            i.vectors3Arrays[o] = this._vectors3Arrays[o];
        i.vectors4Arrays = {};
        for (o in this._vectors4Arrays)
            i.vectors4Arrays[o] = this._vectors4Arrays[o];
        return i
    }
    ,
    e.Parse = function(i, o, s) {
        var c = SerializationHelper.Parse(function() {
            return new e(i.name,o,i.shaderPath,i.options,i.storeEffectOnSubMeshes)
        }, i, o, s), d;
        i.stencil && c.stencil.parse(i.stencil, o, s);
        for (d in i.textures)
            c.setTexture(d, Texture.Parse(i.textures[d], o, s));
        for (d in i.textureArrays) {
            for (var _ = i.textureArrays[d], b = new Array, k = 0; k < _.length; k++)
                b.push(Texture.Parse(_[k], o, s));
            c.setTextureArray(d, b)
        }
        for (d in i.ints)
            c.setInt(d, i.ints[d]);
        for (d in i.floats)
            c.setFloat(d, i.floats[d]);
        for (d in i.floatsArrays)
            c.setFloats(d, i.floatsArrays[d]);
        for (d in i.colors3)
            c.setColor3(d, Color3.FromArray(i.colors3[d]));
        for (d in i.colors3Arrays) {
            var j = i.colors3Arrays[d].reduce(function($, _e, et) {
                return et % 3 === 0 ? $.push([_e]) : $[$.length - 1].push(_e),
                $
            }, []).map(function($) {
                return Color3.FromArray($)
            });
            c.setColor3Array(d, j)
        }
        for (d in i.colors4)
            c.setColor4(d, Color4.FromArray(i.colors4[d]));
        for (d in i.colors4Arrays) {
            var j = i.colors4Arrays[d].reduce(function(_e, et, tt) {
                return tt % 4 === 0 ? _e.push([et]) : _e[_e.length - 1].push(et),
                _e
            }, []).map(function(_e) {
                return Color4.FromArray(_e)
            });
            c.setColor4Array(d, j)
        }
        for (d in i.vectors2)
            c.setVector2(d, Vector2.FromArray(i.vectors2[d]));
        for (d in i.vectors3)
            c.setVector3(d, Vector3.FromArray(i.vectors3[d]));
        for (d in i.vectors4)
            c.setVector4(d, Vector4.FromArray(i.vectors4[d]));
        for (d in i.matrices)
            c.setMatrix(d, Matrix.FromArray(i.matrices[d]));
        for (d in i.matrixArray)
            c._matrixArrays[d] = new Float32Array(i.matrixArray[d]);
        for (d in i.matrices3x3)
            c.setMatrix3x3(d, i.matrices3x3[d]);
        for (d in i.matrices2x2)
            c.setMatrix2x2(d, i.matrices2x2[d]);
        for (d in i.vectors2Arrays)
            c.setArray2(d, i.vectors2Arrays[d]);
        for (d in i.vectors3Arrays)
            c.setArray3(d, i.vectors3Arrays[d]);
        for (d in i.vectors4Arrays)
            c.setArray4(d, i.vectors4Arrays[d]);
        return c
    }
    ,
    e.ParseFromFileAsync = function(i, o, s, c) {
        var d = this;
        return c === void 0 && (c = ""),
        new Promise(function(_, b) {
            var k = new WebRequest;
            k.addEventListener("readystatechange", function() {
                if (k.readyState == 4)
                    if (k.status == 200) {
                        var j = JSON.parse(k.responseText)
                          , $ = d.Parse(j, s || Engine.LastCreatedScene, c);
                        i && ($.name = i),
                        _($)
                    } else
                        b("Unable to load the ShaderMaterial")
            }),
            k.open("GET", o),
            k.send()
        }
        )
    }
    ,
    e.CreateFromSnippetAsync = function(i, o, s) {
        var c = this;
        return s === void 0 && (s = ""),
        new Promise(function(d, _) {
            var b = new WebRequest;
            b.addEventListener("readystatechange", function() {
                if (b.readyState == 4)
                    if (b.status == 200) {
                        var k = JSON.parse(JSON.parse(b.responseText).jsonPayload)
                          , j = JSON.parse(k.shaderMaterial)
                          , $ = c.Parse(j, o || Engine.LastCreatedScene, s);
                        $.snippetId = i,
                        d($)
                    } else
                        _("Unable to load the snippet " + i)
            }),
            b.open("GET", c.SnippetUrl + "/" + i.replace(/#/g, "/")),
            b.send()
        }
        )
    }
    ,
    e.SnippetUrl = "https://snippet.babylonjs.com",
    e
}(PushMaterial);
RegisterClass("BABYLON.ShaderMaterial", ShaderMaterial);
var PrePassConfiguration = function() {
    function a() {
        this.previousWorldMatrices = {},
        this.previousBones = {}
    }
    return a.AddUniforms = function(e) {
        e.push("previousWorld", "previousViewProjection", "mPreviousBones")
    }
    ,
    a.AddSamplers = function(e) {}
    ,
    a.prototype.bindForSubMesh = function(e, i, o, s, c) {
        if (i.prePassRenderer && i.prePassRenderer.enabled && i.prePassRenderer.currentRTisSceneRT && i.prePassRenderer.getIndex(2) !== -1) {
            this.previousWorldMatrices[o.uniqueId] || (this.previousWorldMatrices[o.uniqueId] = s.clone()),
            this.previousViewProjection || (this.previousViewProjection = i.getTransformMatrix().clone(),
            this.currentViewProjection = i.getTransformMatrix().clone());
            var d = i.getEngine();
            this.currentViewProjection.updateFlag !== i.getTransformMatrix().updateFlag ? (this._lastUpdateFrameId = d.frameId,
            this.previousViewProjection.copyFrom(this.currentViewProjection),
            this.currentViewProjection.copyFrom(i.getTransformMatrix())) : this._lastUpdateFrameId !== d.frameId && (this._lastUpdateFrameId = d.frameId,
            this.previousViewProjection.copyFrom(this.currentViewProjection)),
            e.setMatrix("previousWorld", this.previousWorldMatrices[o.uniqueId]),
            e.setMatrix("previousViewProjection", this.previousViewProjection),
            this.previousWorldMatrices[o.uniqueId] = s.clone()
        }
    }
    ,
    a
}()
  , MaterialFlags = function() {
    function a() {}
    return Object.defineProperty(a, "DiffuseTextureEnabled", {
        get: function() {
            return this._DiffuseTextureEnabled
        },
        set: function(e) {
            this._DiffuseTextureEnabled !== e && (this._DiffuseTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "DetailTextureEnabled", {
        get: function() {
            return this._DetailTextureEnabled
        },
        set: function(e) {
            this._DetailTextureEnabled !== e && (this._DetailTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "AmbientTextureEnabled", {
        get: function() {
            return this._AmbientTextureEnabled
        },
        set: function(e) {
            this._AmbientTextureEnabled !== e && (this._AmbientTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "OpacityTextureEnabled", {
        get: function() {
            return this._OpacityTextureEnabled
        },
        set: function(e) {
            this._OpacityTextureEnabled !== e && (this._OpacityTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ReflectionTextureEnabled", {
        get: function() {
            return this._ReflectionTextureEnabled
        },
        set: function(e) {
            this._ReflectionTextureEnabled !== e && (this._ReflectionTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "EmissiveTextureEnabled", {
        get: function() {
            return this._EmissiveTextureEnabled
        },
        set: function(e) {
            this._EmissiveTextureEnabled !== e && (this._EmissiveTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "SpecularTextureEnabled", {
        get: function() {
            return this._SpecularTextureEnabled
        },
        set: function(e) {
            this._SpecularTextureEnabled !== e && (this._SpecularTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "BumpTextureEnabled", {
        get: function() {
            return this._BumpTextureEnabled
        },
        set: function(e) {
            this._BumpTextureEnabled !== e && (this._BumpTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "LightmapTextureEnabled", {
        get: function() {
            return this._LightmapTextureEnabled
        },
        set: function(e) {
            this._LightmapTextureEnabled !== e && (this._LightmapTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "RefractionTextureEnabled", {
        get: function() {
            return this._RefractionTextureEnabled
        },
        set: function(e) {
            this._RefractionTextureEnabled !== e && (this._RefractionTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ColorGradingTextureEnabled", {
        get: function() {
            return this._ColorGradingTextureEnabled
        },
        set: function(e) {
            this._ColorGradingTextureEnabled !== e && (this._ColorGradingTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "FresnelEnabled", {
        get: function() {
            return this._FresnelEnabled
        },
        set: function(e) {
            this._FresnelEnabled !== e && (this._FresnelEnabled = e,
            Engine.MarkAllMaterialsAsDirty(4))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ClearCoatTextureEnabled", {
        get: function() {
            return this._ClearCoatTextureEnabled
        },
        set: function(e) {
            this._ClearCoatTextureEnabled !== e && (this._ClearCoatTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ClearCoatBumpTextureEnabled", {
        get: function() {
            return this._ClearCoatBumpTextureEnabled
        },
        set: function(e) {
            this._ClearCoatBumpTextureEnabled !== e && (this._ClearCoatBumpTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ClearCoatTintTextureEnabled", {
        get: function() {
            return this._ClearCoatTintTextureEnabled
        },
        set: function(e) {
            this._ClearCoatTintTextureEnabled !== e && (this._ClearCoatTintTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "SheenTextureEnabled", {
        get: function() {
            return this._SheenTextureEnabled
        },
        set: function(e) {
            this._SheenTextureEnabled !== e && (this._SheenTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "AnisotropicTextureEnabled", {
        get: function() {
            return this._AnisotropicTextureEnabled
        },
        set: function(e) {
            this._AnisotropicTextureEnabled !== e && (this._AnisotropicTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "ThicknessTextureEnabled", {
        get: function() {
            return this._ThicknessTextureEnabled
        },
        set: function(e) {
            this._ThicknessTextureEnabled !== e && (this._ThicknessTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "RefractionIntensityTextureEnabled", {
        get: function() {
            return this._ThicknessTextureEnabled
        },
        set: function(e) {
            this._RefractionIntensityTextureEnabled !== e && (this._RefractionIntensityTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "TranslucencyIntensityTextureEnabled", {
        get: function() {
            return this._ThicknessTextureEnabled
        },
        set: function(e) {
            this._TranslucencyIntensityTextureEnabled !== e && (this._TranslucencyIntensityTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    a._DiffuseTextureEnabled = !0,
    a._DetailTextureEnabled = !0,
    a._AmbientTextureEnabled = !0,
    a._OpacityTextureEnabled = !0,
    a._ReflectionTextureEnabled = !0,
    a._EmissiveTextureEnabled = !0,
    a._SpecularTextureEnabled = !0,
    a._BumpTextureEnabled = !0,
    a._LightmapTextureEnabled = !0,
    a._RefractionTextureEnabled = !0,
    a._ColorGradingTextureEnabled = !0,
    a._FresnelEnabled = !0,
    a._ClearCoatTextureEnabled = !0,
    a._ClearCoatBumpTextureEnabled = !0,
    a._ClearCoatTintTextureEnabled = !0,
    a._SheenTextureEnabled = !0,
    a._AnisotropicTextureEnabled = !0,
    a._ThicknessTextureEnabled = !0,
    a._RefractionIntensityTextureEnabled = !0,
    a._TranslucencyIntensityTextureEnabled = !0,
    a
}()
  , name$23 = "defaultFragmentDeclaration"
  , shader$23 = `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$23] = shader$23;
var name$22 = "defaultUboDeclaration"
  , shader$22 = `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$22] = shader$22;
var name$21 = "prePassDeclaration"
  , shader$21 = `#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$21] = shader$21;
var name$20 = "oitDeclaration"
  , shader$20 = `#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$20] = shader$20;
var name$1$ = "mainUVVaryingDeclaration"
  , shader$1$ = `#ifdef MAINUV{X}
varying vec2 vMainUV{X};
#endif
`;
ShaderStore.IncludesShadersStore[name$1$] = shader$1$;
var name$1_ = "lightFragmentDeclaration"
  , shader$1_ = `#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$1_] = shader$1_;
var name$1Z = "lightUboDeclaration"
  , shader$1Z = `#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$1Z] = shader$1Z;
var name$1Y = "lightsFragmentFunctions"
  , shader$1Y = `
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$1Y] = shader$1Y;
var name$1X = "shadowsFragmentFunctions"
  , shader$1X = `#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$1X] = shader$1X;
var name$1W = "samplerFragmentDeclaration"
  , shader$1W = `#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$1W] = shader$1W;
var name$1V = "fresnelFunction"
  , shader$1V = `#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$1V] = shader$1V;
var name$1U = "reflectionFunction"
  , shader$1U = `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$1U] = shader$1U;
var name$1T = "imageProcessingDeclaration"
  , shader$1T = `#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$1T] = shader$1T;
var name$1S = "imageProcessingFunctions"
  , shader$1S = `#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$1S] = shader$1S;
var name$1R = "bumpFragmentMainFunctions"
  , shader$1R = `#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$1R] = shader$1R;
var name$1Q = "bumpFragmentFunctions"
  , shader$1Q = `#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$1Q] = shader$1Q;
var name$1P = "logDepthDeclaration"
  , shader$1P = `#ifdef LOGARITHMICDEPTH
uniform float logarithmicDepthConstant;
varying float vFragmentDepth;
#endif`;
ShaderStore.IncludesShadersStore[name$1P] = shader$1P;
var name$1O = "fogFragmentDeclaration"
  , shader$1O = `#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$1O] = shader$1O;
var name$1N = "oitFragment"
  , shader$1N = `#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$1N] = shader$1N;
var name$1M = "bumpFragment"
  , shader$1M = `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$1M] = shader$1M;
var name$1L = "depthPrePass"
  , shader$1L = `#ifdef DEPTHPREPASS
gl_FragColor=vec4(0.,0.,0.,1.0);
return;
#endif`;
ShaderStore.IncludesShadersStore[name$1L] = shader$1L;
var name$1K = "lightFragment"
  , shader$1K = `#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$1K] = shader$1K;
var name$1J = "logDepthFragment"
  , shader$1J = `#ifdef LOGARITHMICDEPTH
gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;
#endif`;
ShaderStore.IncludesShadersStore[name$1J] = shader$1J;
var name$1I = "fogFragment"
  , shader$1I = `#ifdef FOG
float fog=CalcFogFactor();
#ifdef PBR
fog=toLinearSpace(fog);
#endif
color.rgb=mix(vFogColor,color.rgb,fog);
#endif`;
ShaderStore.IncludesShadersStore[name$1I] = shader$1I;
var name$1H = "defaultPixelShader"
  , shader$1H = `#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$1H] = shader$1H;
var name$1G = "defaultVertexDeclaration"
  , shader$1G = `
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$1G] = shader$1G;
var name$1F = "uvAttributeDeclaration"
  , shader$1F = `#ifdef UV{X}
attribute vec2 uv{X};
#endif
`;
ShaderStore.IncludesShadersStore[name$1F] = shader$1F;
var name$1E = "instancesDeclaration"
  , shader$1E = `#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$1E] = shader$1E;
var name$1D = "prePassVertexDeclaration"
  , shader$1D = `#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$1D] = shader$1D;
var name$1C = "samplerVertexDeclaration"
  , shader$1C = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV == 0
varying vec2 v_VARYINGNAME_UV;
#endif
`;
ShaderStore.IncludesShadersStore[name$1C] = shader$1C;
var name$1B = "bumpVertexDeclaration"
  , shader$1B = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
varying mat3 vTBN;
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$1B] = shader$1B;
var name$1A = "fogVertexDeclaration"
  , shader$1A = `#ifdef FOG
varying vec3 vFogDistance;
#endif`;
ShaderStore.IncludesShadersStore[name$1A] = shader$1A;
var name$1z = "lightVxFragmentDeclaration"
  , shader$1z = `#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$1z] = shader$1z;
var name$1y = "lightVxUboDeclaration"
  , shader$1y = `#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$1y] = shader$1y;
var name$1x = "prePassVertex"
  , shader$1x = `#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$1x] = shader$1x;
var name$1w = "uvVariableDeclaration"
  , shader$1w = `#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$1w] = shader$1w;
var name$1v = "samplerVertexImplementation"
  , shader$1v = `#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$1v] = shader$1v;
var name$1u = "bumpVertex"
  , shader$1u = `#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$1u] = shader$1u;
var name$1t = "fogVertex"
  , shader$1t = `#ifdef FOG
vFogDistance=(view*worldPos).xyz;
#endif`;
ShaderStore.IncludesShadersStore[name$1t] = shader$1t;
var name$1s = "shadowsVertex"
  , shader$1s = `#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$1s] = shader$1s;
var name$1r = "pointCloudVertex"
  , shader$1r = `#ifdef POINTSIZE
gl_PointSize=pointSize;
#endif`;
ShaderStore.IncludesShadersStore[name$1r] = shader$1r;
var name$1q = "logDepthVertex"
  , shader$1q = `#ifdef LOGARITHMICDEPTH
vFragmentDepth=1.0+gl_Position.w;
gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;
#endif`;
ShaderStore.IncludesShadersStore[name$1q] = shader$1q;
var name$1p = "defaultVertexShader"
  , shader$1p = `#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$1p] = shader$1p;
var DetailMapConfiguration = function() {
    function a(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 a.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    a.prototype.isReadyForSubMesh = function(e, i) {
        if (!this._isEnabled)
            return !0;
        var o = i.getEngine();
        return !(e._areTexturesDirty && i.texturesEnabled && o.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && !this._texture.isReady())
    }
    ,
    a.prototype.prepareDefines = function(e, i) {
        if (this._isEnabled) {
            e.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;
            var o = i.getEngine();
            e._areTexturesDirty && (o.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
    }
    ,
    a.prototype.bindForSubMesh = function(e, i, o) {
        !this._isEnabled || ((!e.useUbo || !o || !e.isSync) && this._texture && MaterialFlags.DetailTextureEnabled && (e.updateFloat4("vDetailInfos", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel),
        MaterialHelper.BindTextureMatrix(this._texture, e, "detail")),
        i.texturesEnabled && this._texture && MaterialFlags.DetailTextureEnabled && e.setTexture("detailSampler", this._texture))
    }
    ,
    a.prototype.hasTexture = function(e) {
        return this._texture === e
    }
    ,
    a.prototype.getActiveTextures = function(e) {
        this._texture && e.push(this._texture)
    }
    ,
    a.prototype.getAnimatables = function(e) {
        this._texture && this._texture.animations && this._texture.animations.length > 0 && e.push(this._texture)
    }
    ,
    a.prototype.dispose = function(e) {
        var i;
        e && ((i = this._texture) === null || i === void 0 || i.dispose())
    }
    ,
    a.prototype.getClassName = function() {
        return "DetailMapConfiguration"
    }
    ,
    a.AddUniforms = function(e) {
        e.push("vDetailInfos"),
        e.push("detailMatrix")
    }
    ,
    a.AddSamplers = function(e) {
        e.push("detailSampler")
    }
    ,
    a.PrepareUniformBuffer = function(e) {
        e.addUniform("vDetailInfos", 4),
        e.addUniform("detailMatrix", 16)
    }
    ,
    a.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.prototype.parse = function(e, i, o) {
        var s = this;
        SerializationHelper.Parse(function() {
            return s
        }, e, i, o)
    }
    ,
    __decorate([serializeAsTexture("detailTexture"), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "texture", void 0),
    __decorate([serialize()], a.prototype, "diffuseBlendLevel", void 0),
    __decorate([serialize()], a.prototype, "roughnessBlendLevel", void 0),
    __decorate([serialize()], a.prototype, "bumpLevel", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "normalBlendMethod", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "isEnabled", void 0),
    a
}()
  , onCreatedEffectParameters$2 = {
    effect: null,
    subMesh: null
}
  , StandardMaterialDefines = function(a) {
    __extends(e, a);
    function e() {
        var i = a.call(this) || this;
        return i.MAINUV1 = !1,
        i.MAINUV2 = !1,
        i.MAINUV3 = !1,
        i.MAINUV4 = !1,
        i.MAINUV5 = !1,
        i.MAINUV6 = !1,
        i.DIFFUSE = !1,
        i.DIFFUSEDIRECTUV = 0,
        i.DETAIL = !1,
        i.DETAILDIRECTUV = 0,
        i.DETAIL_NORMALBLENDMETHOD = 0,
        i.BAKED_VERTEX_ANIMATION_TEXTURE = !1,
        i.AMBIENT = !1,
        i.AMBIENTDIRECTUV = 0,
        i.OPACITY = !1,
        i.OPACITYDIRECTUV = 0,
        i.OPACITYRGB = !1,
        i.REFLECTION = !1,
        i.EMISSIVE = !1,
        i.EMISSIVEDIRECTUV = 0,
        i.SPECULAR = !1,
        i.SPECULARDIRECTUV = 0,
        i.BUMP = !1,
        i.BUMPDIRECTUV = 0,
        i.PARALLAX = !1,
        i.PARALLAXOCCLUSION = !1,
        i.SPECULAROVERALPHA = !1,
        i.CLIPPLANE = !1,
        i.CLIPPLANE2 = !1,
        i.CLIPPLANE3 = !1,
        i.CLIPPLANE4 = !1,
        i.CLIPPLANE5 = !1,
        i.CLIPPLANE6 = !1,
        i.ALPHATEST = !1,
        i.DEPTHPREPASS = !1,
        i.ALPHAFROMDIFFUSE = !1,
        i.POINTSIZE = !1,
        i.FOG = !1,
        i.SPECULARTERM = !1,
        i.DIFFUSEFRESNEL = !1,
        i.OPACITYFRESNEL = !1,
        i.REFLECTIONFRESNEL = !1,
        i.REFRACTIONFRESNEL = !1,
        i.EMISSIVEFRESNEL = !1,
        i.FRESNEL = !1,
        i.NORMAL = !1,
        i.TANGENT = !1,
        i.UV1 = !1,
        i.UV2 = !1,
        i.UV3 = !1,
        i.UV4 = !1,
        i.UV5 = !1,
        i.UV6 = !1,
        i.VERTEXCOLOR = !1,
        i.VERTEXALPHA = !1,
        i.NUM_BONE_INFLUENCERS = 0,
        i.BonesPerMesh = 0,
        i.BONETEXTURE = !1,
        i.BONES_VELOCITY_ENABLED = !1,
        i.INSTANCES = !1,
        i.THIN_INSTANCES = !1,
        i.GLOSSINESS = !1,
        i.ROUGHNESS = !1,
        i.EMISSIVEASILLUMINATION = !1,
        i.LINKEMISSIVEWITHDIFFUSE = !1,
        i.REFLECTIONFRESNELFROMSPECULAR = !1,
        i.LIGHTMAP = !1,
        i.LIGHTMAPDIRECTUV = 0,
        i.OBJECTSPACE_NORMALMAP = !1,
        i.USELIGHTMAPASSHADOWMAP = !1,
        i.REFLECTIONMAP_3D = !1,
        i.REFLECTIONMAP_SPHERICAL = !1,
        i.REFLECTIONMAP_PLANAR = !1,
        i.REFLECTIONMAP_CUBIC = !1,
        i.USE_LOCAL_REFLECTIONMAP_CUBIC = !1,
        i.USE_LOCAL_REFRACTIONMAP_CUBIC = !1,
        i.REFLECTIONMAP_PROJECTION = !1,
        i.REFLECTIONMAP_SKYBOX = !1,
        i.REFLECTIONMAP_EXPLICIT = !1,
        i.REFLECTIONMAP_EQUIRECTANGULAR = !1,
        i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
        i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
        i.REFLECTIONMAP_OPPOSITEZ = !1,
        i.INVERTCUBICMAP = !1,
        i.LOGARITHMICDEPTH = !1,
        i.REFRACTION = !1,
        i.REFRACTIONMAP_3D = !1,
        i.REFLECTIONOVERALPHA = !1,
        i.TWOSIDEDLIGHTING = !1,
        i.SHADOWFLOAT = !1,
        i.MORPHTARGETS = !1,
        i.MORPHTARGETS_NORMAL = !1,
        i.MORPHTARGETS_TANGENT = !1,
        i.MORPHTARGETS_UV = !1,
        i.NUM_MORPH_INFLUENCERS = 0,
        i.MORPHTARGETS_TEXTURE = !1,
        i.NONUNIFORMSCALING = !1,
        i.PREMULTIPLYALPHA = !1,
        i.ALPHATEST_AFTERALLALPHACOMPUTATIONS = !1,
        i.ALPHABLEND = !0,
        i.PREPASS = !1,
        i.PREPASS_IRRADIANCE = !1,
        i.PREPASS_IRRADIANCE_INDEX = -1,
        i.PREPASS_ALBEDO_SQRT = !1,
        i.PREPASS_ALBEDO_SQRT_INDEX = -1,
        i.PREPASS_DEPTH = !1,
        i.PREPASS_DEPTH_INDEX = -1,
        i.PREPASS_NORMAL = !1,
        i.PREPASS_NORMAL_INDEX = -1,
        i.PREPASS_POSITION = !1,
        i.PREPASS_POSITION_INDEX = -1,
        i.PREPASS_VELOCITY = !1,
        i.PREPASS_VELOCITY_INDEX = -1,
        i.PREPASS_REFLECTIVITY = !1,
        i.PREPASS_REFLECTIVITY_INDEX = -1,
        i.SCENE_MRT_COUNT = 0,
        i.RGBDLIGHTMAP = !1,
        i.RGBDREFLECTION = !1,
        i.RGBDREFRACTION = !1,
        i.IMAGEPROCESSING = !1,
        i.VIGNETTE = !1,
        i.VIGNETTEBLENDMODEMULTIPLY = !1,
        i.VIGNETTEBLENDMODEOPAQUE = !1,
        i.TONEMAPPING = !1,
        i.TONEMAPPING_ACES = !1,
        i.CONTRAST = !1,
        i.COLORCURVES = !1,
        i.COLORGRADING = !1,
        i.COLORGRADING3D = !1,
        i.SAMPLER3DGREENDEPTH = !1,
        i.SAMPLER3DBGRMAP = !1,
        i.IMAGEPROCESSINGPOSTPROCESS = !1,
        i.SKIPFINALCOLORCLAMP = !1,
        i.MULTIVIEW = !1,
        i.ORDER_INDEPENDENT_TRANSPARENCY = !1,
        i.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !1,
        i.IS_REFLECTION_LINEAR = !1,
        i.IS_REFRACTION_LINEAR = !1,
        i.EXPOSURE = !1,
        i.rebuild(),
        i
    }
    return e.prototype.setReflectionMode = function(i) {
        for (var o = ["REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX", "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED", "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"], s = 0, c = o; s < c.length; s++) {
            var d = c[s];
            this[d] = d === i
        }
    }
    ,
    e
}(MaterialDefines)
  , StandardMaterial = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o) || this;
        return s._diffuseTexture = null,
        s._ambientTexture = null,
        s._opacityTexture = null,
        s._reflectionTexture = null,
        s._emissiveTexture = null,
        s._specularTexture = null,
        s._bumpTexture = null,
        s._lightmapTexture = null,
        s._refractionTexture = null,
        s.ambientColor = new Color3(0,0,0),
        s.diffuseColor = new Color3(1,1,1),
        s.specularColor = new Color3(1,1,1),
        s.emissiveColor = new Color3(0,0,0),
        s.specularPower = 64,
        s._useAlphaFromDiffuseTexture = !1,
        s._useEmissiveAsIllumination = !1,
        s._linkEmissiveWithDiffuse = !1,
        s._useSpecularOverAlpha = !1,
        s._useReflectionOverAlpha = !1,
        s._disableLighting = !1,
        s._useObjectSpaceNormalMap = !1,
        s._useParallax = !1,
        s._useParallaxOcclusion = !1,
        s.parallaxScaleBias = .05,
        s._roughness = 0,
        s.indexOfRefraction = .98,
        s.invertRefractionY = !0,
        s.alphaCutOff = .4,
        s._useLightmapAsShadowmap = !1,
        s._useReflectionFresnelFromSpecular = !1,
        s._useGlossinessFromSpecularMapAlpha = !1,
        s._maxSimultaneousLights = 4,
        s._invertNormalMapX = !1,
        s._invertNormalMapY = !1,
        s._twoSidedLighting = !1,
        s.detailMap = new DetailMapConfiguration(s._markAllSubMeshesAsTexturesDirty.bind(s)),
        s._renderTargets = new SmartArray(16),
        s._worldViewProjectionMatrix = Matrix.Zero(),
        s._globalAmbientColor = new Color3(0,0,0),
        s.buildUniformLayout(),
        s._attachImageProcessingConfiguration(null),
        s.prePassConfiguration = new PrePassConfiguration,
        s.getRenderTargetTextures = function() {
            return s._renderTargets.reset(),
            e.ReflectionTextureEnabled && s._reflectionTexture && s._reflectionTexture.isRenderTarget && s._renderTargets.push(s._reflectionTexture),
            e.RefractionTextureEnabled && s._refractionTexture && s._refractionTexture.isRenderTarget && s._renderTargets.push(s._refractionTexture),
            s._renderTargets
        }
        ,
        s
    }
    return Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(i) {
            this._attachImageProcessingConfiguration(i),
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachImageProcessingConfiguration = function(i) {
        var o = this;
        i !== this._imageProcessingConfiguration && (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        i ? this._imageProcessingConfiguration = i : this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration,
        this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
            o._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(i) {
            this.imageProcessingConfiguration.colorCurvesEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingEnabled
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorGradingEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraToneMappingEnabled", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingEnabled
        },
        set: function(i) {
            this._imageProcessingConfiguration.toneMappingEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraExposure", {
        get: function() {
            return this._imageProcessingConfiguration.exposure
        },
        set: function(i) {
            this._imageProcessingConfiguration.exposure = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraContrast", {
        get: function() {
            return this._imageProcessingConfiguration.contrast
        },
        set: function(i) {
            this._imageProcessingConfiguration.contrast = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingTexture", {
        get: function() {
            return this._imageProcessingConfiguration.colorGradingTexture
        },
        set: function(i) {
            this._imageProcessingConfiguration.colorGradingTexture = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurves", {
        get: function() {
            return this._imageProcessingConfiguration.colorCurves
        },
        set: function(i) {
            this._imageProcessingConfiguration.colorCurves = i
        },
        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(i) {
            this._useLogarithmicDepth = i && 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(i, o, s) {
        if (s === void 0 && (s = !1),
        o.effect && this.isFrozen && o.effect._wasPreviouslyReady)
            return !0;
        o.materialDefines || (o.materialDefines = new StandardMaterialDefines);
        var c = this.getScene()
          , d = o.materialDefines;
        if (this._isReadyForSubMesh(o))
            return !0;
        var _ = c.getEngine();
        d._needNormals = MaterialHelper.PrepareDefinesForLights(c, i, d, !0, this._maxSimultaneousLights, this._disableLighting),
        MaterialHelper.PrepareDefinesForMultiview(c, d);
        var b = this.needAlphaBlendingForMesh(i) && this.getScene().useOrderIndependentTransparency;
        if (MaterialHelper.PrepareDefinesForPrePass(c, d, this.canRenderToMRT && !b),
        MaterialHelper.PrepareDefinesForOIT(c, d, b),
        d._areTexturesDirty) {
            d._needUVs = !1;
            for (var k = 1; k <= 6; ++k)
                d["MAINUV" + k] = !1;
            if (c.texturesEnabled) {
                if (this._diffuseTexture && e.DiffuseTextureEnabled)
                    if (this._diffuseTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, d, "DIFFUSE");
                    else
                        return !1;
                else
                    d.DIFFUSE = !1;
                if (this._ambientTexture && e.AmbientTextureEnabled)
                    if (this._ambientTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, d, "AMBIENT");
                    else
                        return !1;
                else
                    d.AMBIENT = !1;
                if (this._opacityTexture && e.OpacityTextureEnabled)
                    if (this._opacityTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, d, "OPACITY"),
                        d.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
                    else
                        return !1;
                else
                    d.OPACITY = !1;
                if (this._reflectionTexture && e.ReflectionTextureEnabled)
                    if (this._reflectionTexture.isReadyOrNotBlocking()) {
                        switch (d._needNormals = !0,
                        d.REFLECTION = !0,
                        d.ROUGHNESS = this._roughness > 0,
                        d.REFLECTIONOVERALPHA = this._useReflectionOverAlpha,
                        d.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE,
                        d.REFLECTIONMAP_3D = this._reflectionTexture.isCube,
                        d.RGBDREFLECTION = this._reflectionTexture.isRGBD,
                        d.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !this._reflectionTexture.invertZ : this._reflectionTexture.invertZ,
                        this._reflectionTexture.coordinatesMode) {
                        case Texture.EXPLICIT_MODE:
                            d.setReflectionMode("REFLECTIONMAP_EXPLICIT");
                            break;
                        case Texture.PLANAR_MODE:
                            d.setReflectionMode("REFLECTIONMAP_PLANAR");
                            break;
                        case Texture.PROJECTION_MODE:
                            d.setReflectionMode("REFLECTIONMAP_PROJECTION");
                            break;
                        case Texture.SKYBOX_MODE:
                            d.setReflectionMode("REFLECTIONMAP_SKYBOX");
                            break;
                        case Texture.SPHERICAL_MODE:
                            d.setReflectionMode("REFLECTIONMAP_SPHERICAL");
                            break;
                        case Texture.EQUIRECTANGULAR_MODE:
                            d.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
                            break;
                        case Texture.FIXED_EQUIRECTANGULAR_MODE:
                            d.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
                            break;
                        case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                            d.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
                            break;
                        case Texture.CUBIC_MODE:
                        case Texture.INVCUBIC_MODE:
                        default:
                            d.setReflectionMode("REFLECTIONMAP_CUBIC");
                            break
                        }
                        d.USE_LOCAL_REFLECTIONMAP_CUBIC = !!this._reflectionTexture.boundingBoxSize
                    } else
                        return !1;
                else
                    d.REFLECTION = !1,
                    d.REFLECTIONMAP_OPPOSITEZ = !1;
                if (this._emissiveTexture && e.EmissiveTextureEnabled)
                    if (this._emissiveTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, d, "EMISSIVE");
                    else
                        return !1;
                else
                    d.EMISSIVE = !1;
                if (this._lightmapTexture && e.LightmapTextureEnabled)
                    if (this._lightmapTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, d, "LIGHTMAP"),
                        d.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap,
                        d.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;
                    else
                        return !1;
                else
                    d.LIGHTMAP = !1;
                if (this._specularTexture && e.SpecularTextureEnabled)
                    if (this._specularTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, d, "SPECULAR"),
                        d.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
                    else
                        return !1;
                else
                    d.SPECULAR = !1;
                if (c.getEngine().getCaps().standardDerivatives && this._bumpTexture && e.BumpTextureEnabled) {
                    if (this._bumpTexture.isReady())
                        MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, d, "BUMP"),
                        d.PARALLAX = this._useParallax,
                        d.PARALLAXOCCLUSION = this._useParallaxOcclusion;
                    else
                        return !1;
                    d.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap
                } else
                    d.BUMP = !1;
                if (this._refractionTexture && e.RefractionTextureEnabled)
                    if (this._refractionTexture.isReadyOrNotBlocking())
                        d._needUVs = !0,
                        d.REFRACTION = !0,
                        d.REFRACTIONMAP_3D = this._refractionTexture.isCube,
                        d.RGBDREFRACTION = this._refractionTexture.isRGBD,
                        d.USE_LOCAL_REFRACTIONMAP_CUBIC = !!this._refractionTexture.boundingBoxSize;
                    else
                        return !1;
                else
                    d.REFRACTION = !1;
                d.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting
            } else
                d.DIFFUSE = !1,
                d.AMBIENT = !1,
                d.OPACITY = !1,
                d.REFLECTION = !1,
                d.EMISSIVE = !1,
                d.LIGHTMAP = !1,
                d.BUMP = !1,
                d.REFRACTION = !1;
            d.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture(),
            d.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination,
            d.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse,
            d.SPECULAROVERALPHA = this._useSpecularOverAlpha,
            d.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8,
            d.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null,
            d.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(i)
        }
        if (!this.detailMap.isReadyForSubMesh(d, c))
            return !1;
        if (d._areImageProcessingDirty && this._imageProcessingConfiguration) {
            if (!this._imageProcessingConfiguration.isReady())
                return !1;
            this._imageProcessingConfiguration.prepareDefines(d),
            d.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace,
            d.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace
        }
        if (d._areFresnelDirty && (e.FresnelEnabled ? (this._diffuseFresnelParameters || this._opacityFresnelParameters || this._emissiveFresnelParameters || this._refractionFresnelParameters || this._reflectionFresnelParameters) && (d.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled,
        d.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled,
        d.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled,
        d.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular,
        d.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled,
        d.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled,
        d._needNormals = !0,
        d.FRESNEL = !0) : d.FRESNEL = !1),
        MaterialHelper.PrepareDefinesForMisc(i, c, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(i) || this._forceAlphaTest, d),
        MaterialHelper.PrepareDefinesForAttributes(i, d, !0, !0, !0),
        MaterialHelper.PrepareDefinesForFrameBoundValues(c, _, d, s, null, o.getRenderingMesh().hasThinInstances),
        this.detailMap.prepareDefines(d, c),
        d.isDirty) {
            var j = d._areLightsDisposed;
            d.markAsProcessed();
            var $ = new EffectFallbacks;
            d.REFLECTION && $.addFallback(0, "REFLECTION"),
            d.SPECULAR && $.addFallback(0, "SPECULAR"),
            d.BUMP && $.addFallback(0, "BUMP"),
            d.PARALLAX && $.addFallback(1, "PARALLAX"),
            d.PARALLAXOCCLUSION && $.addFallback(0, "PARALLAXOCCLUSION"),
            d.SPECULAROVERALPHA && $.addFallback(0, "SPECULAROVERALPHA"),
            d.FOG && $.addFallback(1, "FOG"),
            d.POINTSIZE && $.addFallback(0, "POINTSIZE"),
            d.LOGARITHMICDEPTH && $.addFallback(0, "LOGARITHMICDEPTH"),
            MaterialHelper.HandleFallbacksForShadows(d, $, this._maxSimultaneousLights),
            d.SPECULARTERM && $.addFallback(0, "SPECULARTERM"),
            d.DIFFUSEFRESNEL && $.addFallback(1, "DIFFUSEFRESNEL"),
            d.OPACITYFRESNEL && $.addFallback(2, "OPACITYFRESNEL"),
            d.REFLECTIONFRESNEL && $.addFallback(3, "REFLECTIONFRESNEL"),
            d.EMISSIVEFRESNEL && $.addFallback(4, "EMISSIVEFRESNEL"),
            d.FRESNEL && $.addFallback(4, "FRESNEL"),
            d.MULTIVIEW && $.addFallback(0, "MULTIVIEW");
            var _e = [VertexBuffer.PositionKind];
            d.NORMAL && _e.push(VertexBuffer.NormalKind),
            d.TANGENT && _e.push(VertexBuffer.TangentKind);
            for (var k = 1; k <= 6; ++k)
                d["UV" + k] && _e.push("uv" + (k === 1 ? "" : k));
            d.VERTEXCOLOR && _e.push(VertexBuffer.ColorKind),
            MaterialHelper.PrepareAttributesForBones(_e, i, d, $),
            MaterialHelper.PrepareAttributesForInstances(_e, d),
            MaterialHelper.PrepareAttributesForMorphTargets(_e, i, d),
            MaterialHelper.PrepareAttributesForBakedVertexAnimation(_e, i, d);
            var et = "default"
              , tt = ["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"]
              , rt = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler", "boneSampler", "morphTargets", "oitDepthSampler", "oitFrontColorSampler"]
              , it = ["Material", "Scene", "Mesh"];
            DetailMapConfiguration.AddUniforms(tt),
            DetailMapConfiguration.AddSamplers(rt),
            PrePassConfiguration.AddUniforms(tt),
            PrePassConfiguration.AddSamplers(rt),
            ImageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms(tt, d),
            ImageProcessingConfiguration.PrepareSamplers(rt, d)),
            MaterialHelper.PrepareUniformsAndSamplersList({
                uniformsNames: tt,
                uniformBuffersNames: it,
                samplers: rt,
                defines: d,
                maxSimultaneousLights: this._maxSimultaneousLights
            });
            var nt = {};
            this.customShaderNameResolve && (et = this.customShaderNameResolve(et, tt, it, rt, d, _e, nt));
            var ot = d.toString()
              , at = o.effect
              , st = c.getEngine().createEffect(et, {
                attributes: _e,
                uniformsNames: tt,
                uniformBuffersNames: it,
                samplers: rt,
                defines: ot,
                fallbacks: $,
                onCompiled: this.onCompiled,
                onError: this.onError,
                indexParameters: {
                    maxSimultaneousLights: this._maxSimultaneousLights,
                    maxSimultaneousMorphTargets: d.NUM_MORPH_INFLUENCERS
                },
                processFinalCode: nt.processFinalCode,
                multiTarget: d.PREPASS
            }, _);
            if (st)
                if (this._onEffectCreatedObservable && (onCreatedEffectParameters$2.effect = st,
                onCreatedEffectParameters$2.subMesh = o,
                this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$2)),
                this.allowShaderHotSwapping && at && !st.isReady()) {
                    if (st = at,
                    d.markAsUnprocessed(),
                    j)
                        return d._areLightsDisposed = !0,
                        !1
                } else
                    c.resetCachedMaterial(),
                    o.setEffect(st, d, this._materialContext)
        }
        return !o.effect || !o.effect.isReady() ? !1 : (d._renderId = c.getRenderId(),
        o.effect._wasPreviouslyReady = !0,
        !0)
    }
    ,
    e.prototype.buildUniformLayout = function() {
        var i = this._uniformBuffer;
        i.addUniform("diffuseLeftColor", 4),
        i.addUniform("diffuseRightColor", 4),
        i.addUniform("opacityParts", 4),
        i.addUniform("reflectionLeftColor", 4),
        i.addUniform("reflectionRightColor", 4),
        i.addUniform("refractionLeftColor", 4),
        i.addUniform("refractionRightColor", 4),
        i.addUniform("emissiveLeftColor", 4),
        i.addUniform("emissiveRightColor", 4),
        i.addUniform("vDiffuseInfos", 2),
        i.addUniform("vAmbientInfos", 2),
        i.addUniform("vOpacityInfos", 2),
        i.addUniform("vReflectionInfos", 2),
        i.addUniform("vReflectionPosition", 3),
        i.addUniform("vReflectionSize", 3),
        i.addUniform("vEmissiveInfos", 2),
        i.addUniform("vLightmapInfos", 2),
        i.addUniform("vSpecularInfos", 2),
        i.addUniform("vBumpInfos", 3),
        i.addUniform("diffuseMatrix", 16),
        i.addUniform("ambientMatrix", 16),
        i.addUniform("opacityMatrix", 16),
        i.addUniform("reflectionMatrix", 16),
        i.addUniform("emissiveMatrix", 16),
        i.addUniform("lightmapMatrix", 16),
        i.addUniform("specularMatrix", 16),
        i.addUniform("bumpMatrix", 16),
        i.addUniform("vTangentSpaceParams", 2),
        i.addUniform("pointSize", 1),
        i.addUniform("alphaCutOff", 1),
        i.addUniform("refractionMatrix", 16),
        i.addUniform("vRefractionInfos", 4),
        i.addUniform("vRefractionPosition", 3),
        i.addUniform("vRefractionSize", 3),
        i.addUniform("vSpecularColor", 4),
        i.addUniform("vEmissiveColor", 3),
        i.addUniform("vDiffuseColor", 4),
        i.addUniform("vAmbientColor", 3),
        DetailMapConfiguration.PrepareUniformBuffer(i),
        i.create()
    }
    ,
    e.prototype.unbind = function() {
        if (this._activeEffect && !this.getScene().getEngine()._features.needToAlwaysBindUniformBuffers) {
            var i = !1;
            this._reflectionTexture && this._reflectionTexture.isRenderTarget && (this._activeEffect.setTexture("reflection2DSampler", null),
            i = !0),
            this._refractionTexture && this._refractionTexture.isRenderTarget && (this._activeEffect.setTexture("refraction2DSampler", null),
            i = !0),
            i && this._markAllSubMeshesAsTexturesDirty()
        }
        a.prototype.unbind.call(this)
    }
    ,
    e.prototype.bindForSubMesh = function(i, o, s) {
        var c, d = this.getScene(), _ = s.materialDefines;
        if (!!_) {
            var b = s.effect;
            if (!!b) {
                this._activeEffect = b,
                o.getMeshUniformBuffer().bindToEffect(b, "Mesh"),
                o.transferToEffect(i),
                this.prePassConfiguration.bindForSubMesh(this._activeEffect, d, o, i, this.isFrozen),
                _.OBJECTSPACE_NORMALMAP && (i.toNormalMatrix(this._normalMatrix),
                this.bindOnlyNormalMatrix(this._normalMatrix));
                var k = this._mustRebind(d, b, o.visibility);
                MaterialHelper.BindBonesParameters(o, b);
                var j = this._uniformBuffer;
                if (k) {
                    if (j.bindToEffect(b, "Material"),
                    this.bindViewProjection(b),
                    !j.useUbo || !this.isFrozen || !j.isSync) {
                        if (e.FresnelEnabled && _.FRESNEL && (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled && (j.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power),
                        j.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias)),
                        this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled && j.updateColor4("opacityParts", new Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power),
                        this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled && (j.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power),
                        j.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias)),
                        this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled && (j.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power),
                        j.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias)),
                        this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled && (j.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power),
                        j.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias))),
                        d.texturesEnabled) {
                            if (this._diffuseTexture && e.DiffuseTextureEnabled && (j.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level),
                            MaterialHelper.BindTextureMatrix(this._diffuseTexture, j, "diffuse")),
                            this._ambientTexture && e.AmbientTextureEnabled && (j.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level),
                            MaterialHelper.BindTextureMatrix(this._ambientTexture, j, "ambient")),
                            this._opacityTexture && e.OpacityTextureEnabled && (j.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level),
                            MaterialHelper.BindTextureMatrix(this._opacityTexture, j, "opacity")),
                            this._hasAlphaChannel() && j.updateFloat("alphaCutOff", this.alphaCutOff),
                            this._reflectionTexture && e.ReflectionTextureEnabled && (j.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness),
                            j.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix()),
                            this._reflectionTexture.boundingBoxSize)) {
                                var $ = this._reflectionTexture;
                                j.updateVector3("vReflectionPosition", $.boundingBoxPosition),
                                j.updateVector3("vReflectionSize", $.boundingBoxSize)
                            }
                            if (this._emissiveTexture && e.EmissiveTextureEnabled && (j.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level),
                            MaterialHelper.BindTextureMatrix(this._emissiveTexture, j, "emissive")),
                            this._lightmapTexture && e.LightmapTextureEnabled && (j.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level),
                            MaterialHelper.BindTextureMatrix(this._lightmapTexture, j, "lightmap")),
                            this._specularTexture && e.SpecularTextureEnabled && (j.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level),
                            MaterialHelper.BindTextureMatrix(this._specularTexture, j, "specular")),
                            this._bumpTexture && d.getEngine().getCaps().standardDerivatives && e.BumpTextureEnabled && (j.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1 / this._bumpTexture.level, this.parallaxScaleBias),
                            MaterialHelper.BindTextureMatrix(this._bumpTexture, j, "bump"),
                            d._mirroredCameraPosition ? j.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1 : -1, this._invertNormalMapY ? 1 : -1) : j.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1, this._invertNormalMapY ? -1 : 1)),
                            this._refractionTexture && e.RefractionTextureEnabled) {
                                var _e = 1;
                                if (this._refractionTexture.isCube || (j.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix()),
                                this._refractionTexture.depth && (_e = this._refractionTexture.depth)),
                                j.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, _e, this.invertRefractionY ? -1 : 1),
                                this._refractionTexture.boundingBoxSize) {
                                    var $ = this._refractionTexture;
                                    j.updateVector3("vRefractionPosition", $.boundingBoxPosition),
                                    j.updateVector3("vRefractionSize", $.boundingBoxSize)
                                }
                            }
                        }
                        this.pointsCloud && j.updateFloat("pointSize", this.pointSize),
                        _.SPECULARTERM && j.updateColor4("vSpecularColor", this.specularColor, this.specularPower),
                        j.updateColor3("vEmissiveColor", e.EmissiveTextureEnabled ? this.emissiveColor : Color3.BlackReadOnly),
                        j.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha),
                        d.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor),
                        j.updateColor3("vAmbientColor", this._globalAmbientColor)
                    }
                    if (d.texturesEnabled && (this._diffuseTexture && e.DiffuseTextureEnabled && b.setTexture("diffuseSampler", this._diffuseTexture),
                    this._ambientTexture && e.AmbientTextureEnabled && b.setTexture("ambientSampler", this._ambientTexture),
                    this._opacityTexture && e.OpacityTextureEnabled && b.setTexture("opacitySampler", this._opacityTexture),
                    this._reflectionTexture && e.ReflectionTextureEnabled && (this._reflectionTexture.isCube ? b.setTexture("reflectionCubeSampler", this._reflectionTexture) : b.setTexture("reflection2DSampler", this._reflectionTexture)),
                    this._emissiveTexture && e.EmissiveTextureEnabled && b.setTexture("emissiveSampler", this._emissiveTexture),
                    this._lightmapTexture && e.LightmapTextureEnabled && b.setTexture("lightmapSampler", this._lightmapTexture),
                    this._specularTexture && e.SpecularTextureEnabled && b.setTexture("specularSampler", this._specularTexture),
                    this._bumpTexture && d.getEngine().getCaps().standardDerivatives && e.BumpTextureEnabled && b.setTexture("bumpSampler", this._bumpTexture),
                    this._refractionTexture && e.RefractionTextureEnabled)) {
                        var _e = 1;
                        this._refractionTexture.isCube ? b.setTexture("refractionCubeSampler", this._refractionTexture) : b.setTexture("refraction2DSampler", this._refractionTexture)
                    }
                    this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(o) && this.getScene().depthPeelingRenderer.bind(b),
                    this.detailMap.bindForSubMesh(j, d, this.isFrozen),
                    MaterialHelper.BindClipPlane(b, d),
                    this.bindEyePosition(b)
                } else
                    d.getEngine()._features.needToAlwaysBindUniformBuffers && (j.bindToEffect(b, "Material"),
                    this._needToBindSceneUbo = !0);
                (k || !this.isFrozen) && (d.lightsEnabled && !this._disableLighting && MaterialHelper.BindLights(d, o, b, _, this._maxSimultaneousLights),
                (d.fogEnabled && o.applyFog && d.fogMode !== Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture || o.receiveShadows) && this.bindView(b),
                MaterialHelper.BindFogParameters(d, o, b),
                _.NUM_MORPH_INFLUENCERS && MaterialHelper.BindMorphTargetParameters(o, b),
                _.BAKED_VERTEX_ANIMATION_TEXTURE && ((c = o.bakedVertexAnimationManager) === null || c === void 0 || c.bind(b, _.INSTANCES)),
                this.useLogarithmicDepth && MaterialHelper.BindLogDepth(_, b, d),
                this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess && this._imageProcessingConfiguration.bind(this._activeEffect)),
                this._afterBind(o, this._activeEffect),
                j.update()
            }
        }
    }
    ,
    e.prototype.getAnimatables = function() {
        var i = [];
        return this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0 && i.push(this._diffuseTexture),
        this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0 && i.push(this._ambientTexture),
        this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0 && i.push(this._opacityTexture),
        this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0 && i.push(this._reflectionTexture),
        this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0 && i.push(this._emissiveTexture),
        this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0 && i.push(this._specularTexture),
        this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0 && i.push(this._bumpTexture),
        this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0 && i.push(this._lightmapTexture),
        this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0 && i.push(this._refractionTexture),
        this.detailMap.getAnimatables(i),
        i
    }
    ,
    e.prototype.getActiveTextures = function() {
        var i = a.prototype.getActiveTextures.call(this);
        return this._diffuseTexture && i.push(this._diffuseTexture),
        this._ambientTexture && i.push(this._ambientTexture),
        this._opacityTexture && i.push(this._opacityTexture),
        this._reflectionTexture && i.push(this._reflectionTexture),
        this._emissiveTexture && i.push(this._emissiveTexture),
        this._specularTexture && i.push(this._specularTexture),
        this._bumpTexture && i.push(this._bumpTexture),
        this._lightmapTexture && i.push(this._lightmapTexture),
        this._refractionTexture && i.push(this._refractionTexture),
        this.detailMap.getActiveTextures(i),
        i
    }
    ,
    e.prototype.hasTexture = function(i) {
        return !!(a.prototype.hasTexture.call(this, i) || this._diffuseTexture === i || this._ambientTexture === i || this._opacityTexture === i || this._reflectionTexture === i || this._emissiveTexture === i || this._specularTexture === i || this._bumpTexture === i || this._lightmapTexture === i || this._refractionTexture === i || this.detailMap.hasTexture(i))
    }
    ,
    e.prototype.dispose = function(i, o) {
        var s, c, d, _, b, k, j, $, _e;
        o && ((s = this._diffuseTexture) === null || s === void 0 || s.dispose(),
        (c = this._ambientTexture) === null || c === void 0 || c.dispose(),
        (d = this._opacityTexture) === null || d === void 0 || d.dispose(),
        (_ = this._reflectionTexture) === null || _ === void 0 || _.dispose(),
        (b = this._emissiveTexture) === null || b === void 0 || b.dispose(),
        (k = this._specularTexture) === null || k === void 0 || k.dispose(),
        (j = this._bumpTexture) === null || j === void 0 || j.dispose(),
        ($ = this._lightmapTexture) === null || $ === void 0 || $.dispose(),
        (_e = this._refractionTexture) === null || _e === void 0 || _e.dispose()),
        this.detailMap.dispose(o),
        this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        a.prototype.dispose.call(this, i, o)
    }
    ,
    e.prototype.clone = function(i) {
        var o = this
          , s = SerializationHelper.Clone(function() {
            return new e(i,o.getScene())
        }, this);
        return s.name = i,
        s.id = i,
        this.stencil.copyTo(s.stencil),
        s
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        return i.stencil = this.stencil.serialize(),
        i
    }
    ,
    e.Parse = function(i, o, s) {
        var c = SerializationHelper.Parse(function() {
            return new e(i.name,o)
        }, i, o, s);
        return i.stencil && c.stencil.parse(i.stencil, o, s),
        c
    }
    ,
    Object.defineProperty(e, "DiffuseTextureEnabled", {
        get: function() {
            return MaterialFlags.DiffuseTextureEnabled
        },
        set: function(i) {
            MaterialFlags.DiffuseTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "DetailTextureEnabled", {
        get: function() {
            return MaterialFlags.DetailTextureEnabled
        },
        set: function(i) {
            MaterialFlags.DetailTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "AmbientTextureEnabled", {
        get: function() {
            return MaterialFlags.AmbientTextureEnabled
        },
        set: function(i) {
            MaterialFlags.AmbientTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "OpacityTextureEnabled", {
        get: function() {
            return MaterialFlags.OpacityTextureEnabled
        },
        set: function(i) {
            MaterialFlags.OpacityTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "ReflectionTextureEnabled", {
        get: function() {
            return MaterialFlags.ReflectionTextureEnabled
        },
        set: function(i) {
            MaterialFlags.ReflectionTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "EmissiveTextureEnabled", {
        get: function() {
            return MaterialFlags.EmissiveTextureEnabled
        },
        set: function(i) {
            MaterialFlags.EmissiveTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "SpecularTextureEnabled", {
        get: function() {
            return MaterialFlags.SpecularTextureEnabled
        },
        set: function(i) {
            MaterialFlags.SpecularTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "BumpTextureEnabled", {
        get: function() {
            return MaterialFlags.BumpTextureEnabled
        },
        set: function(i) {
            MaterialFlags.BumpTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "LightmapTextureEnabled", {
        get: function() {
            return MaterialFlags.LightmapTextureEnabled
        },
        set: function(i) {
            MaterialFlags.LightmapTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "RefractionTextureEnabled", {
        get: function() {
            return MaterialFlags.RefractionTextureEnabled
        },
        set: function(i) {
            MaterialFlags.RefractionTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "ColorGradingTextureEnabled", {
        get: function() {
            return MaterialFlags.ColorGradingTextureEnabled
        },
        set: function(i) {
            MaterialFlags.ColorGradingTextureEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "FresnelEnabled", {
        get: function() {
            return MaterialFlags.FresnelEnabled
        },
        set: function(i) {
            MaterialFlags.FresnelEnabled = i
        },
        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(a) {
    return new StandardMaterial("default material",a)
}
;
var CubeTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it) {
        s === void 0 && (s = null),
        c === void 0 && (c = !1),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        b === void 0 && (b = null),
        k === void 0 && (k = 5),
        j === void 0 && (j = !1),
        $ === void 0 && ($ = null),
        _e === void 0 && (_e = !1),
        et === void 0 && (et = .8),
        tt === void 0 && (tt = 0);
        var nt, ot = a.call(this, o) || this;
        return ot._lodScale = .8,
        ot._lodOffset = 0,
        ot.onLoadObservable = new Observable,
        ot.boundingBoxPosition = Vector3.Zero(),
        ot._rotationY = 0,
        ot._files = null,
        ot._forcedExtension = null,
        ot._extensions = null,
        ot.name = i,
        ot.url = i,
        ot._noMipmap = c,
        ot.hasAlpha = !1,
        ot._format = k,
        ot.isCube = !0,
        ot._textureMatrix = Matrix.Identity(),
        ot._createPolynomials = _e,
        ot.coordinatesMode = Texture.CUBIC_MODE,
        ot._extensions = s,
        ot._files = d,
        ot._forcedExtension = $,
        ot._loaderOptions = rt,
        ot._useSRGBBuffer = it,
        ot._lodScale = et,
        ot._lodOffset = tt,
        !i && !d || ot.updateURL(i, $, _, j, b, s, (nt = ot.getScene()) === null || nt === void 0 ? void 0 : nt.useDelayedTextureLoading, d),
        ot
    }
    return Object.defineProperty(e.prototype, "boundingBoxSize", {
        get: function() {
            return this._boundingBoxSize
        },
        set: function(i) {
            if (!(this._boundingBoxSize && this._boundingBoxSize.equals(i))) {
                this._boundingBoxSize = i;
                var o = this.getScene();
                o && o.markAllMaterialsAsDirty(1)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotationY", {
        get: function() {
            return this._rotationY
        },
        set: function(i) {
            this._rotationY = i,
            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(i, o, s) {
        var c = "";
        return i.forEach(function(d) {
            return c += d
        }),
        new e(c,o,null,s,i)
    }
    ,
    e.CreateFromPrefilteredData = function(i, o, s, c) {
        s === void 0 && (s = null),
        c === void 0 && (c = !0);
        var d = o.useDelayedTextureLoading;
        o.useDelayedTextureLoading = !1;
        var _ = new e(i,o,null,!1,null,null,null,void 0,!0,s,c);
        return o.useDelayedTextureLoading = d,
        _
    }
    ,
    e.prototype.getClassName = function() {
        return "CubeTexture"
    }
    ,
    e.prototype.updateURL = function(i, o, s, c, d, _, b, k) {
        s === void 0 && (s = null),
        c === void 0 && (c = !1),
        d === void 0 && (d = null),
        _ === void 0 && (_ = null),
        b === void 0 && (b = !1),
        k === void 0 && (k = null),
        (!this.name || StartsWith(this.name, "data:")) && (this.name = i),
        this.url = i;
        var j = i.lastIndexOf(".")
          , $ = o || (j > -1 ? i.substring(j).toLowerCase() : "")
          , _e = $.indexOf(".dds") === 0
          , et = $.indexOf(".env") === 0;
        if (et ? (this.gammaSpace = !1,
        this._prefiltered = !1,
        this.anisotropicFilteringLevel = 1) : (this._prefiltered = c,
        c && (this.gammaSpace = !1,
        this.anisotropicFilteringLevel = 1)),
        k)
            this._files = k;
        else if (!et && !_e && !_ && (_ = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"]),
        this._files = this._files || [],
        this._files.length = 0,
        _) {
            for (var tt = 0; tt < _.length; tt++)
                this._files.push(i + _[tt]);
            this._extensions = _
        }
        b ? (this.delayLoadState = 4,
        this._delayedOnLoad = s,
        this._delayedOnError = d) : this._loadTexture(s, d)
    }
    ,
    e.prototype.delayLoad = function(i) {
        this.delayLoadState === 4 && (i && (this._forcedExtension = i),
        this.delayLoadState = 1,
        this._loadTexture(this._delayedOnLoad, this._delayedOnError))
    }
    ,
    e.prototype.getReflectionTextureMatrix = function() {
        return this._textureMatrix
    }
    ,
    e.prototype.setReflectionTextureMatrix = function(i) {
        var o = this, s;
        i.updateFlag !== this._textureMatrix.updateFlag && (i.isIdentity() !== this._textureMatrix.isIdentity() && ((s = this.getScene()) === null || s === void 0 || s.markAllMaterialsAsDirty(1, function(c) {
            return c.getActiveTextures().indexOf(o) !== -1
        })),
        this._textureMatrix = i)
    }
    ,
    e.prototype._loadTexture = function(i, o) {
        var s = this, c;
        i === void 0 && (i = null),
        o === void 0 && (o = null);
        var d = this.getScene()
          , _ = this._texture;
        this._texture = this._getFromCache(this.url, this._noMipmap, void 0, void 0, this._useSRGBBuffer);
        var b = function() {
            var j;
            s.onLoadObservable.notifyObservers(s),
            _ && (_.dispose(),
            (j = s.getScene()) === null || j === void 0 || j.markAllMaterialsAsDirty(1)),
            i && i()
        }
          , k = function(j, $) {
            s._loadingError = !0,
            s._errorObject = {
                message: j,
                exception: $
            },
            o && o(j, $),
            Texture.OnTextureLoadErrorObservable.notifyObservers(s)
        };
        this._texture ? this._texture.isReady ? Tools.SetImmediate(function() {
            return b()
        }) : this._texture.onLoadedObservable.add(function() {
            return b()
        }) : (this._prefiltered ? this._texture = this._getEngine().createPrefilteredCubeTexture(this.url, d, this._lodScale, this._lodOffset, i, k, this._format, this._forcedExtension, this._createPolynomials) : this._texture = this._getEngine().createCubeTexture(this.url, d, this._files, this._noMipmap, i, k, this._format, this._forcedExtension, !1, this._lodScale, this._lodOffset, null, this._loaderOptions, !!this._useSRGBBuffer),
        (c = this._texture) === null || c === void 0 || c.onLoadedObservable.add(function() {
            return s.onLoadObservable.notifyObservers(s)
        }))
    }
    ,
    e.Parse = function(i, o, s) {
        var c = SerializationHelper.Parse(function() {
            var k = !1;
            return i.prefiltered && (k = i.prefiltered),
            new e(s + i.name,o,i.extensions,!1,i.files || null,null,null,void 0,k,i.forcedExtension)
        }, i, o);
        if (i.boundingBoxPosition && (c.boundingBoxPosition = Vector3.FromArray(i.boundingBoxPosition)),
        i.boundingBoxSize && (c.boundingBoxSize = Vector3.FromArray(i.boundingBoxSize)),
        i.animations)
            for (var d = 0; d < i.animations.length; d++) {
                var _ = i.animations[d]
                  , b = GetClass("BABYLON.Animation");
                b && c.animations.push(b.Parse(_))
            }
        return c
    }
    ,
    e.prototype.clone = function() {
        var i = this
          , o = 0
          , s = SerializationHelper.Clone(function() {
            var c = new e(i.url,i.getScene() || i._getEngine(),i._extensions,i._noMipmap,i._files);
            return o = c.uniqueId,
            c
        }, this);
        return s.uniqueId = o,
        s
    }
    ,
    __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);
var DynamicTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b) {
        s === void 0 && (s = null),
        c === void 0 && (c = !1),
        d === void 0 && (d = 3),
        _ === void 0 && (_ = 5);
        var k = a.call(this, null, s, !c, b, d, void 0, void 0, void 0, void 0, _) || this;
        k.name = i,
        k.wrapU = Texture.CLAMP_ADDRESSMODE,
        k.wrapV = Texture.CLAMP_ADDRESSMODE,
        k._generateMipMaps = c;
        var j = k._getEngine();
        if (!j)
            return k;
        o.getContext ? (k._canvas = o,
        k._texture = j.createDynamicTexture(o.width, o.height, c, d)) : (k._canvas = j.createCanvas(1, 1),
        o.width || o.width === 0 ? k._texture = j.createDynamicTexture(o.width, o.height, c, d) : k._texture = j.createDynamicTexture(o, o, c, d));
        var $ = k.getSize();
        return k._canvas.width !== $.width && (k._canvas.width = $.width),
        k._canvas.height !== $.height && (k._canvas.height = $.height),
        k._context = k._canvas.getContext("2d"),
        k
    }
    return e.prototype.getClassName = function() {
        return "DynamicTexture"
    }
    ,
    Object.defineProperty(e.prototype, "canRescale", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._recreate = function(i) {
        this._canvas.width = i.width,
        this._canvas.height = i.height,
        this.releaseInternalTexture(),
        this._texture = this._getEngine().createDynamicTexture(i.width, i.height, this._generateMipMaps, this.samplingMode)
    }
    ,
    e.prototype.scale = function(i) {
        var o = this.getSize();
        o.width *= i,
        o.height *= i,
        this._recreate(o)
    }
    ,
    e.prototype.scaleTo = function(i, o) {
        var s = this.getSize();
        s.width = i,
        s.height = o,
        this._recreate(s)
    }
    ,
    e.prototype.getContext = function() {
        return this._context
    }
    ,
    e.prototype.clear = function() {
        var i = this.getSize();
        this._context.fillRect(0, 0, i.width, i.height)
    }
    ,
    e.prototype.update = function(i, o, s) {
        o === void 0 && (o = !1),
        s === void 0 && (s = !1),
        this._getEngine().updateDynamicTexture(this._texture, this._canvas, i === void 0 ? !0 : i, o, this._format || void 0, void 0, s)
    }
    ,
    e.prototype.drawText = function(i, o, s, c, d, _, b, k) {
        k === void 0 && (k = !0);
        var j = this.getSize();
        if (_ && (this._context.fillStyle = _,
        this._context.fillRect(0, 0, j.width, j.height)),
        this._context.font = c,
        o == null) {
            var $ = this._context.measureText(i);
            o = (j.width - $.width) / 2
        }
        if (s == null) {
            var _e = parseInt(c.replace(/\D/g, ""));
            s = j.height / 2 + _e / 3.65
        }
        this._context.fillStyle = d || "",
        this._context.fillText(i, o, s),
        k && this.update(b)
    }
    ,
    e.prototype.clone = function() {
        var i = this.getScene();
        if (!i)
            return this;
        var o = this.getSize()
          , s = new e(this.name,o,i,this._generateMipMaps);
        return s.hasAlpha = this.hasAlpha,
        s.level = this.level,
        s.wrapU = this.wrapU,
        s.wrapV = this.wrapV,
        s
    }
    ,
    e.prototype.serialize = function() {
        var i = this.getScene();
        i && !i.isReady() && Logger$2.Warn("The scene must be ready before serializing the dynamic texture");
        var o = a.prototype.serialize.call(this);
        return this._IsCanvasElement(this._canvas) && (o.base64String = this._canvas.toDataURL()),
        o.invertY = this._invertY,
        o.samplingMode = this.samplingMode,
        o
    }
    ,
    e.prototype._IsCanvasElement = function(i) {
        return i.toDataURL !== void 0
    }
    ,
    e.prototype._rebuild = function() {
        this.update()
    }
    ,
    e
}(Texture)
  , VideoTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        c === void 0 && (c = !1),
        d === void 0 && (d = !1),
        _ === void 0 && (_ = Texture.TRILINEAR_SAMPLINGMODE);
        var j = a.call(this, null, s, !c, d) || this;
        j._onUserActionRequestedObservable = null,
        j._stillImageCaptured = !1,
        j._displayingPosterTexture = !1,
        j._frameId = -1,
        j._currentSrc = null,
        j._errorFound = !1,
        j._createInternalTexture = function() {
            if (j._texture != null)
                if (j._displayingPosterTexture)
                    j._texture.dispose(),
                    j._displayingPosterTexture = !1;
                else
                    return;
            if (!j._getEngine().needPOTTextures || Tools.IsExponentOfTwo(j.video.videoWidth) && Tools.IsExponentOfTwo(j.video.videoHeight) ? (j.wrapU = Texture.WRAP_ADDRESSMODE,
            j.wrapV = Texture.WRAP_ADDRESSMODE) : (j.wrapU = Texture.CLAMP_ADDRESSMODE,
            j.wrapV = Texture.CLAMP_ADDRESSMODE,
            j._generateMipMaps = !1),
            j._texture = j._getEngine().createDynamicTexture(j.video.videoWidth, j.video.videoHeight, j._generateMipMaps, j.samplingMode),
            !j.video.autoplay && !j._settings.poster) {
                var _e = j.video.onplaying
                  , et = j.video.muted;
                j.video.muted = !0,
                j.video.onplaying = function() {
                    j.video.muted = et,
                    j.video.onplaying = _e,
                    j._updateInternalTexture(),
                    j._errorFound || j.video.pause(),
                    j.onLoadObservable.hasObservers() && j.onLoadObservable.notifyObservers(j)
                }
                ,
                j._handlePlay()
            } else
                j._updateInternalTexture(),
                j.onLoadObservable.hasObservers() && j.onLoadObservable.notifyObservers(j)
        }
        ,
        j.reset = function() {
            j._texture != null && (j._displayingPosterTexture || (j._texture.dispose(),
            j._texture = null))
        }
        ,
        j._updateInternalTexture = function() {
            if (j._texture != null && !(j.video.readyState < j.video.HAVE_CURRENT_DATA) && !j._displayingPosterTexture) {
                var _e = j.getScene().getFrameId();
                j._frameId !== _e && (j._frameId = _e,
                j._getEngine().updateVideoTexture(j._texture, j.video, j._invertY))
            }
        }
        ,
        b || (b = {
            autoPlay: !0,
            loop: !0,
            autoUpdateTexture: !0
        }),
        j._onError = k,
        j._generateMipMaps = c,
        j._initialSamplingMode = _,
        j.autoUpdateTexture = b.autoUpdateTexture,
        j._currentSrc = o,
        j.name = i || j._getName(o),
        j.video = j._getVideo(o),
        j._settings = b,
        b.poster && (j.video.poster = b.poster),
        b.autoPlay !== void 0 && (j.video.autoplay = b.autoPlay),
        b.loop !== void 0 && (j.video.loop = b.loop),
        b.muted !== void 0 && (j.video.muted = b.muted),
        j.video.setAttribute("playsinline", ""),
        j.video.addEventListener("paused", j._updateInternalTexture),
        j.video.addEventListener("seeked", j._updateInternalTexture),
        j.video.addEventListener("emptied", j.reset),
        j._createInternalTextureOnEvent = b.poster && !b.autoPlay ? "play" : "canplay",
        j.video.addEventListener(j._createInternalTextureOnEvent, j._createInternalTexture),
        b.autoPlay && j._handlePlay();
        var $ = j.video.readyState >= j.video.HAVE_CURRENT_DATA;
        return b.poster && (!b.autoPlay || !$) ? (j._texture = j._getEngine().createTexture(b.poster, !1, !j.invertY, s),
        j._displayingPosterTexture = !0) : $ && j._createInternalTexture(),
        j
    }
    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(i) {
        this._errorFound = !0,
        this._onError ? this._onError(i == null ? void 0 : i.message) : Logger$2.Error(i == null ? void 0 : i.message)
    }
    ,
    e.prototype._handlePlay = function() {
        var i = this;
        this._errorFound = !1,
        this.video.play().catch(function(o) {
            if ((o == null ? void 0 : o.name) === "NotAllowedError") {
                if (i._onUserActionRequestedObservable && i._onUserActionRequestedObservable.hasObservers()) {
                    i._onUserActionRequestedObservable.notifyObservers(i);
                    return
                } else if (!i.video.muted) {
                    Logger$2.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),
                    i.video.muted = !0,
                    i._errorFound = !1,
                    i.video.play().catch(function(s) {
                        i._processError(s)
                    });
                    return
                }
            }
            i._processError(o)
        })
    }
    ,
    e.prototype.getClassName = function() {
        return "VideoTexture"
    }
    ,
    e.prototype._getName = function(i) {
        return i instanceof HTMLVideoElement ? i.currentSrc : typeof i == "object" ? i.toString() : i
    }
    ,
    e.prototype._getVideo = function(i) {
        if (i.isNative)
            return i;
        if (i instanceof HTMLVideoElement)
            return Tools.SetCorsBehavior(i.currentSrc, i),
            i;
        var o = document.createElement("video");
        return typeof i == "string" ? (Tools.SetCorsBehavior(i, o),
        o.src = i) : (Tools.SetCorsBehavior(i[0], o),
        i.forEach(function(s) {
            var c = document.createElement("source");
            c.src = s,
            o.appendChild(c)
        })),
        o
    }
    ,
    e.prototype._rebuild = function() {
        this.update()
    }
    ,
    e.prototype.update = function() {
        !this.autoUpdateTexture || this.updateTexture(!0)
    }
    ,
    e.prototype.updateTexture = function(i) {
        !i || this.video.paused && this._stillImageCaptured || (this._stillImageCaptured = !0,
        this._updateInternalTexture())
    }
    ,
    e.prototype.updateURL = function(i) {
        this.video.src = i,
        this._currentSrc = i
    }
    ,
    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() {
        a.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(i, o, s, c) {
        c === void 0 && (c = !0);
        var d = i.getEngine().createVideoElement(s);
        return i.getEngine()._badOS && (document.body.appendChild(d),
        d.style.transform = "scale(0.0001, 0.0001)",
        d.style.opacity = "0",
        d.style.position = "fixed",
        d.style.bottom = "0px",
        d.style.right = "0px"),
        d.setAttribute("autoplay", ""),
        d.setAttribute("muted", "true"),
        d.setAttribute("playsinline", ""),
        d.muted = !0,
        d.mozSrcObject !== void 0 ? d.mozSrcObject = o : typeof d.srcObject == "object" ? d.srcObject = o : (window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL,
        d.src = window.URL && window.URL.createObjectURL(o)),
        new Promise(function(_) {
            var b = function() {
                _(new e("video",d,i,!0,c)),
                d.removeEventListener("playing", b)
            };
            d.addEventListener("playing", b),
            d.play()
        }
        )
    }
    ,
    e.CreateFromWebCamAsync = function(i, o, s, c) {
        var d = this;
        s === void 0 && (s = !1),
        c === void 0 && (c = !0);
        var _;
        if (o && o.deviceId && (_ = {
            exact: o.deviceId
        }),
        navigator.mediaDevices)
            return navigator.mediaDevices.getUserMedia({
                video: o,
                audio: s
            }).then(function(k) {
                return d.CreateFromStreamAsync(i, k, o, c)
            });
        var b = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
        return b && b({
            video: {
                deviceId: _,
                width: {
                    min: o && o.minWidth || 256,
                    max: o && o.maxWidth || 640
                },
                height: {
                    min: o && o.minHeight || 256,
                    max: o && o.maxHeight || 480
                }
            },
            audio: s
        }, function(k) {
            return d.CreateFromStreamAsync(i, k, o, c)
        }, function(k) {
            Logger$2.Error(k.name)
        }),
        Promise.reject("No support for userMedia on this device")
    }
    ,
    e.CreateFromWebCam = function(i, o, s, c, d) {
        c === void 0 && (c = !1),
        d === void 0 && (d = !0),
        this.CreateFromWebCamAsync(i, s, c, d).then(function(_) {
            o && o(_)
        }).catch(function(_) {
            Logger$2.Error(_.name)
        })
    }
    ,
    e
}(Texture)
  , Action = function() {
    function a(e, i) {
        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 = i
    }
    return a.prototype._prepare = function() {}
    ,
    a.prototype.getTriggerParameter = function() {
        return this._triggerParameter
    }
    ,
    a.prototype.setTriggerParameter = function(e) {
        this._triggerParameter = e
    }
    ,
    a.prototype._evaluateConditionForCurrentFrame = function() {
        var e = this._condition;
        if (!e)
            return !0;
        var i = this._actionManager.getScene().getRenderId();
        return e._evaluationId !== i && (e._evaluationId = i,
        e._currentResult = e.isValid()),
        e._currentResult
    }
    ,
    a.prototype._executeCurrent = function(e) {
        var i = this._evaluateConditionForCurrentFrame();
        !i || (this.onBeforeExecuteObservable.notifyObservers(this),
        this._nextActiveAction.execute(e),
        this.skipToNextActiveAction())
    }
    ,
    a.prototype.execute = function(e) {}
    ,
    a.prototype.skipToNextActiveAction = function() {
        this._nextActiveAction._child ? (this._nextActiveAction._child._actionManager || (this._nextActiveAction._child._actionManager = this._actionManager),
        this._nextActiveAction = this._nextActiveAction._child) : this._nextActiveAction = this
    }
    ,
    a.prototype.then = function(e) {
        return this._child = e,
        e._actionManager = this._actionManager,
        e._prepare(),
        e
    }
    ,
    a.prototype._getProperty = function(e) {
        return this._actionManager._getProperty(e)
    }
    ,
    a.prototype._getEffectiveTarget = function(e, i) {
        return this._actionManager._getEffectiveTarget(e, i)
    }
    ,
    a.prototype.serialize = function(e) {}
    ,
    a.prototype._serialize = function(e, i) {
        var o = {
            type: 1,
            children: [],
            name: e.name,
            properties: e.properties || []
        };
        if (this._child && this._child.serialize(o),
        this._condition) {
            var s = this._condition.serialize();
            return s.children.push(o),
            i && i.children.push(s),
            s
        }
        return i && i.children.push(o),
        o
    }
    ,
    a._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
    }
    ,
    a._GetTargetProperty = function(e) {
        return {
            name: "target",
            targetType: e._isMesh ? "MeshProperties" : e._isLight ? "LightProperties" : e._isCamera ? "CameraProperties" : "SceneProperties",
            value: e._isScene ? "Scene" : e.name
        }
    }
    ,
    a
}();
RegisterClass("BABYLON.Action", Action);
var Condition = function() {
    function a(e) {
        this._actionManager = e
    }
    return a.prototype.isValid = function() {
        return !0
    }
    ,
    a.prototype._getProperty = function(e) {
        return this._actionManager._getProperty(e)
    }
    ,
    a.prototype._getEffectiveTarget = function(e, i) {
        return this._actionManager._getEffectiveTarget(e, i)
    }
    ,
    a.prototype.serialize = function() {}
    ,
    a.prototype._serialize = function(e) {
        return {
            type: 2,
            children: [],
            name: e.name,
            properties: e.properties
        }
    }
    ,
    a
}()
  , ValueCondition = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        d === void 0 && (d = e.IsEqual);
        var _ = a.call(this, i) || this;
        return _.propertyPath = s,
        _.value = c,
        _.operator = d,
        _._target = o,
        _._effectiveTarget = _._getEffectiveTarget(o, _.propertyPath),
        _._property = _._getProperty(_.propertyPath),
        _
    }
    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 i;
            return this.value.equals ? i = this.value.equals(this._effectiveTarget[this._property]) : i = this.value === this._effectiveTarget[this._property],
            this.operator === e.IsEqual ? i : !i
        }
        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(i) {
        switch (i) {
        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(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i) || this;
        return s.predicate = o,
        s
    }
    return e.prototype.isValid = function() {
        return this.predicate()
    }
    ,
    e
}(Condition)
  , StateCondition = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i) || this;
        return c.value = s,
        c._target = o,
        c
    }
    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(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        var d = a.call(this, i, c) || this;
        return d.propertyPath = s,
        d._target = d._effectiveTarget = o,
        d
    }
    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(i) {
        return a.prototype._serialize.call(this, {
            name: "SwitchBooleanAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "propertyPath",
                value: this.propertyPath
            }]
        }, i)
    }
    ,
    e
}
)(Action);
var SetStateAction = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        var d = a.call(this, i, c) || this;
        return d.value = s,
        d._target = o,
        d
    }
    return e.prototype.execute = function() {
        this._target.state = this.value
    }
    ,
    e.prototype.serialize = function(i) {
        return a.prototype._serialize.call(this, {
            name: "SetStateAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "value",
                value: this.value
            }]
        }, i)
    }
    ,
    e
}(Action)
  , SetValueAction = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        var _ = a.call(this, i, d) || this;
        return _.propertyPath = s,
        _.value = c,
        _._target = _._effectiveTarget = o,
        _
    }
    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(i) {
        return a.prototype._serialize.call(this, {
            name: "SetValueAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "propertyPath",
                value: this.propertyPath
            }, {
                name: "value",
                value: Action._SerializeValueAsString(this.value)
            }]
        }, i)
    }
    ,
    e
}(Action)
  , IncrementValueAction = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        var _ = a.call(this, i, d) || this;
        return _.propertyPath = s,
        _.value = c,
        _._target = _._effectiveTarget = o,
        _
    }
    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(i) {
        return a.prototype._serialize.call(this, {
            name: "IncrementValueAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "propertyPath",
                value: this.propertyPath
            }, {
                name: "value",
                value: Action._SerializeValueAsString(this.value)
            }]
        }, i)
    }
    ,
    e
}(Action)
  , PlayAnimationAction = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _) {
        var b = a.call(this, i, _) || this;
        return b.from = s,
        b.to = c,
        b.loop = d,
        b._target = o,
        b
    }
    return e.prototype._prepare = function() {}
    ,
    e.prototype.execute = function() {
        var i = this._actionManager.getScene();
        i.beginAnimation(this._target, this.from, this.to, this.loop)
    }
    ,
    e.prototype.serialize = function(i) {
        return a.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
            }]
        }, i)
    }
    ,
    e
}(Action)
  , StopAnimationAction = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, s) || this;
        return c._target = o,
        c
    }
    return e.prototype._prepare = function() {}
    ,
    e.prototype.execute = function() {
        var i = this._actionManager.getScene();
        i.stopAnimation(this._target)
    }
    ,
    e.prototype.serialize = function(i) {
        return a.prototype._serialize.call(this, {
            name: "StopAnimationAction",
            properties: [Action._GetTargetProperty(this._target)]
        }, i)
    }
    ,
    e
}(Action)
  , DoNothingAction = function(a) {
    __extends(e, a);
    function e(i, o) {
        return i === void 0 && (i = 0),
        a.call(this, i, o) || this
    }
    return e.prototype.execute = function() {}
    ,
    e.prototype.serialize = function(i) {
        return a.prototype._serialize.call(this, {
            name: "DoNothingAction",
            properties: []
        }, i)
    }
    ,
    e
}(Action);
(function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        c === void 0 && (c = !0);
        var d = a.call(this, i, s) || this;
        return d.children = o,
        d.enableChildrenConditions = c,
        d
    }
    return e.prototype._prepare = function() {
        for (var i = 0; i < this.children.length; i++)
            this.children[i]._actionManager = this._actionManager,
            this.children[i]._prepare()
    }
    ,
    e.prototype.execute = function(i) {
        for (var o = 0, s = this.children; o < s.length; o++) {
            var c = s[o];
            (!this.enableChildrenConditions || c._evaluateConditionForCurrentFrame()) && c.execute(i)
        }
    }
    ,
    e.prototype.serialize = function(i) {
        for (var o = a.prototype._serialize.call(this, {
            name: "CombineAction",
            properties: [],
            combine: []
        }, i), s = 0; s < this.children.length; s++)
            o.combine.push(this.children[s].serialize(null));
        return o
    }
    ,
    e
}
)(Action);
var ExecuteCodeAction = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, s) || this;
        return c.func = o,
        c
    }
    return e.prototype.execute = function(i) {
        this.func(i)
    }
    ,
    e
}(Action)
  , SetParentAction = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        var d = a.call(this, i, c) || this;
        return d._target = o,
        d._parent = s,
        d
    }
    return e.prototype._prepare = function() {}
    ,
    e.prototype.execute = function() {
        if (this._target.parent !== this._parent) {
            var i = this._parent.getWorldMatrix().clone();
            i.invert(),
            this._target.position = Vector3.TransformCoordinates(this._target.position, i),
            this._target.parent = this._parent
        }
    }
    ,
    e.prototype.serialize = function(i) {
        return a.prototype._serialize.call(this, {
            name: "SetParentAction",
            properties: [Action._GetTargetProperty(this._target), Action._GetTargetProperty(this._parent)]
        }, i)
    }
    ,
    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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this) || this;
        return o._scene = i || EngineStore.LastCreatedScene,
        i.actionManagers.push(o),
        o
    }
    return e.prototype.dispose = function() {
        for (var i = this._scene.actionManagers.indexOf(this), o = 0; o < this.actions.length; o++) {
            var s = this.actions[o];
            e.Triggers[s.trigger]--,
            e.Triggers[s.trigger] === 0 && delete e.Triggers[s.trigger]
        }
        i > -1 && this._scene.actionManagers.splice(i, 1)
    }
    ,
    e.prototype.getScene = function() {
        return this._scene
    }
    ,
    e.prototype.hasSpecificTriggers = function(i) {
        for (var o = 0; o < this.actions.length; o++) {
            var s = this.actions[o];
            if (i.indexOf(s.trigger) > -1)
                return !0
        }
        return !1
    }
    ,
    e.prototype.hasSpecificTriggers2 = function(i, o) {
        for (var s = 0; s < this.actions.length; s++) {
            var c = this.actions[s];
            if (i == c.trigger || o == c.trigger)
                return !0
        }
        return !1
    }
    ,
    e.prototype.hasSpecificTrigger = function(i, o) {
        for (var s = 0; s < this.actions.length; s++) {
            var c = this.actions[s];
            if (c.trigger === i)
                if (o) {
                    if (o(c.getTriggerParameter()))
                        return !0
                } else
                    return !0
        }
        return !1
    }
    ,
    Object.defineProperty(e.prototype, "hasPointerTriggers", {
        get: function() {
            for (var i = 0; i < this.actions.length; i++) {
                var o = this.actions[i];
                if (o.trigger >= e.OnPickTrigger && o.trigger <= e.OnPointerOutTrigger)
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasPickTriggers", {
        get: function() {
            for (var i = 0; i < this.actions.length; i++) {
                var o = this.actions[i];
                if (o.trigger >= e.OnPickTrigger && o.trigger <= e.OnPickUpTrigger)
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.registerAction = function(i) {
        return i.trigger === e.OnEveryFrameTrigger && this.getScene().actionManager !== this ? (Logger$2.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),
        null) : (this.actions.push(i),
        e.Triggers[i.trigger] ? e.Triggers[i.trigger]++ : e.Triggers[i.trigger] = 1,
        i._actionManager = this,
        i._prepare(),
        i)
    }
    ,
    e.prototype.unregisterAction = function(i) {
        var o = this.actions.indexOf(i);
        return o !== -1 ? (this.actions.splice(o, 1),
        e.Triggers[i.trigger] -= 1,
        e.Triggers[i.trigger] === 0 && delete e.Triggers[i.trigger],
        i._actionManager = null,
        !0) : !1
    }
    ,
    e.prototype.processTrigger = function(i, o) {
        for (var s = 0; s < this.actions.length; s++) {
            var c = this.actions[s];
            if (c.trigger === i) {
                if (o && (i === e.OnKeyUpTrigger || i === e.OnKeyDownTrigger)) {
                    var d = c.getTriggerParameter();
                    if (d && d !== o.sourceEvent.keyCode) {
                        if (!d.toLowerCase)
                            continue;
                        var _ = d.toLowerCase();
                        if (_ !== o.sourceEvent.key) {
                            var b = o.sourceEvent.charCode ? o.sourceEvent.charCode : o.sourceEvent.keyCode
                              , k = String.fromCharCode(b).toLowerCase();
                            if (k !== _)
                                continue
                        }
                    }
                }
                c._executeCurrent(o)
            }
        }
    }
    ,
    e.prototype._getEffectiveTarget = function(i, o) {
        for (var s = o.split("."), c = 0; c < s.length - 1; c++)
            i = i[s[c]];
        return i
    }
    ,
    e.prototype._getProperty = function(i) {
        var o = i.split(".");
        return o[o.length - 1]
    }
    ,
    e.prototype.serialize = function(i) {
        for (var o = {
            children: new Array,
            name: i,
            type: 3,
            properties: new Array
        }, s = 0; s < this.actions.length; s++) {
            var c = {
                type: 0,
                children: new Array,
                name: e.GetTriggerName(this.actions[s].trigger),
                properties: new Array
            }
              , d = this.actions[s].triggerOptions;
            if (d && typeof d != "number")
                if (d.parameter instanceof Node)
                    c.properties.push(Action._GetTargetProperty(d.parameter));
                else {
                    var _ = {};
                    DeepCopier.DeepCopy(d.parameter, _, ["mesh"]),
                    d.parameter && d.parameter.mesh && (_._meshId = d.parameter.mesh.id),
                    c.properties.push({
                        name: "parameter",
                        targetType: null,
                        value: _
                    })
                }
            this.actions[s].serialize(c),
            o.children.push(c)
        }
        return o
    }
    ,
    e.Parse = function(i, o, s) {
        var c = new e(s);
        o === null ? s.actionManager = c : o.actionManager = c;
        for (var d = function(rt, it) {
            var nt = GetClass("BABYLON." + rt);
            if (nt) {
                var ot = Object.create(nt.prototype);
                return ot.constructor.apply(ot, it),
                ot
            }
        }, _ = function(rt, it, nt, ot) {
            if (ot === null) {
                var at = parseFloat(it);
                return it === "true" || it === "false" ? it === "true" : isNaN(at) ? it : at
            }
            for (var st = ot.split("."), ut = it.split(","), ct = 0; ct < st.length; ct++)
                nt = nt[st[ct]];
            if (typeof nt == "boolean")
                return ut[0] === "true";
            if (typeof nt == "string")
                return ut[0];
            for (var lt = new Array, ct = 0; ct < ut.length; ct++)
                lt.push(parseFloat(ut[ct]));
            return nt instanceof Vector3 ? Vector3.FromArray(lt) : nt instanceof Vector4 ? Vector4.FromArray(lt) : nt instanceof Color3 ? Color3.FromArray(lt) : nt instanceof Color4 ? Color4.FromArray(lt) : parseFloat(ut[0])
        }, b = function(rt, it, nt, ot, at) {
            if (at === void 0 && (at = null),
            !rt.detached) {
                var st = new Array
                  , ut = null
                  , ct = null
                  , lt = rt.combine && rt.combine.length > 0;
                if (rt.type === 2 ? st.push(c) : st.push(it),
                lt) {
                    for (var ft = new Array, ht = 0; ht < rt.combine.length; ht++)
                        b(rt.combine[ht], e.NothingTrigger, nt, ot, ft);
                    st.push(ft)
                } else
                    for (var pt = 0; pt < rt.properties.length; pt++) {
                        var dt = rt.properties[pt].value
                          , _t = rt.properties[pt].name
                          , mt = rt.properties[pt].targetType;
                        _t === "target" ? mt !== null && mt === "SceneProperties" ? dt = ut = s : dt = ut = s.getNodeByName(dt) : _t === "parent" ? dt = s.getNodeByName(dt) : _t === "sound" ? s.getSoundByName && (dt = s.getSoundByName(dt)) : _t !== "propertyPath" ? rt.type === 2 && _t === "operator" ? dt = ValueCondition[dt] : dt = _(_t, dt, ut, _t === "value" ? ct : null) : ct = dt,
                        st.push(dt)
                    }
                if (at === null ? st.push(nt) : st.push(null),
                rt.name === "InterpolateValueAction") {
                    var vt = st[st.length - 2];
                    st[st.length - 1] = vt,
                    st[st.length - 2] = nt
                }
                var yt = d(rt.name, st);
                if (yt instanceof Condition && nt !== null) {
                    var Et = new DoNothingAction(it,nt);
                    ot ? ot.then(Et) : c.registerAction(Et),
                    ot = Et
                }
                at === null ? yt instanceof Condition ? (nt = yt,
                yt = ot) : (nt = null,
                ot ? ot.then(yt) : c.registerAction(yt)) : at.push(yt);
                for (var pt = 0; pt < rt.children.length; pt++)
                    b(rt.children[pt], it, nt, yt, null)
            }
        }, k = 0; k < i.children.length; k++) {
            var j, $ = i.children[k];
            if ($.properties.length > 0) {
                var _e = $.properties[0].value
                  , et = $.properties[0].targetType === null ? _e : s.getMeshByName(_e);
                et._meshId && (et.mesh = s.getMeshById(et._meshId)),
                j = {
                    trigger: e[$.name],
                    parameter: et
                }
            } else
                j = e[$.name];
            for (var tt = 0; tt < $.children.length; tt++)
                $.detached || b($.children[tt], j, null, null)
        }
    }
    ,
    e.GetTriggerName = function(i) {
        switch (i) {
        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(a, e) {
    return function() {
        return new PointLight(a,Vector3.Zero(),e)
    }
});
var PointLight = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, s) || this;
        return c._shadowAngle = Math.PI / 2,
        c.position = o,
        c
    }
    return Object.defineProperty(e.prototype, "shadowAngle", {
        get: function() {
            return this._shadowAngle
        },
        set: function(i) {
            this._shadowAngle = i,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "direction", {
        get: function() {
            return this._direction
        },
        set: function(i) {
            var o = this.needCube();
            this._direction = i,
            this.needCube() !== o && 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(i) {
        if (this.direction)
            return a.prototype.getShadowDirection.call(this, i);
        switch (i) {
        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(i, o, s) {
        var c = this.getScene().activeCamera;
        if (!!c) {
            var d = this.shadowMinZ !== void 0 ? this.shadowMinZ : c.minZ
              , _ = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : c.maxZ
              , b = this.getScene().getEngine().useReverseDepthBuffer;
            Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1, b ? _ : d, b ? d : _, i, !0, this._scene.getEngine().isNDCHalfZRange, void 0, b)
        }
    }
    ,
    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(i, o) {
        return this.computeTransformedInformation() ? this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0, o) : this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, o),
        this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, o),
        this
    }
    ,
    e.prototype.transferToNodeMaterialEffect = function(i, o) {
        return this.computeTransformedInformation() ? i.setFloat3(o, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z) : i.setFloat3(o, this.position.x, this.position.y, this.position.z),
        this
    }
    ,
    e.prototype.prepareLightSpecificDefines = function(i, o) {
        i["POINTLIGHT" + o] = !0
    }
    ,
    __decorate([serialize()], e.prototype, "shadowAngle", null),
    e
}(ShadowLight);
function CreateRibbonVertexData(a) {
    var e = a.pathArray
      , i = a.closeArray || !1
      , o = a.closePath || !1
      , s = a.invertUV || !1
      , c = Math.floor(e[0].length / 2)
      , d = a.offset || c;
    d = d > c ? c : Math.floor(d);
    var _ = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, b = a.uvs, k = a.colors, j = [], $ = [], _e = [], et = [], tt = [], rt = [], it = [], nt = [], ot, at = [], st = [], ut, ct, lt;
    if (e.length < 2) {
        var ft = []
          , ht = [];
        for (ct = 0; ct < e[0].length - d; ct++)
            ft.push(e[0][ct]),
            ht.push(e[0][ct + d]);
        e = [ft, ht]
    }
    var pt = 0, dt = o ? 1 : 0, _t, mt;
    ot = e[0].length;
    var vt, yt;
    for (ut = 0; ut < e.length; ut++) {
        for (it[ut] = 0,
        tt[ut] = [0],
        _t = e[ut],
        mt = _t.length,
        ot = ot < mt ? ot : mt,
        lt = 0; lt < mt; )
            j.push(_t[lt].x, _t[lt].y, _t[lt].z),
            lt > 0 && (vt = _t[lt].subtract(_t[lt - 1]).length(),
            yt = vt + it[ut],
            tt[ut].push(yt),
            it[ut] = yt),
            lt++;
        o && (lt--,
        j.push(_t[0].x, _t[0].y, _t[0].z),
        vt = _t[lt].subtract(_t[0]).length(),
        yt = vt + it[ut],
        tt[ut].push(yt),
        it[ut] = yt),
        at[ut] = mt + dt,
        st[ut] = pt,
        pt += mt + dt
    }
    var Et, At, gt = null, St = null;
    for (ct = 0; ct < ot + dt; ct++) {
        for (nt[ct] = 0,
        rt[ct] = [0],
        ut = 0; ut < e.length - 1; ut++)
            Et = e[ut],
            At = e[ut + 1],
            ct === ot ? (gt = Et[0],
            St = At[0]) : (gt = Et[ct],
            St = At[ct]),
            vt = St.subtract(gt).length(),
            yt = vt + nt[ct],
            rt[ct].push(yt),
            nt[ct] = yt;
        i && St && gt && (Et = e[ut],
        At = e[0],
        ct === ot && (St = At[0]),
        vt = St.subtract(gt).length(),
        yt = vt + nt[ct],
        nt[ct] = yt)
    }
    var xt, bt;
    if (b)
        for (ut = 0; ut < b.length; ut++)
            et.push(b[ut].x, b[ut].y);
    else
        for (ut = 0; ut < e.length; ut++)
            for (ct = 0; ct < ot + dt; ct++)
                xt = it[ut] != 0 ? tt[ut][ct] / it[ut] : 0,
                bt = nt[ct] != 0 ? rt[ct][ut] / nt[ct] : 0,
                s ? et.push(bt, xt) : et.push(xt, bt);
    ut = 0;
    for (var Rt = 0, Mt = at[ut] - 1, Pt = at[ut + 1] - 1, It = Mt < Pt ? Mt : Pt, Dt = st[1] - st[0], Ct = i ? at.length : at.length - 1; Rt <= It && ut < Ct; )
        $.push(Rt, Rt + Dt, Rt + 1),
        $.push(Rt + Dt + 1, Rt + 1, Rt + Dt),
        Rt += 1,
        Rt === It && (ut++,
        ut === at.length - 1 ? (Dt = st[0] - st[ut],
        Mt = at[ut] - 1,
        Pt = at[0] - 1) : (Dt = st[ut + 1] - st[ut],
        Mt = at[ut] - 1,
        Pt = at[ut + 1] - 1),
        Rt = st[ut],
        It = Mt < Pt ? Mt + Rt : Pt + Rt);
    if (VertexData.ComputeNormals(j, $, _e),
    o) {
        var Ot = 0
          , wt = 0;
        for (ut = 0; ut < e.length; ut++)
            Ot = st[ut] * 3,
            ut + 1 < e.length ? wt = (st[ut + 1] - 1) * 3 : wt = _e.length - 3,
            _e[Ot] = (_e[Ot] + _e[wt]) * .5,
            _e[Ot + 1] = (_e[Ot + 1] + _e[wt + 1]) * .5,
            _e[Ot + 2] = (_e[Ot + 2] + _e[wt + 2]) * .5,
            _e[wt] = _e[Ot],
            _e[wt + 1] = _e[Ot + 1],
            _e[wt + 2] = _e[Ot + 2]
    }
    VertexData._ComputeSides(_, j, $, _e, et, a.frontUVs, a.backUVs);
    var Nt = null;
    if (k) {
        Nt = new Float32Array(k.length * 4);
        for (var Ft = 0; Ft < k.length; Ft++)
            Nt[Ft * 4] = k[Ft].r,
            Nt[Ft * 4 + 1] = k[Ft].g,
            Nt[Ft * 4 + 2] = k[Ft].b,
            Nt[Ft * 4 + 3] = k[Ft].a
    }
    var Vt = new VertexData
      , Lt = new Float32Array(j)
      , kt = new Float32Array(_e)
      , Bt = new Float32Array(et);
    return Vt.indices = $,
    Vt.positions = Lt,
    Vt.normals = kt,
    Vt.uvs = Bt,
    Nt && Vt.set(Nt, VertexBuffer.ColorKind),
    o && (Vt._idx = st),
    Vt
}
function CreateRibbon(a, e, i) {
    i === void 0 && (i = null);
    var o = e.pathArray
      , s = e.closeArray
      , c = e.closePath
      , d = Mesh._GetDefaultSideOrientation(e.sideOrientation)
      , _ = e.instance
      , b = e.updatable;
    if (_) {
        var k = TmpVectors.Vector3[0].setAll(Number.MAX_VALUE)
          , j = TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE)
          , $ = function(dt) {
            for (var _t = o[0].length, mt = _, vt = 0, yt = mt._originalBuilderSideOrientation === Mesh.DOUBLESIDE ? 2 : 1, Et = 1; Et <= yt; ++Et)
                for (var At = 0; At < o.length; ++At) {
                    var gt = o[At]
                      , St = gt.length;
                    _t = _t < St ? _t : St;
                    for (var xt = 0; xt < _t; ++xt) {
                        var bt = gt[xt];
                        dt[vt] = bt.x,
                        dt[vt + 1] = bt.y,
                        dt[vt + 2] = bt.z,
                        k.minimizeInPlaceFromFloats(bt.x, bt.y, bt.z),
                        j.maximizeInPlaceFromFloats(bt.x, bt.y, bt.z),
                        vt += 3
                    }
                    if (mt._creationDataStorage && mt._creationDataStorage.closePath) {
                        var bt = gt[0];
                        dt[vt] = bt.x,
                        dt[vt + 1] = bt.y,
                        dt[vt + 2] = bt.z,
                        vt += 3
                    }
                }
        }
          , _e = _.getVerticesData(VertexBuffer.PositionKind);
        if ($(_e),
        _.hasBoundingInfo ? _.getBoundingInfo().reConstruct(k, j, _._worldMatrix) : _.buildBoundingInfo(k, j, _._worldMatrix),
        _.updateVerticesData(VertexBuffer.PositionKind, _e, !1, !1),
        e.colors) {
            for (var et = _.getVerticesData(VertexBuffer.ColorKind), tt = 0, rt = 0; tt < e.colors.length; tt++,
            rt += 4) {
                var it = e.colors[tt];
                et[rt] = it.r,
                et[rt + 1] = it.g,
                et[rt + 2] = it.b,
                et[rt + 3] = it.a
            }
            _.updateVerticesData(VertexBuffer.ColorKind, et, !1, !1)
        }
        if (e.uvs) {
            for (var nt = _.getVerticesData(VertexBuffer.UVKind), ot = 0; ot < e.uvs.length; ot++)
                nt[ot * 2] = e.uvs[ot].x,
                nt[ot * 2 + 1] = e.uvs[ot].y;
            _.updateVerticesData(VertexBuffer.UVKind, nt, !1, !1)
        }
        if (!_.areNormalsFrozen || _.isFacetDataEnabled) {
            var at = _.getIndices()
              , st = _.getVerticesData(VertexBuffer.NormalKind)
              , ut = _.isFacetDataEnabled ? _.getFacetDataParameters() : null;
            if (VertexData.ComputeNormals(_e, at, st, ut),
            _._creationDataStorage && _._creationDataStorage.closePath)
                for (var ct = 0, lt = 0, ft = 0; ft < o.length; ft++)
                    ct = _._creationDataStorage.idx[ft] * 3,
                    ft + 1 < o.length ? lt = (_._creationDataStorage.idx[ft + 1] - 1) * 3 : lt = st.length - 3,
                    st[ct] = (st[ct] + st[lt]) * .5,
                    st[ct + 1] = (st[ct + 1] + st[lt + 1]) * .5,
                    st[ct + 2] = (st[ct + 2] + st[lt + 2]) * .5,
                    st[lt] = st[ct],
                    st[lt + 1] = st[ct + 1],
                    st[lt + 2] = st[ct + 2];
            _.areNormalsFrozen || _.updateVerticesData(VertexBuffer.NormalKind, st, !1, !1)
        }
        return _
    } else {
        var ht = new Mesh(a,i);
        ht._originalBuilderSideOrientation = d,
        ht._creationDataStorage = new _CreationDataStorage;
        var pt = CreateRibbonVertexData(e);
        return c && (ht._creationDataStorage.idx = pt._idx),
        ht._creationDataStorage.closePath = c,
        ht._creationDataStorage.closeArray = s,
        pt.applyToMesh(ht, b),
        ht
    }
}
VertexData.CreateRibbon = CreateRibbonVertexData;
Mesh.CreateRibbon = function(a, e, i, o, s, c, d, _, b) {
    return i === void 0 && (i = !1),
    d === void 0 && (d = !1),
    CreateRibbon(a, {
        pathArray: e,
        closeArray: i,
        closePath: o,
        offset: s,
        updatable: d,
        sideOrientation: _,
        instance: b
    }, c)
}
;
function CreateDiscVertexData(a) {
    var e = new Array
      , i = new Array
      , o = new Array
      , s = new Array
      , c = a.radius || .5
      , d = a.tessellation || 64
      , _ = a.arc && (a.arc <= 0 || a.arc > 1) ? 1 : a.arc || 1
      , b = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE;
    e.push(0, 0, 0),
    s.push(.5, .5);
    for (var k = Math.PI * 2 * _, j = _ === 1 ? k / d : k / (d - 1), $ = 0, _e = 0; _e < d; _e++) {
        var et = Math.cos($)
          , tt = Math.sin($)
          , rt = (et + 1) / 2
          , it = (1 - tt) / 2;
        e.push(c * et, c * tt, 0),
        s.push(rt, it),
        $ += j
    }
    _ === 1 && (e.push(e[3], e[4], e[5]),
    s.push(s[2], s[3]));
    for (var nt = e.length / 3, ot = 1; ot < nt - 1; ot++)
        i.push(ot + 1, 0, ot);
    VertexData.ComputeNormals(e, i, o),
    VertexData._ComputeSides(b, e, i, o, s, a.frontUVs, a.backUVs);
    var at = new VertexData;
    return at.indices = i,
    at.positions = e,
    at.normals = o,
    at.uvs = s,
    at
}
function CreateDisc(a, e, i) {
    e === void 0 && (e = {}),
    i === void 0 && (i = null);
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateDiscVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateDisc = CreateDiscVertexData;
Mesh.CreateDisc = function(a, e, i, o, s, c) {
    o === void 0 && (o = null);
    var d = {
        radius: e,
        tessellation: i,
        sideOrientation: c,
        updatable: s
    };
    return CreateDisc(a, d, o)
}
;
function CreateBoxVertexData(a) {
    var e = 6
      , i = [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]
      , o = [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]
      , s = []
      , c = []
      , d = a.width || a.size || 1
      , _ = a.height || a.size || 1
      , b = a.depth || a.size || 1
      , k = a.wrap || !1
      , j = a.topBaseAt === void 0 ? 1 : a.topBaseAt
      , $ = a.bottomBaseAt === void 0 ? 0 : a.bottomBaseAt;
    j = (j + 4) % 4,
    $ = ($ + 4) % 4;
    var _e = [2, 0, 3, 1]
      , et = [2, 0, 1, 3]
      , tt = _e[j]
      , rt = et[$]
      , it = [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 (k) {
        i = [2, 3, 0, 2, 0, 1, 4, 5, 6, 4, 6, 7, 9, 10, 11, 9, 11, 8, 12, 14, 15, 12, 13, 14],
        it = [-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 nt = [[1, 1, 1], [-1, 1, 1], [-1, 1, -1], [1, 1, -1]], ot = [[-1, -1, 1], [1, -1, 1], [1, -1, -1], [-1, -1, -1]], at = [17, 18, 19, 16], st = [22, 23, 20, 21]; tt > 0; )
            nt.unshift(nt.pop()),
            at.unshift(at.pop()),
            tt--;
        for (; rt > 0; )
            ot.unshift(ot.pop()),
            st.unshift(st.pop()),
            rt--;
        nt = nt.flat(),
        ot = ot.flat(),
        it = it.concat(nt).concat(ot),
        i.push(at[0], at[2], at[3], at[0], at[1], at[2]),
        i.push(st[0], st[2], st[3], st[0], st[1], st[2])
    }
    var ut = [d / 2, _ / 2, b / 2];
    c = it.reduce(function(yt, Et, At) {
        return yt.concat(Et * ut[At % 3])
    }, []);
    for (var ct = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, lt = a.faceUV || new Array(6), ft = a.faceColors, ht = [], pt = 0; pt < 6; pt++)
        lt[pt] === void 0 && (lt[pt] = new Vector4(0,0,1,1)),
        ft && ft[pt] === void 0 && (ft[pt] = new Color4(1,1,1,1));
    for (var dt = 0; dt < e; dt++)
        if (s.push(lt[dt].z, lt[dt].w),
        s.push(lt[dt].x, lt[dt].w),
        s.push(lt[dt].x, lt[dt].y),
        s.push(lt[dt].z, lt[dt].y),
        ft)
            for (var _t = 0; _t < 4; _t++)
                ht.push(ft[dt].r, ft[dt].g, ft[dt].b, ft[dt].a);
    VertexData._ComputeSides(ct, c, i, o, s, a.frontUVs, a.backUVs);
    var mt = new VertexData;
    if (mt.indices = i,
    mt.positions = c,
    mt.normals = o,
    mt.uvs = s,
    ft) {
        var vt = ct === VertexData.DOUBLESIDE ? ht.concat(ht) : ht;
        mt.colors = vt
    }
    return mt
}
function CreateBox(a, e, i) {
    e === void 0 && (e = {}),
    i === void 0 && (i = null);
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateBoxVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateBox = CreateBoxVertexData;
Mesh.CreateBox = function(a, e, i, o, s) {
    i === void 0 && (i = null);
    var c = {
        size: e,
        sideOrientation: s,
        updatable: o
    };
    return CreateBox(a, c, i)
}
;
function CreateTiledPlaneVertexData(a) {
    var e = a.pattern || Mesh.NO_FLIP
      , i = a.tileWidth || a.tileSize || 1
      , o = a.tileHeight || a.tileSize || 1
      , s = a.alignHorizontal || 0
      , c = a.alignVertical || 0
      , d = a.width || a.size || 1
      , _ = Math.floor(d / i)
      , b = d - _ * i
      , k = a.height || a.size || 1
      , j = Math.floor(k / o)
      , $ = k - j * o
      , _e = i * _ / 2
      , et = o * j / 2
      , tt = 0
      , rt = 0
      , it = 0
      , nt = 0
      , ot = 0
      , at = 0;
    if (b > 0 || $ > 0) {
        it = -_e,
        nt = -et;
        var ot = _e
          , at = et;
        switch (s) {
        case Mesh.CENTER:
            b /= 2,
            it -= b,
            ot += b;
            break;
        case Mesh.LEFT:
            ot += b,
            tt = -b / 2;
            break;
        case Mesh.RIGHT:
            it -= b,
            tt = b / 2;
            break
        }
        switch (c) {
        case Mesh.CENTER:
            $ /= 2,
            nt -= $,
            at += $;
            break;
        case Mesh.BOTTOM:
            at += $,
            rt = -$ / 2;
            break;
        case Mesh.TOP:
            nt -= $,
            rt = $ / 2;
            break
        }
    }
    var st = []
      , ut = []
      , ct = [];
    ct[0] = [0, 0, 1, 0, 1, 1, 0, 1],
    ct[1] = [0, 0, 1, 0, 1, 1, 0, 1],
    (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (ct[1] = [1, 1, 0, 1, 0, 0, 1, 0]),
    (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (ct[1] = [1, 0, 0, 0, 0, 1, 1, 1]),
    (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (ct[1] = [0, 1, 1, 1, 1, 0, 0, 0]);
    for (var lt = [], ft = [], ht = [], pt = 0, dt = 0; dt < j; dt++)
        for (var _t = 0; _t < _; _t++)
            st.push(-_e + _t * i + tt, -et + dt * o + rt, 0),
            st.push(-_e + (_t + 1) * i + tt, -et + dt * o + rt, 0),
            st.push(-_e + (_t + 1) * i + tt, -et + (dt + 1) * o + rt, 0),
            st.push(-_e + _t * i + tt, -et + (dt + 1) * o + rt, 0),
            ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
            e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? lt = lt.concat(ct[(_t % 2 + dt % 2) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? lt = lt.concat(ct[dt % 2]) : lt = lt.concat(ct[0]),
            ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
            ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1),
            pt += 4;
    if (b > 0 || $ > 0) {
        var mt = $ > 0 && (c === Mesh.CENTER || c === Mesh.TOP), vt = $ > 0 && (c === Mesh.CENTER || c === Mesh.BOTTOM), yt = b > 0 && (s === Mesh.CENTER || s === Mesh.RIGHT), Et = b > 0 && (s === Mesh.CENTER || s === Mesh.LEFT), At = [], gt, St, xt, bt;
        if (mt && yt && (st.push(it + tt, nt + rt, 0),
        st.push(-_e + tt, nt + rt, 0),
        st.push(-_e + tt, nt + $ + rt, 0),
        st.push(it + tt, nt + $ + rt, 0),
        ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
        pt += 4,
        gt = 1 - b / i,
        St = 1 - $ / o,
        xt = 1,
        bt = 1,
        At = [gt, St, xt, St, xt, bt, gt, bt],
        e === Mesh.ROTATE_ROW && (At = [1 - gt, 1 - St, 1 - xt, 1 - St, 1 - xt, 1 - bt, 1 - gt, 1 - bt]),
        e === Mesh.FLIP_ROW && (At = [1 - gt, St, 1 - xt, St, 1 - xt, bt, 1 - gt, bt]),
        e === Mesh.FLIP_N_ROTATE_ROW && (At = [gt, 1 - St, xt, 1 - St, xt, 1 - bt, gt, 1 - bt]),
        lt = lt.concat(At),
        ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
        ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)),
        mt && Et && (st.push(_e + tt, nt + rt, 0),
        st.push(ot + tt, nt + rt, 0),
        st.push(ot + tt, nt + $ + rt, 0),
        st.push(_e + tt, nt + $ + rt, 0),
        ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
        pt += 4,
        gt = 0,
        St = 1 - $ / o,
        xt = b / i,
        bt = 1,
        At = [gt, St, xt, St, xt, bt, gt, bt],
        (e === Mesh.ROTATE_ROW || e === Mesh.ROTATE_TILE && _ % 2 === 0) && (At = [1 - gt, 1 - St, 1 - xt, 1 - St, 1 - xt, 1 - bt, 1 - gt, 1 - bt]),
        (e === Mesh.FLIP_ROW || e === Mesh.FLIP_TILE && _ % 2 === 0) && (At = [1 - gt, St, 1 - xt, St, 1 - xt, bt, 1 - gt, bt]),
        (e === Mesh.FLIP_N_ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_TILE && _ % 2 === 0) && (At = [gt, 1 - St, xt, 1 - St, xt, 1 - bt, gt, 1 - bt]),
        lt = lt.concat(At),
        ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
        ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)),
        vt && yt && (st.push(it + tt, et + rt, 0),
        st.push(-_e + tt, et + rt, 0),
        st.push(-_e + tt, at + rt, 0),
        st.push(it + tt, at + rt, 0),
        ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
        pt += 4,
        gt = 1 - b / i,
        St = 0,
        xt = 1,
        bt = $ / o,
        At = [gt, St, xt, St, xt, bt, gt, bt],
        (e === Mesh.ROTATE_ROW && j % 2 === 1 || e === Mesh.ROTATE_TILE && j % 1 === 0) && (At = [1 - gt, 1 - St, 1 - xt, 1 - St, 1 - xt, 1 - bt, 1 - gt, 1 - bt]),
        (e === Mesh.FLIP_ROW && j % 2 === 1 || e === Mesh.FLIP_TILE && j % 2 === 0) && (At = [1 - gt, St, 1 - xt, St, 1 - xt, bt, 1 - gt, bt]),
        (e === Mesh.FLIP_N_ROTATE_ROW && j % 2 === 1 || e === Mesh.FLIP_N_ROTATE_TILE && j % 2 === 0) && (At = [gt, 1 - St, xt, 1 - St, xt, 1 - bt, gt, 1 - bt]),
        lt = lt.concat(At),
        ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
        ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)),
        vt && Et && (st.push(_e + tt, et + rt, 0),
        st.push(ot + tt, et + rt, 0),
        st.push(ot + tt, at + rt, 0),
        st.push(_e + tt, at + rt, 0),
        ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
        pt += 4,
        gt = 0,
        St = 0,
        xt = b / i,
        bt = $ / o,
        At = [gt, St, xt, St, xt, bt, gt, bt],
        (e === Mesh.ROTATE_ROW && j % 2 === 1 || e === Mesh.ROTATE_TILE && (j + _) % 2 === 1) && (At = [1 - gt, 1 - St, 1 - xt, 1 - St, 1 - xt, 1 - bt, 1 - gt, 1 - bt]),
        (e === Mesh.FLIP_ROW && j % 2 === 1 || e === Mesh.FLIP_TILE && (j + _) % 2 === 1) && (At = [1 - gt, St, 1 - xt, St, 1 - xt, bt, 1 - gt, bt]),
        (e === Mesh.FLIP_N_ROTATE_ROW && j % 2 === 1 || e === Mesh.FLIP_N_ROTATE_TILE && (j + _) % 2 === 1) && (At = [gt, 1 - St, xt, 1 - St, xt, 1 - bt, gt, 1 - bt]),
        lt = lt.concat(At),
        ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
        ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)),
        mt) {
            var Rt = [];
            gt = 0,
            St = 1 - $ / o,
            xt = 1,
            bt = 1,
            Rt[0] = [gt, St, xt, St, xt, bt, gt, bt],
            Rt[1] = [gt, St, xt, St, xt, bt, gt, bt],
            (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (Rt[1] = [1 - gt, 1 - St, 1 - xt, 1 - St, 1 - xt, 1 - bt, 1 - gt, 1 - bt]),
            (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (Rt[1] = [1 - gt, St, 1 - xt, St, 1 - xt, bt, 1 - gt, bt]),
            (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (Rt[1] = [gt, 1 - St, xt, 1 - St, xt, 1 - bt, gt, 1 - bt]);
            for (var _t = 0; _t < _; _t++)
                st.push(-_e + _t * i + tt, nt + rt, 0),
                st.push(-_e + (_t + 1) * i + tt, nt + rt, 0),
                st.push(-_e + (_t + 1) * i + tt, nt + $ + rt, 0),
                st.push(-_e + _t * i + tt, nt + $ + rt, 0),
                ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
                pt += 4,
                e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? lt = lt.concat(Rt[(_t + 1) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? lt = lt.concat(Rt[1]) : lt = lt.concat(Rt[0]),
                ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)
        }
        if (vt) {
            var Mt = [];
            gt = 0,
            St = 0,
            xt = 1,
            bt = $ / o,
            Mt[0] = [gt, St, xt, St, xt, bt, gt, bt],
            Mt[1] = [gt, St, xt, St, xt, bt, gt, bt],
            (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (Mt[1] = [1 - gt, 1 - St, 1 - xt, 1 - St, 1 - xt, 1 - bt, 1 - gt, 1 - bt]),
            (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (Mt[1] = [1 - gt, St, 1 - xt, St, 1 - xt, bt, 1 - gt, bt]),
            (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (Mt[1] = [gt, 1 - St, xt, 1 - St, xt, 1 - bt, gt, 1 - bt]);
            for (var _t = 0; _t < _; _t++)
                st.push(-_e + _t * i + tt, at - $ + rt, 0),
                st.push(-_e + (_t + 1) * i + tt, at - $ + rt, 0),
                st.push(-_e + (_t + 1) * i + tt, at + rt, 0),
                st.push(-_e + _t * i + tt, at + rt, 0),
                ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
                pt += 4,
                e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? lt = lt.concat(Mt[(_t + j) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? lt = lt.concat(Mt[j % 2]) : lt = lt.concat(Mt[0]),
                ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)
        }
        if (yt) {
            var Pt = [];
            gt = 1 - b / i,
            St = 0,
            xt = 1,
            bt = 1,
            Pt[0] = [gt, St, xt, St, xt, bt, gt, bt],
            Pt[1] = [gt, St, xt, St, xt, bt, gt, bt],
            (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (Pt[1] = [1 - gt, 1 - St, 1 - xt, 1 - St, 1 - xt, 1 - bt, 1 - gt, 1 - bt]),
            (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (Pt[1] = [1 - gt, St, 1 - xt, St, 1 - xt, bt, 1 - gt, bt]),
            (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (Pt[1] = [gt, 1 - St, xt, 1 - St, xt, 1 - bt, gt, 1 - bt]);
            for (var dt = 0; dt < j; dt++)
                st.push(it + tt, -et + dt * o + rt, 0),
                st.push(it + b + tt, -et + dt * o + rt, 0),
                st.push(it + b + tt, -et + (dt + 1) * o + rt, 0),
                st.push(it + tt, -et + (dt + 1) * o + rt, 0),
                ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
                pt += 4,
                e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? lt = lt.concat(Pt[(dt + 1) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? lt = lt.concat(Pt[dt % 2]) : lt = lt.concat(Pt[0]),
                ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)
        }
        if (Et) {
            var It = [];
            gt = 0,
            St = 0,
            xt = b / o,
            bt = 1,
            It[0] = [gt, St, xt, St, xt, bt, gt, bt],
            It[1] = [gt, St, xt, St, xt, bt, gt, bt],
            (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (It[1] = [1 - gt, 1 - St, 1 - xt, 1 - St, 1 - xt, 1 - bt, 1 - gt, 1 - bt]),
            (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (It[1] = [1 - gt, St, 1 - xt, St, 1 - xt, bt, 1 - gt, bt]),
            (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (It[1] = [gt, 1 - St, xt, 1 - St, xt, 1 - bt, gt, 1 - bt]);
            for (var dt = 0; dt < j; dt++)
                st.push(ot - b + tt, -et + dt * o + rt, 0),
                st.push(ot + tt, -et + dt * o + rt, 0),
                st.push(ot + tt, -et + (dt + 1) * o + rt, 0),
                st.push(ot - b + tt, -et + (dt + 1) * o + rt, 0),
                ht.push(pt, pt + 1, pt + 3, pt + 1, pt + 2, pt + 3),
                pt += 4,
                e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? lt = lt.concat(It[(dt + _) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? lt = lt.concat(It[dt % 2]) : lt = lt.concat(It[0]),
                ft.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                ut.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)
        }
    }
    var Dt = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE;
    VertexData._ComputeSides(Dt, st, ht, ut, lt, a.frontUVs, a.backUVs);
    var Ct = new VertexData;
    Ct.indices = ht,
    Ct.positions = st,
    Ct.normals = ut,
    Ct.uvs = lt;
    var Ot = Dt === VertexData.DOUBLESIDE ? ft.concat(ft) : ft;
    return Ct.colors = Ot,
    Ct
}
function CreateTiledPlane(a, e, i) {
    i === void 0 && (i = null);
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateTiledPlaneVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateTiledPlane = CreateTiledPlaneVertexData;
function CreateTiledBoxVertexData(a) {
    for (var e = 6, i = a.faceUV || new Array(6), o = a.faceColors, s = a.pattern || Mesh.NO_FLIP, c = a.width || a.size || 1, d = a.height || a.size || 1, _ = a.depth || a.size || 1, b = a.tileWidth || a.tileSize || 1, k = a.tileHeight || a.tileSize || 1, j = a.alignHorizontal || 0, $ = a.alignVertical || 0, _e = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, et = 0; et < e; et++)
        i[et] === void 0 && (i[et] = new Vector4(0,0,1,1)),
        o && o[et] === void 0 && (o[et] = new Color4(1,1,1,1));
    for (var tt = c / 2, rt = d / 2, it = _ / 2, nt = [], et = 0; et < 2; et++)
        nt[et] = CreateTiledPlaneVertexData({
            pattern: s,
            tileWidth: b,
            tileHeight: k,
            width: c,
            height: d,
            alignVertical: $,
            alignHorizontal: j,
            sideOrientation: _e
        });
    for (var et = 2; et < 4; et++)
        nt[et] = CreateTiledPlaneVertexData({
            pattern: s,
            tileWidth: b,
            tileHeight: k,
            width: _,
            height: d,
            alignVertical: $,
            alignHorizontal: j,
            sideOrientation: _e
        });
    var ot = $;
    $ === Mesh.BOTTOM ? ot = Mesh.TOP : $ === Mesh.TOP && (ot = Mesh.BOTTOM);
    for (var et = 4; et < 6; et++)
        nt[et] = CreateTiledPlaneVertexData({
            pattern: s,
            tileWidth: b,
            tileHeight: k,
            width: c,
            height: _,
            alignVertical: ot,
            alignHorizontal: j,
            sideOrientation: _e
        });
    for (var at = [], st = [], ut = [], ct = [], lt = [], ft = [], ht = [], pt = [], dt = 0, _t = 0, mt = 0, et = 0; et < e; et++) {
        var dt = nt[et].positions.length;
        ft[et] = [],
        ht[et] = [];
        for (var vt = 0; vt < dt / 3; vt++)
            ft[et].push(new Vector3(nt[et].positions[3 * vt],nt[et].positions[3 * vt + 1],nt[et].positions[3 * vt + 2])),
            ht[et].push(new Vector3(nt[et].normals[3 * vt],nt[et].normals[3 * vt + 1],nt[et].normals[3 * vt + 2]));
        _t = nt[et].uvs.length,
        pt[et] = [];
        for (var yt = 0; yt < _t; yt += 2)
            pt[et][yt] = i[et].x + (i[et].z - i[et].x) * nt[et].uvs[yt],
            pt[et][yt + 1] = i[et].y + (i[et].w - i[et].y) * nt[et].uvs[yt + 1];
        if (ut = ut.concat(pt[et]),
        ct = ct.concat(nt[et].indices.map(function(wt) {
            return wt + mt
        })),
        mt += ft[et].length,
        o)
            for (var Et = 0; Et < 4; Et++)
                lt.push(o[et].r, o[et].g, o[et].b, o[et].a)
    }
    var At = new Vector3(0,0,it)
      , gt = Matrix.RotationY(Math.PI);
    at = ft[0].map(function(Ct) {
        return Vector3.TransformNormal(Ct, gt).add(At)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, []),
    st = ht[0].map(function(Ct) {
        return Vector3.TransformNormal(Ct, gt)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, []),
    at = at.concat(ft[1].map(function(Ct) {
        return Ct.subtract(At)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, [])),
    st = st.concat(ht[1].map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, []));
    var St = new Vector3(tt,0,0)
      , xt = Matrix.RotationY(-Math.PI / 2);
    at = at.concat(ft[2].map(function(Ct) {
        return Vector3.TransformNormal(Ct, xt).add(St)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, [])),
    st = st.concat(ht[2].map(function(Ct) {
        return Vector3.TransformNormal(Ct, xt)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, []));
    var bt = Matrix.RotationY(Math.PI / 2);
    at = at.concat(ft[3].map(function(Ct) {
        return Vector3.TransformNormal(Ct, bt).subtract(St)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, [])),
    st = st.concat(ht[3].map(function(Ct) {
        return Vector3.TransformNormal(Ct, bt)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, []));
    var Rt = new Vector3(0,rt,0)
      , Mt = Matrix.RotationX(Math.PI / 2);
    at = at.concat(ft[4].map(function(Ct) {
        return Vector3.TransformNormal(Ct, Mt).add(Rt)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, [])),
    st = st.concat(ht[4].map(function(Ct) {
        return Vector3.TransformNormal(Ct, Mt)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, []));
    var Pt = Matrix.RotationX(-Math.PI / 2);
    at = at.concat(ft[5].map(function(Ct) {
        return Vector3.TransformNormal(Ct, Pt).subtract(Rt)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, [])),
    st = st.concat(ht[5].map(function(Ct) {
        return Vector3.TransformNormal(Ct, Pt)
    }).map(function(Ct) {
        return [Ct.x, Ct.y, Ct.z]
    }).reduce(function(Ct, Ot) {
        return Ct.concat(Ot)
    }, [])),
    VertexData._ComputeSides(_e, at, ct, st, ut);
    var It = new VertexData;
    if (It.indices = ct,
    It.positions = at,
    It.normals = st,
    It.uvs = ut,
    o) {
        var Dt = _e === VertexData.DOUBLESIDE ? lt.concat(lt) : lt;
        It.colors = Dt
    }
    return It
}
function CreateTiledBox(a, e, i) {
    i === void 0 && (i = null);
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateTiledBoxVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateTiledBox = CreateTiledBoxVertexData;
function CreateSphereVertexData(a) {
    for (var e = a.segments || 32, i = a.diameterX || a.diameter || 1, o = a.diameterY || a.diameter || 1, s = a.diameterZ || a.diameter || 1, c = a.arc && (a.arc <= 0 || a.arc > 1) ? 1 : a.arc || 1, d = a.slice && a.slice <= 0 ? 1 : a.slice || 1, _ = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, b = !!a.dedupTopBottomIndices, k = new Vector3(i / 2,o / 2,s / 2), j = 2 + e, $ = 2 * j, _e = [], et = [], tt = [], rt = [], it = 0; it <= j; it++) {
        for (var nt = it / j, ot = nt * Math.PI * d, at = 0; at <= $; at++) {
            var st = at / $
              , ut = st * Math.PI * 2 * c
              , ct = Matrix.RotationZ(-ot)
              , lt = Matrix.RotationY(ut)
              , ft = Vector3.TransformCoordinates(Vector3.Up(), ct)
              , ht = Vector3.TransformCoordinates(ft, lt)
              , pt = ht.multiply(k)
              , dt = ht.divide(k).normalize();
            et.push(pt.x, pt.y, pt.z),
            tt.push(dt.x, dt.y, dt.z),
            rt.push(st, nt)
        }
        if (it > 0)
            for (var _t = et.length / 3, mt = _t - 2 * ($ + 1); mt + $ + 2 < _t; mt++)
                b ? (it > 1 && (_e.push(mt),
                _e.push(mt + 1),
                _e.push(mt + $ + 1)),
                (it < j || d < 1) && (_e.push(mt + $ + 1),
                _e.push(mt + 1),
                _e.push(mt + $ + 2))) : (_e.push(mt),
                _e.push(mt + 1),
                _e.push(mt + $ + 1),
                _e.push(mt + $ + 1),
                _e.push(mt + 1),
                _e.push(mt + $ + 2))
    }
    VertexData._ComputeSides(_, et, _e, tt, rt, a.frontUVs, a.backUVs);
    var vt = new VertexData;
    return vt.indices = _e,
    vt.positions = et,
    vt.normals = tt,
    vt.uvs = rt,
    vt
}
function CreateSphere(a, e, i) {
    e === void 0 && (e = {}),
    i === void 0 && (i = null);
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateSphereVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateSphere = CreateSphereVertexData;
Mesh.CreateSphere = function(a, e, i, o, s, c) {
    var d = {
        segments: e,
        diameterX: i,
        diameterY: i,
        diameterZ: i,
        sideOrientation: c,
        updatable: s
    };
    return CreateSphere(a, d, o)
}
;
function CreateCylinderVertexData(a) {
    var e = a.height || 2
      , i = a.diameterTop === 0 ? 0 : a.diameterTop || a.diameter || 1
      , o = a.diameterBottom === 0 ? 0 : a.diameterBottom || a.diameter || 1;
    i = i || 1e-5,
    o = o || 1e-5;
    var s = a.tessellation || 24, c = a.subdivisions || 1, d = !!a.hasRings, _ = !!a.enclose, b = a.cap === 0 ? 0 : a.cap || Mesh.CAP_ALL, k = a.arc && (a.arc <= 0 || a.arc > 1) ? 1 : a.arc || 1, j = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, $ = a.faceUV || new Array(3), _e = a.faceColors, et = k !== 1 && _ ? 2 : 0, tt = d ? c : 1, rt = 2 + (1 + et) * tt, it;
    for (it = 0; it < rt; it++)
        _e && _e[it] === void 0 && (_e[it] = new Color4(1,1,1,1));
    for (it = 0; it < rt; it++)
        $ && $[it] === void 0 && ($[it] = new Vector4(0,0,1,1));
    var nt = new Array, ot = new Array, at = new Array, st = new Array, ut = new Array, ct = Math.PI * 2 * k / s, lt, ft, ht, pt = (o - i) / 2 / e, dt = Vector3.Zero(), _t = Vector3.Zero(), mt = Vector3.Zero(), vt = Vector3.Zero(), yt = Vector3.Zero(), Et = Axis.Y, At, gt, St, xt = 1, Pt = 1, bt = 0, Rt = 0;
    for (At = 0; At <= c; At++)
        for (ft = At / c,
        ht = (ft * (i - o) + o) / 2,
        xt = d && At !== 0 && At !== c ? 2 : 1,
        St = 0; St < xt; St++) {
            for (d && (Pt += St),
            _ && (Pt += 2 * St),
            gt = 0; gt <= s; gt++)
                lt = gt * ct,
                dt.x = Math.cos(-lt) * ht,
                dt.y = -e / 2 + ft * e,
                dt.z = Math.sin(-lt) * ht,
                i === 0 && At === c ? (_t.x = at[at.length - (s + 1) * 3],
                _t.y = at[at.length - (s + 1) * 3 + 1],
                _t.z = at[at.length - (s + 1) * 3 + 2]) : (_t.x = dt.x,
                _t.z = dt.z,
                _t.y = Math.sqrt(_t.x * _t.x + _t.z * _t.z) * pt,
                _t.normalize()),
                gt === 0 && (mt.copyFrom(dt),
                vt.copyFrom(_t)),
                ot.push(dt.x, dt.y, dt.z),
                at.push(_t.x, _t.y, _t.z),
                d ? Rt = bt !== Pt ? $[Pt].y : $[Pt].w : Rt = $[Pt].y + ($[Pt].w - $[Pt].y) * ft,
                st.push($[Pt].x + ($[Pt].z - $[Pt].x) * gt / s, Rt),
                _e && ut.push(_e[Pt].r, _e[Pt].g, _e[Pt].b, _e[Pt].a);
            k !== 1 && _ && (ot.push(dt.x, dt.y, dt.z),
            ot.push(0, dt.y, 0),
            ot.push(0, dt.y, 0),
            ot.push(mt.x, mt.y, mt.z),
            Vector3.CrossToRef(Et, _t, yt),
            yt.normalize(),
            at.push(yt.x, yt.y, yt.z, yt.x, yt.y, yt.z),
            Vector3.CrossToRef(vt, Et, yt),
            yt.normalize(),
            at.push(yt.x, yt.y, yt.z, yt.x, yt.y, yt.z),
            d ? Rt = bt !== Pt ? $[Pt + 1].y : $[Pt + 1].w : Rt = $[Pt + 1].y + ($[Pt + 1].w - $[Pt + 1].y) * ft,
            st.push($[Pt + 1].x, Rt),
            st.push($[Pt + 1].z, Rt),
            d ? Rt = bt !== Pt ? $[Pt + 2].y : $[Pt + 2].w : Rt = $[Pt + 2].y + ($[Pt + 2].w - $[Pt + 2].y) * ft,
            st.push($[Pt + 2].x, Rt),
            st.push($[Pt + 2].z, Rt),
            _e && (ut.push(_e[Pt + 1].r, _e[Pt + 1].g, _e[Pt + 1].b, _e[Pt + 1].a),
            ut.push(_e[Pt + 1].r, _e[Pt + 1].g, _e[Pt + 1].b, _e[Pt + 1].a),
            ut.push(_e[Pt + 2].r, _e[Pt + 2].g, _e[Pt + 2].b, _e[Pt + 2].a),
            ut.push(_e[Pt + 2].r, _e[Pt + 2].g, _e[Pt + 2].b, _e[Pt + 2].a))),
            bt !== Pt && (bt = Pt)
        }
    var Mt = k !== 1 && _ ? s + 4 : s, Pt;
    for (At = 0,
    Pt = 0; Pt < c; Pt++) {
        var It = 0
          , Dt = 0
          , Ct = 0
          , Ot = 0;
        for (gt = 0; gt < s; gt++)
            It = At * (Mt + 1) + gt,
            Dt = (At + 1) * (Mt + 1) + gt,
            Ct = At * (Mt + 1) + (gt + 1),
            Ot = (At + 1) * (Mt + 1) + (gt + 1),
            nt.push(It, Dt, Ct),
            nt.push(Ot, Ct, Dt);
        k !== 1 && _ && (nt.push(It + 2, Dt + 2, Ct + 2),
        nt.push(Ot + 2, Ct + 2, Dt + 2),
        nt.push(It + 4, Dt + 4, Ct + 4),
        nt.push(Ot + 4, Ct + 4, Dt + 4)),
        At = d ? At + 2 : At + 1
    }
    var wt = function(Ft) {
        var Vt = Ft ? i / 2 : o / 2;
        if (Vt !== 0) {
            var Lt, kt, Bt, Ut = Ft ? $[rt - 1] : $[0], Gt = null;
            _e && (Gt = Ft ? _e[rt - 1] : _e[0]);
            var Ht = ot.length / 3
              , zt = Ft ? e / 2 : -e / 2
              , Wt = new Vector3(0,zt,0);
            ot.push(Wt.x, Wt.y, Wt.z),
            at.push(0, Ft ? 1 : -1, 0),
            st.push(Ut.x + (Ut.z - Ut.x) * .5, Ut.y + (Ut.w - Ut.y) * .5),
            Gt && ut.push(Gt.r, Gt.g, Gt.b, Gt.a);
            var Kt = new Vector2(.5,.5);
            for (Bt = 0; Bt <= s; Bt++) {
                Lt = Math.PI * 2 * Bt * k / s;
                var Qt = Math.cos(-Lt)
                  , qt = Math.sin(-Lt);
                kt = new Vector3(Qt * Vt,zt,qt * Vt);
                var Yt = new Vector2(Qt * Kt.x + .5,qt * Kt.y + .5);
                ot.push(kt.x, kt.y, kt.z),
                at.push(0, Ft ? 1 : -1, 0),
                st.push(Ut.x + (Ut.z - Ut.x) * Yt.x, Ut.y + (Ut.w - Ut.y) * Yt.y),
                Gt && ut.push(Gt.r, Gt.g, Gt.b, Gt.a)
            }
            for (Bt = 0; Bt < s; Bt++)
                Ft ? (nt.push(Ht),
                nt.push(Ht + (Bt + 2)),
                nt.push(Ht + (Bt + 1))) : (nt.push(Ht),
                nt.push(Ht + (Bt + 1)),
                nt.push(Ht + (Bt + 2)))
        }
    };
    (b === Mesh.CAP_START || b === Mesh.CAP_ALL) && wt(!1),
    (b === Mesh.CAP_END || b === Mesh.CAP_ALL) && wt(!0),
    VertexData._ComputeSides(j, ot, nt, at, st, a.frontUVs, a.backUVs);
    var Nt = new VertexData;
    return Nt.indices = nt,
    Nt.positions = ot,
    Nt.normals = at,
    Nt.uvs = st,
    _e && (Nt.colors = ut),
    Nt
}
function CreateCylinder(a, e, i) {
    e === void 0 && (e = {});
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateCylinderVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateCylinder = CreateCylinderVertexData;
Mesh.CreateCylinder = function(a, e, i, o, s, c, d, _, b) {
    (d === void 0 || !(d instanceof Scene)) && (d !== void 0 && (b = _ || Mesh.DEFAULTSIDE,
    _ = d),
    d = c,
    c = 1);
    var k = {
        height: e,
        diameterTop: i,
        diameterBottom: o,
        tessellation: s,
        subdivisions: c,
        sideOrientation: b,
        updatable: _
    };
    return CreateCylinder(a, k, d)
}
;
function CreateTorusVertexData(a) {
    for (var e = [], i = [], o = [], s = [], c = a.diameter || 1, d = a.thickness || .5, _ = a.tessellation || 16, b = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, k = _ + 1, j = 0; j <= _; j++)
        for (var $ = j / _, _e = j * Math.PI * 2 / _ - Math.PI / 2, et = Matrix.Translation(c / 2, 0, 0).multiply(Matrix.RotationY(_e)), tt = 0; tt <= _; tt++) {
            var rt = 1 - tt / _
              , it = tt * Math.PI * 2 / _ + Math.PI
              , nt = Math.cos(it)
              , ot = Math.sin(it)
              , at = new Vector3(nt,ot,0)
              , st = at.scale(d / 2)
              , ut = new Vector2($,rt);
            st = Vector3.TransformCoordinates(st, et),
            at = Vector3.TransformNormal(at, et),
            i.push(st.x, st.y, st.z),
            o.push(at.x, at.y, at.z),
            s.push(ut.x, ut.y);
            var ct = (j + 1) % k
              , lt = (tt + 1) % k;
            e.push(j * k + tt),
            e.push(j * k + lt),
            e.push(ct * k + tt),
            e.push(j * k + lt),
            e.push(ct * k + lt),
            e.push(ct * k + tt)
        }
    VertexData._ComputeSides(b, i, e, o, s, a.frontUVs, a.backUVs);
    var ft = new VertexData;
    return ft.indices = e,
    ft.positions = i,
    ft.normals = o,
    ft.uvs = s,
    ft
}
function CreateTorus(a, e, i) {
    e === void 0 && (e = {});
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateTorusVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateTorus = CreateTorusVertexData;
Mesh.CreateTorus = function(a, e, i, o, s, c, d) {
    var _ = {
        diameter: e,
        thickness: i,
        tessellation: o,
        sideOrientation: d,
        updatable: c
    };
    return CreateTorus(a, _, s)
}
;
function CreateTorusKnotVertexData(a) {
    var e = new Array, i = new Array, o = new Array, s = new Array, c = a.radius || 2, d = a.tube || .5, _ = a.radialSegments || 32, b = a.tubularSegments || 32, k = a.p || 2, j = a.q || 3, $ = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, _e = function(Et) {
        var At = Math.cos(Et)
          , gt = Math.sin(Et)
          , St = j / k * Et
          , xt = Math.cos(St)
          , bt = c * (2 + xt) * .5 * At
          , Rt = c * (2 + xt) * gt * .5
          , Mt = c * Math.sin(St) * .5;
        return new Vector3(bt,Rt,Mt)
    }, et, tt;
    for (et = 0; et <= _; et++) {
        var rt = et % _
          , it = rt / _ * 2 * k * Math.PI
          , nt = _e(it)
          , ot = _e(it + .01)
          , at = ot.subtract(nt)
          , st = ot.add(nt)
          , ut = Vector3.Cross(at, st);
        for (st = Vector3.Cross(ut, at),
        ut.normalize(),
        st.normalize(),
        tt = 0; tt < b; tt++) {
            var ct = tt % b
              , lt = ct / b * 2 * Math.PI
              , ft = -d * Math.cos(lt)
              , ht = d * Math.sin(lt);
            i.push(nt.x + ft * st.x + ht * ut.x),
            i.push(nt.y + ft * st.y + ht * ut.y),
            i.push(nt.z + ft * st.z + ht * ut.z),
            s.push(et / _),
            s.push(tt / b)
        }
    }
    for (et = 0; et < _; et++)
        for (tt = 0; tt < b; tt++) {
            var pt = (tt + 1) % b
              , dt = et * b + tt
              , _t = (et + 1) * b + tt
              , mt = (et + 1) * b + pt
              , vt = et * b + pt;
            e.push(vt),
            e.push(_t),
            e.push(dt),
            e.push(vt),
            e.push(mt),
            e.push(_t)
        }
    VertexData.ComputeNormals(i, e, o),
    VertexData._ComputeSides($, i, e, o, s, a.frontUVs, a.backUVs);
    var yt = new VertexData;
    return yt.indices = e,
    yt.positions = i,
    yt.normals = o,
    yt.uvs = s,
    yt
}
function CreateTorusKnot(a, e, i) {
    e === void 0 && (e = {});
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateTorusKnotVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateTorusKnot = CreateTorusKnotVertexData;
Mesh.CreateTorusKnot = function(a, e, i, o, s, c, d, _, b, k) {
    var j = {
        radius: e,
        tube: i,
        radialSegments: o,
        tubularSegments: s,
        p: c,
        q: d,
        sideOrientation: k,
        updatable: b
    };
    return CreateTorusKnot(a, j, _)
}
;
Mesh._instancedMeshFactory = function(a, e) {
    var i = new InstancedMesh(a,e);
    if (e.instancedBuffers) {
        i.instancedBuffers = {};
        for (var o in e.instancedBuffers)
            i.instancedBuffers[o] = e.instancedBuffers[o]
    }
    return i
}
;
var InstancedMesh = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o.getScene()) || this;
        s._indexInSourceMeshInstanceArray = -1,
        s._distanceToCamera = 0,
        o.addInstance(s),
        s._sourceMesh = o,
        s._unIndexed = o._unIndexed,
        s.position.copyFrom(o.position),
        s.rotation.copyFrom(o.rotation),
        s.scaling.copyFrom(o.scaling),
        o.rotationQuaternion && (s.rotationQuaternion = o.rotationQuaternion.clone()),
        s.animations = Tools.Slice(o.animations);
        for (var c = 0, d = o.getAnimationRanges(); c < d.length; c++) {
            var _ = d[c];
            _ != null && s.createAnimationRange(_.name, _.from, _.to)
        }
        return s.infiniteDistance = o.infiniteDistance,
        s.setPivotMatrix(o.getPivotMatrix()),
        s.refreshBoundingInfo(),
        s._syncSubMeshes(),
        s
    }
    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(i) {}
    ,
    e.prototype._removeLightSource = function(i, o) {}
    ,
    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(i) {
            !this._sourceMesh || i === 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(i) {
        return this._sourceMesh.createInstance(i)
    }
    ,
    e.prototype.isReady = function(i) {
        return i === void 0 && (i = !1),
        this._sourceMesh.isReady(i, !0)
    }
    ,
    e.prototype.getVerticesData = function(i, o) {
        return this._sourceMesh.getVerticesData(i, o)
    }
    ,
    e.prototype.setVerticesData = function(i, o, s, c) {
        return this.sourceMesh && this.sourceMesh.setVerticesData(i, o, s, c),
        this.sourceMesh
    }
    ,
    e.prototype.updateVerticesData = function(i, o, s, c) {
        return this.sourceMesh && this.sourceMesh.updateVerticesData(i, o, s, c),
        this.sourceMesh
    }
    ,
    e.prototype.setIndices = function(i, o) {
        return o === void 0 && (o = null),
        this.sourceMesh && this.sourceMesh.setIndices(i, o),
        this.sourceMesh
    }
    ,
    e.prototype.isVerticesDataPresent = function(i) {
        return this._sourceMesh.isVerticesDataPresent(i)
    }
    ,
    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(i, o) {
        if (i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        this.hasBoundingInfo && this.getBoundingInfo().isLocked)
            return this;
        var s = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;
        return this._refreshBoundingInfo(this._sourceMesh._getPositionData(i, o), s),
        this
    }
    ,
    e.prototype._preActivate = function() {
        return this._currentLOD && this._currentLOD._preActivate(),
        this
    }
    ,
    e.prototype._activate = function(i, o) {
        if (this._sourceMesh.subMeshes || Logger$2.Warn("Instances should only be created for meshes with geometry."),
        this._currentLOD) {
            var s = this._currentLOD._getWorldMatrixDeterminant() > 0 != this._getWorldMatrixDeterminant() > 0;
            if (s)
                return this._internalAbstractMeshDataInfo._actAsRegularMesh = !0,
                !0;
            if (this._internalAbstractMeshDataInfo._actAsRegularMesh = !1,
            this._currentLOD._registerInstanceForRenderId(this, i),
            o) {
                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 i = 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 = i,
            this._billboardWorldMatrix
        }
        return a.prototype.getWorldMatrix.call(this)
    }
    ,
    Object.defineProperty(e.prototype, "isAnInstance", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getLOD = function(i) {
        if (!i)
            return this;
        var o = this.getBoundingInfo();
        return this._currentLOD = this.sourceMesh.getLOD(i, o.boundingSphere),
        this._currentLOD === this.sourceMesh ? this.sourceMesh : this._currentLOD
    }
    ,
    e.prototype._preActivateForIntermediateRendering = function(i) {
        return this.sourceMesh._preActivateForIntermediateRendering(i)
    }
    ,
    e.prototype._syncSubMeshes = function() {
        if (this.releaseSubMeshes(),
        this._sourceMesh.subMeshes)
            for (var i = 0; i < this._sourceMesh.subMeshes.length; i++)
                this._sourceMesh.subMeshes[i].clone(this, this._sourceMesh);
        return this
    }
    ,
    e.prototype._generatePointsArray = function() {
        return this._sourceMesh._generatePointsArray()
    }
    ,
    e.prototype._updateBoundingInfo = function() {
        var i = this;
        return this.hasBoundingInfo ? this.getBoundingInfo().update(i.worldMatrixFromCache) : this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, i.worldMatrixFromCache),
        this._updateSubMeshesBoundingInfo(i.worldMatrixFromCache),
        this
    }
    ,
    e.prototype.clone = function(i, o, s) {
        o === void 0 && (o = null);
        var c = this._sourceMesh.createInstance(i);
        if (DeepCopier.DeepCopy(this, c, ["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(),
        o && (c.parent = o),
        !s)
            for (var d = 0; d < this.getScene().meshes.length; d++) {
                var _ = this.getScene().meshes[d];
                _.parent === this && _.clone(_.name, c)
            }
        return c.computeWorldMatrix(!0),
        this.onClonedObservable.notifyObservers(c),
        c
    }
    ,
    e.prototype.dispose = function(i, o) {
        o === void 0 && (o = !1),
        this._sourceMesh.removeInstance(this),
        a.prototype.dispose.call(this, i, o)
    }
    ,
    e
}(AbstractMesh);
Mesh.prototype.edgesShareWithInstances = !1;
Mesh.prototype.registerInstancedBuffer = function(a, e) {
    var i, o;
    if ((o = (i = this._userInstancedBuffersStorage) === null || i === void 0 ? void 0 : i.vertexBuffers[a]) === null || o === void 0 || o.dispose(),
    !this.instancedBuffers) {
        this.instancedBuffers = {};
        for (var s = 0, c = this.instances; s < c.length; s++) {
            var d = c[s];
            d.instancedBuffers = {}
        }
        this._userInstancedBuffersStorage = {
            data: {},
            vertexBuffers: {},
            strides: {},
            sizes: {},
            vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : void 0
        }
    }
    this.instancedBuffers[a] = null,
    this._userInstancedBuffersStorage.strides[a] = e,
    this._userInstancedBuffersStorage.sizes[a] = e * 32,
    this._userInstancedBuffersStorage.data[a] = new Float32Array(this._userInstancedBuffersStorage.sizes[a]),
    this._userInstancedBuffersStorage.vertexBuffers[a] = new VertexBuffer(this.getEngine(),this._userInstancedBuffersStorage.data[a],a,!0,!1,e,!0);
    for (var _ = 0, b = this.instances; _ < b.length; _++) {
        var d = b[_];
        d.instancedBuffers[a] = null
    }
    this._invalidateInstanceVertexArrayObject()
}
;
Mesh.prototype._processInstancedBuffers = function(a, e) {
    var i = a.length;
    for (var o in this.instancedBuffers) {
        for (var s = this._userInstancedBuffersStorage.sizes[o], c = this._userInstancedBuffersStorage.strides[o], d = (i + 1) * c; s < d; )
            s *= 2;
        this._userInstancedBuffersStorage.data[o].length != s && (this._userInstancedBuffersStorage.data[o] = new Float32Array(s),
        this._userInstancedBuffersStorage.sizes[o] = s,
        this._userInstancedBuffersStorage.vertexBuffers[o] && (this._userInstancedBuffersStorage.vertexBuffers[o].dispose(),
        this._userInstancedBuffersStorage.vertexBuffers[o] = null));
        var _ = this._userInstancedBuffersStorage.data[o]
          , b = 0;
        if (e) {
            var k = this.instancedBuffers[o];
            k.toArray ? k.toArray(_, b) : k.copyToArray ? k.copyToArray(_, b) : _[b] = k,
            b += c
        }
        for (var j = 0; j < i; j++) {
            var $ = a[j]
              , k = $.instancedBuffers[o];
            k.toArray ? k.toArray(_, b) : k.copyToArray ? k.copyToArray(_, b) : _[b] = k,
            b += c
        }
        this._userInstancedBuffersStorage.vertexBuffers[o] ? this._userInstancedBuffersStorage.vertexBuffers[o].updateDirectly(_, 0) : (this._userInstancedBuffersStorage.vertexBuffers[o] = new VertexBuffer(this.getEngine(),this._userInstancedBuffersStorage.data[o],o,!0,!1,c,!0),
        this._invalidateInstanceVertexArrayObject())
    }
}
;
Mesh.prototype._invalidateInstanceVertexArrayObject = function() {
    if (!(!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === void 0)) {
        for (var a in this._userInstancedBuffersStorage.vertexArrayObjects)
            this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[a]);
        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 a in this.instancedBuffers)
        this._userInstancedBuffersStorage.vertexBuffers[a] && this._userInstancedBuffersStorage.vertexBuffers[a].dispose();
    this._invalidateInstanceVertexArrayObject(),
    this.instancedBuffers = {}
}
;
var name$1o = "colorPixelShader"
  , shader$1o = `#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$1o] = shader$1o;
var name$1n = "colorVertexShader"
  , shader$1n = `
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$1n] = shader$1n;
Mesh._LinesMeshParser = function(a, e) {
    return LinesMesh.Parse(a, e)
}
;
var LinesMesh = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        o === void 0 && (o = null),
        s === void 0 && (s = null),
        c === void 0 && (c = null);
        var j = a.call(this, i, o, s, c, d) || this;
        j.useVertexColor = _,
        j.useVertexAlpha = b,
        j.color = new Color3(1,1,1),
        j.alpha = 1,
        c && (j.color = c.color.clone(),
        j.alpha = c.alpha,
        j.useVertexColor = c.useVertexColor,
        j.useVertexAlpha = c.useVertexAlpha),
        j.intersectionThreshold = .1;
        var $ = []
          , _e = {
            attributes: [VertexBuffer.PositionKind],
            uniforms: ["vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "world", "viewProjection"],
            needAlphaBlending: !0,
            defines: $,
            useClipPlane: null
        };
        return b === !1 && (_e.needAlphaBlending = !1),
        _ ? (_e.defines.push("#define VERTEXCOLOR"),
        _e.attributes.push(VertexBuffer.ColorKind)) : (_e.uniforms.push("color"),
        j.color4 = new Color4),
        k ? j.material = k : j._lineMaterial = new ShaderMaterial("colorShader",j.getScene(),"color",_e,!1),
        j
    }
    return e.prototype._isShaderMaterial = function(i) {
        return i.getClassName() === "ShaderMaterial"
    }
    ,
    e.prototype.isReady = function() {
        return this._lineMaterial.isReady(this, !!this._userInstancedBuffersStorage) ? a.prototype.isReady.call(this) : !1
    }
    ,
    e.prototype.getClassName = function() {
        return "LinesMesh"
    }
    ,
    Object.defineProperty(e.prototype, "material", {
        get: function() {
            return this._lineMaterial
        },
        set: function(i) {
            this._lineMaterial = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "checkCollisions", {
        get: function() {
            return !1
        },
        set: function(i) {},
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._bind = function(i, o, s) {
        if (!this._geometry)
            return this;
        var c = this._lineMaterial.getEffect()
          , d = this.isUnIndexed ? null : this._geometry.getIndexBuffer();
        if (this._userInstancedBuffersStorage ? this._geometry._bind(c, d, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects) : this._geometry._bind(c, d),
        !this.useVertexColor && this._isShaderMaterial(this._lineMaterial)) {
            var _ = this.color
              , b = _.r
              , k = _.g
              , j = _.b;
            this.color4.set(b, k, j, this.alpha),
            this._lineMaterial.setColor4("color", this.color4)
        }
        return this
    }
    ,
    e.prototype._draw = function(i, o, s) {
        if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer())
            return this;
        var c = this.getScene().getEngine();
        return this._unIndexed ? c.drawArraysType(Material.LineListDrawMode, i.verticesStart, i.verticesCount, s) : c.drawElementsType(Material.LineListDrawMode, i.indexStart, i.indexCount, s),
        this
    }
    ,
    e.prototype.dispose = function(i) {
        this._lineMaterial.dispose(!1, !1, !0),
        a.prototype.dispose.call(this, i)
    }
    ,
    e.prototype.clone = function(i, o, s) {
        return o === void 0 && (o = null),
        new e(i,this.getScene(),o,this,s)
    }
    ,
    e.prototype.createInstance = function(i) {
        var o = new InstancedLinesMesh(i,this);
        if (this.instancedBuffers) {
            o.instancedBuffers = {};
            for (var s in this.instancedBuffers)
                o.instancedBuffers[s] = this.instancedBuffers[s]
        }
        return o
    }
    ,
    e.prototype.serialize = function(i) {
        a.prototype.serialize.call(this, i),
        i.color = this.color.asArray(),
        i.alpha = this.alpha
    }
    ,
    e.Parse = function(i, o) {
        var s = new e(i.name,o);
        return s.color = Color3.FromArray(i.color),
        s.alpha = i.alpha,
        s
    }
    ,
    e
}(Mesh)
  , InstancedLinesMesh = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o) || this;
        return s.intersectionThreshold = o.intersectionThreshold,
        s
    }
    return e.prototype.getClassName = function() {
        return "InstancedLinesMesh"
    }
    ,
    e
}(InstancedMesh);
function CreateLineSystemVertexData(a) {
    for (var e = [], i = [], o = a.lines, s = a.colors, c = [], d = 0, _ = 0; _ < o.length; _++)
        for (var b = o[_], k = 0; k < b.length; k++) {
            if (i.push(b[k].x, b[k].y, b[k].z),
            s) {
                var j = s[_];
                c.push(j[k].r, j[k].g, j[k].b, j[k].a)
            }
            k > 0 && (e.push(d - 1),
            e.push(d)),
            d++
        }
    var $ = new VertexData;
    return $.indices = e,
    $.positions = i,
    s && ($.colors = c),
    $
}
function CreateDashedLinesVertexData(a) {
    var e = a.dashSize || 3
      , i = a.gapSize || 1
      , o = a.dashNb || 200
      , s = a.points
      , c = new Array
      , d = new Array
      , _ = Vector3.Zero()
      , b = 0
      , k = 0
      , j = 0
      , $ = 0
      , _e = 0
      , et = 0
      , tt = 0;
    for (tt = 0; tt < s.length - 1; tt++)
        s[tt + 1].subtractToRef(s[tt], _),
        b += _.length();
    for (j = b / o,
    $ = e * j / (e + i),
    tt = 0; tt < s.length - 1; tt++) {
        s[tt + 1].subtractToRef(s[tt], _),
        k = Math.floor(_.length() / j),
        _.normalize();
        for (var rt = 0; rt < k; rt++)
            _e = j * rt,
            c.push(s[tt].x + _e * _.x, s[tt].y + _e * _.y, s[tt].z + _e * _.z),
            c.push(s[tt].x + (_e + $) * _.x, s[tt].y + (_e + $) * _.y, s[tt].z + (_e + $) * _.z),
            d.push(et, et + 1),
            et += 2
    }
    var it = new VertexData;
    return it.positions = c,
    it.indices = d,
    it
}
function CreateLineSystem(a, e, i) {
    var o = e.instance
      , s = e.lines
      , c = e.colors;
    if (o) {
        var d = o.getVerticesData(VertexBuffer.PositionKind), _, b;
        c && (_ = o.getVerticesData(VertexBuffer.ColorKind));
        for (var k = 0, j = 0, $ = 0; $ < s.length; $++)
            for (var _e = s[$], et = 0; et < _e.length; et++)
                d[k] = _e[et].x,
                d[k + 1] = _e[et].y,
                d[k + 2] = _e[et].z,
                c && _ && (b = c[$],
                _[j] = b[et].r,
                _[j + 1] = b[et].g,
                _[j + 2] = b[et].b,
                _[j + 3] = b[et].a,
                j += 4),
                k += 3;
        return o.updateVerticesData(VertexBuffer.PositionKind, d, !1, !1),
        c && _ && o.updateVerticesData(VertexBuffer.ColorKind, _, !1, !1),
        o
    }
    var tt = !!c
      , rt = new LinesMesh(a,i,null,void 0,void 0,tt,e.useVertexAlpha,e.material)
      , it = CreateLineSystemVertexData(e);
    return it.applyToMesh(rt, e.updatable),
    rt
}
function CreateLines(a, e, i) {
    i === void 0 && (i = null);
    var o = e.colors ? [e.colors] : null
      , s = CreateLineSystem(a, {
        lines: [e.points],
        updatable: e.updatable,
        instance: e.instance,
        colors: o,
        useVertexAlpha: e.useVertexAlpha,
        material: e.material
    }, i);
    return s
}
function CreateDashedLines(a, e, i) {
    i === void 0 && (i = null);
    var o = e.points
      , s = e.instance
      , c = e.gapSize || 1
      , d = e.dashSize || 3;
    if (s) {
        var _ = function(j) {
            var $ = Vector3.Zero()
              , _e = j.length / 6
              , et = 0
              , tt = 0
              , rt = 0
              , it = 0
              , nt = 0
              , ot = 0
              , at = 0
              , st = 0;
            for (at = 0; at < o.length - 1; at++)
                o[at + 1].subtractToRef(o[at], $),
                et += $.length();
            rt = et / _e;
            var ut = s._creationDataStorage.dashSize
              , ct = s._creationDataStorage.gapSize;
            for (it = ut * rt / (ut + ct),
            at = 0; at < o.length - 1; at++)
                for (o[at + 1].subtractToRef(o[at], $),
                tt = Math.floor($.length() / rt),
                $.normalize(),
                st = 0; st < tt && ot < j.length; )
                    nt = rt * st,
                    j[ot] = o[at].x + nt * $.x,
                    j[ot + 1] = o[at].y + nt * $.y,
                    j[ot + 2] = o[at].z + nt * $.z,
                    j[ot + 3] = o[at].x + (nt + it) * $.x,
                    j[ot + 4] = o[at].y + (nt + it) * $.y,
                    j[ot + 5] = o[at].z + (nt + it) * $.z,
                    ot += 6,
                    st++;
            for (; ot < j.length; )
                j[ot] = o[at].x,
                j[ot + 1] = o[at].y,
                j[ot + 2] = o[at].z,
                ot += 3
        };
        return s.updateMeshPositions(_, !1),
        s
    }
    var b = new LinesMesh(a,i,null,void 0,void 0,void 0,e.useVertexAlpha,e.material)
      , k = CreateDashedLinesVertexData(e);
    return k.applyToMesh(b, e.updatable),
    b._creationDataStorage = new _CreationDataStorage,
    b._creationDataStorage.dashSize = d,
    b._creationDataStorage.gapSize = c,
    b
}
VertexData.CreateLineSystem = CreateLineSystemVertexData;
VertexData.CreateDashedLines = CreateDashedLinesVertexData;
Mesh.CreateLines = function(a, e, i, o, s) {
    i === void 0 && (i = null),
    o === void 0 && (o = !1),
    s === void 0 && (s = null);
    var c = {
        points: e,
        updatable: o,
        instance: s
    };
    return CreateLines(a, c, i)
}
;
Mesh.CreateDashedLines = function(a, e, i, o, s, c, d, _) {
    c === void 0 && (c = null);
    var b = {
        points: e,
        dashSize: i,
        gapSize: o,
        dashNb: s,
        updatable: d,
        instance: _
    };
    return CreateDashedLines(a, b, c)
}
;
var IndexedVector2 = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i.x, i.y) || this;
        return s.index = o,
        s
    }
    return e
}(Vector2)
  , PolygonPoints = function() {
    function a() {
        this.elements = new Array
    }
    return a.prototype.add = function(e) {
        var i = this
          , o = new Array;
        return e.forEach(function(s) {
            var c = new IndexedVector2(s,i.elements.length);
            o.push(c),
            i.elements.push(c)
        }),
        o
    }
    ,
    a.prototype.computeBounds = function() {
        var e = new Vector2(this.elements[0].x,this.elements[0].y)
          , i = new Vector2(this.elements[0].x,this.elements[0].y);
        return this.elements.forEach(function(o) {
            o.x < e.x ? e.x = o.x : o.x > i.x && (i.x = o.x),
            o.y < e.y ? e.y = o.y : o.y > i.y && (i.y = o.y)
        }),
        {
            min: e,
            max: i,
            width: i.x - e.x,
            height: i.y - e.y
        }
    }
    ,
    a
}()
  , PolygonMeshBuilder = function() {
    function a(e, i, o, s) {
        s === void 0 && (s = earcut),
        this._points = new PolygonPoints,
        this._outlinepoints = new PolygonPoints,
        this._holes = new Array,
        this._epoints = new Array,
        this._eholes = new Array,
        this.bjsEarcut = s,
        this._name = e,
        this._scene = o || Engine.LastCreatedScene;
        var c;
        i instanceof Path2 ? c = i.getPoints() : c = i,
        this._addToepoint(c),
        this._points.add(c),
        this._outlinepoints.add(c),
        typeof this.bjsEarcut == "undefined" && Logger$2.Warn("Earcut was not found, the polygon will not be built.")
    }
    return a.prototype._addToepoint = function(e) {
        for (var i = 0, o = e; i < o.length; i++) {
            var s = o[i];
            this._epoints.push(s.x, s.y)
        }
    }
    ,
    a.prototype.addHole = function(e) {
        this._points.add(e);
        var i = new PolygonPoints;
        return i.add(e),
        this._holes.push(i),
        this._eholes.push(this._epoints.length / 2),
        this._addToepoint(e),
        this
    }
    ,
    a.prototype.build = function(e, i, o) {
        e === void 0 && (e = !1),
        i === void 0 && (i = 0),
        o === void 0 && (o = 2);
        var s = new Mesh(this._name,this._scene)
          , c = this.buildVertexData(i, o);
        return s.setVerticesData(VertexBuffer.PositionKind, c.positions, e),
        s.setVerticesData(VertexBuffer.NormalKind, c.normals, e),
        s.setVerticesData(VertexBuffer.UVKind, c.uvs, e),
        s.setIndices(c.indices),
        s
    }
    ,
    a.prototype.buildVertexData = function(e, i) {
        var o = this;
        e === void 0 && (e = 0),
        i === void 0 && (i = 2);
        var s = new VertexData
          , c = new Array
          , d = new Array
          , _ = new Array
          , b = this._points.computeBounds();
        this._points.elements.forEach(function(nt) {
            c.push(0, 1, 0),
            d.push(nt.x, 0, nt.y),
            _.push((nt.x - b.min.x) / b.width, (nt.y - b.min.y) / b.height)
        });
        for (var k = new Array, j = this.bjsEarcut(this._epoints, this._eholes, 2), $ = 0; $ < j.length; $++)
            k.push(j[$]);
        if (e > 0) {
            var _e = d.length / 3;
            this._points.elements.forEach(function(nt) {
                c.push(0, -1, 0),
                d.push(nt.x, -e, nt.y),
                _.push(1 - (nt.x - b.min.x) / b.width, 1 - (nt.y - b.min.y) / b.height)
            });
            for (var et = k.length, $ = 0; $ < et; $ += 3) {
                var tt = k[$ + 0]
                  , rt = k[$ + 1]
                  , it = k[$ + 2];
                k.push(it + _e),
                k.push(rt + _e),
                k.push(tt + _e)
            }
            this.addSide(d, c, _, k, b, this._outlinepoints, e, !1, i),
            this._holes.forEach(function(nt) {
                o.addSide(d, c, _, k, b, nt, e, !0, i)
            })
        }
        return s.indices = k,
        s.positions = d,
        s.normals = c,
        s.uvs = _,
        s
    }
    ,
    a.prototype.addSide = function(e, i, o, s, c, d, _, b, k) {
        for (var j = e.length / 3, $ = 0, _e = 0; _e < d.elements.length; _e++) {
            var et = d.elements[_e]
              , tt = d.elements[(_e + 1) % d.elements.length];
            e.push(et.x, 0, et.y),
            e.push(et.x, -_, et.y),
            e.push(tt.x, 0, tt.y),
            e.push(tt.x, -_, tt.y);
            var rt = d.elements[(_e + d.elements.length - 1) % d.elements.length]
              , it = d.elements[(_e + 2) % d.elements.length]
              , nt = new Vector3(-(tt.y - et.y),0,tt.x - et.x)
              , ot = new Vector3(-(et.y - rt.y),0,et.x - rt.x)
              , at = new Vector3(-(it.y - tt.y),0,it.x - tt.x);
            b || (nt = nt.scale(-1),
            ot = ot.scale(-1),
            at = at.scale(-1));
            var st = nt.normalizeToNew()
              , ut = ot.normalizeToNew()
              , ct = at.normalizeToNew()
              , lt = Vector3.Dot(ut, st);
            lt > k ? lt < Epsilon - 1 ? ut = new Vector3(et.x,0,et.y).subtract(new Vector3(tt.x,0,tt.y)).normalize() : ut = ot.add(nt).normalize() : ut = st;
            var ft = Vector3.Dot(at, nt);
            ft > k ? ft < Epsilon - 1 ? ct = new Vector3(tt.x,0,tt.y).subtract(new Vector3(et.x,0,et.y)).normalize() : ct = at.add(nt).normalize() : ct = st,
            o.push($ / c.width, 0),
            o.push($ / c.width, 1),
            $ += nt.length(),
            o.push($ / c.width, 0),
            o.push($ / c.width, 1),
            i.push(ut.x, ut.y, ut.z),
            i.push(ut.x, ut.y, ut.z),
            i.push(ct.x, ct.y, ct.z),
            i.push(ct.x, ct.y, ct.z),
            b ? (s.push(j),
            s.push(j + 2),
            s.push(j + 1),
            s.push(j + 1),
            s.push(j + 2),
            s.push(j + 3)) : (s.push(j),
            s.push(j + 1),
            s.push(j + 2),
            s.push(j + 1),
            s.push(j + 3),
            s.push(j + 2)),
            j += 4
        }
    }
    ,
    a
}();
function CreatePolygonVertexData(a, e, i, o, s, c, d) {
    for (var _ = i || new Array(3), b = o, k = [], j = d || !1, $ = 0; $ < 3; $++)
        _[$] === void 0 && (_[$] = new Vector4(0,0,1,1)),
        b && b[$] === void 0 && (b[$] = new Color4(1,1,1,1));
    var _e = a.getVerticesData(VertexBuffer.PositionKind)
      , et = a.getVerticesData(VertexBuffer.NormalKind)
      , tt = a.getVerticesData(VertexBuffer.UVKind)
      , rt = a.getIndices()
      , it = _e.length / 9
      , nt = 0
      , ot = 0
      , at = 0
      , st = 0
      , ut = 0
      , ct = [0];
    if (j)
        for (var lt = it; lt < _e.length / 3; lt += 4)
            ot = _e[3 * (lt + 2)] - _e[3 * lt],
            at = _e[3 * (lt + 2) + 2] - _e[3 * lt + 2],
            st = Math.sqrt(ot * ot + at * at),
            ut += st,
            ct.push(ut);
    for (var lt = 0, ft = 0, ht = 0; ht < et.length; ht += 3)
        Math.abs(et[ht + 1]) < .001 && (ft = 1),
        Math.abs(et[ht + 1] - 1) < .001 && (ft = 0),
        Math.abs(et[ht + 1] + 1) < .001 && (ft = 2),
        lt = ht / 3,
        ft === 1 ? (nt = lt - it,
        nt % 4 < 1.5 ? j ? tt[2 * lt] = _[ft].x + (_[ft].z - _[ft].x) * ct[Math.floor(nt / 4)] / ut : tt[2 * lt] = _[ft].x : j ? tt[2 * lt] = _[ft].x + (_[ft].z - _[ft].x) * ct[Math.floor(nt / 4) + 1] / ut : tt[2 * lt] = _[ft].z,
        nt % 2 === 0 ? tt[2 * lt + 1] = _[ft].w : tt[2 * lt + 1] = _[ft].y) : (tt[2 * lt] = (1 - tt[2 * lt]) * _[ft].x + tt[2 * lt] * _[ft].z,
        tt[2 * lt + 1] = (1 - tt[2 * lt + 1]) * _[ft].y + tt[2 * lt + 1] * _[ft].w),
        b && k.push(b[ft].r, b[ft].g, b[ft].b, b[ft].a);
    VertexData._ComputeSides(e, _e, rt, et, tt, s, c);
    var pt = new VertexData;
    if (pt.indices = rt,
    pt.positions = _e,
    pt.normals = et,
    pt.uvs = tt,
    b) {
        var dt = e === VertexData.DOUBLESIDE ? k.concat(k) : k;
        pt.colors = dt
    }
    return pt
}
function CreatePolygon(a, e, i, o) {
    i === void 0 && (i = null),
    o === void 0 && (o = earcut),
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation);
    for (var s = e.shape, c = e.holes || [], d = e.depth || 0, _ = e.smoothingThreshold || 2, b = [], k = [], j = 0; j < s.length; j++)
        b[j] = new Vector2(s[j].x,s[j].z);
    var $ = 1e-8;
    b[0].equalsWithEpsilon(b[b.length - 1], $) && b.pop();
    for (var _e = new PolygonMeshBuilder(a,b,i || EngineStore.LastCreatedScene,o), et = 0; et < c.length; et++) {
        k = [];
        for (var tt = 0; tt < c[et].length; tt++)
            k.push(new Vector2(c[et][tt].x,c[et][tt].z));
        _e.addHole(k)
    }
    var rt = _e.build(e.updatable, d, _);
    rt._originalBuilderSideOrientation = e.sideOrientation;
    var it = CreatePolygonVertexData(rt, e.sideOrientation, e.faceUV, e.faceColors, e.frontUVs, e.backUVs, e.wrap);
    return it.applyToMesh(rt, e.updatable),
    rt
}
function ExtrudePolygon(a, e, i, o) {
    return i === void 0 && (i = null),
    o === void 0 && (o = earcut),
    CreatePolygon(a, e, i, o)
}
VertexData.CreatePolygon = CreatePolygonVertexData;
Mesh.CreatePolygon = function(a, e, i, o, s, c, d) {
    d === void 0 && (d = earcut);
    var _ = {
        shape: e,
        holes: o,
        updatable: s,
        sideOrientation: c
    };
    return CreatePolygon(a, _, i, d)
}
;
Mesh.ExtrudePolygon = function(a, e, i, o, s, c, d, _) {
    _ === void 0 && (_ = earcut);
    var b = {
        shape: e,
        holes: s,
        depth: i,
        updatable: c,
        sideOrientation: d
    };
    return ExtrudePolygon(a, b, o, _)
}
;
function ExtrudeShape(a, e, i) {
    i === void 0 && (i = null);
    var o = e.path
      , s = e.shape
      , c = e.scale || 1
      , d = e.rotation || 0
      , _ = e.cap === 0 ? 0 : e.cap || Mesh.NO_CAP
      , b = e.updatable
      , k = Mesh._GetDefaultSideOrientation(e.sideOrientation)
      , j = e.instance || null
      , $ = e.invertUV || !1;
    return _ExtrudeShapeGeneric(a, s, o, c, d, null, null, !1, !1, _, !1, i, !!b, k, j, $, e.frontUVs || null, e.backUVs || null)
}
function ExtrudeShapeCustom(a, e, i) {
    i === void 0 && (i = null);
    var o = e.path
      , s = e.shape
      , c = e.scaleFunction || function() {
        return 1
    }
      , d = e.rotationFunction || function() {
        return 0
    }
      , _ = e.ribbonCloseArray || !1
      , b = e.ribbonClosePath || !1
      , k = e.cap === 0 ? 0 : e.cap || Mesh.NO_CAP
      , j = e.updatable
      , $ = Mesh._GetDefaultSideOrientation(e.sideOrientation)
      , _e = e.instance
      , et = e.invertUV || !1;
    return _ExtrudeShapeGeneric(a, s, o, null, null, c, d, _, b, k, !0, i, !!j, $, _e || null, et, e.frontUVs || null, e.backUVs || null)
}
function _ExtrudeShapeGeneric(a, e, i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it, nt) {
    var ot = function(ft, ht, pt, dt, _t, mt, vt, yt, Et, At) {
        for (var gt = pt.getTangents(), St = pt.getNormals(), xt = pt.getBinormals(), bt = pt.getDistances(), Rt = 0, Mt = function() {
            return _t !== null ? _t : 1
        }, Pt = function() {
            return mt !== null ? mt : 0
        }, It = At && yt ? yt : Pt, Dt = At && vt ? vt : Mt, Ct = Et === Mesh.NO_CAP || Et === Mesh.CAP_END ? 0 : 2, Ot = TmpVectors.Matrix[0], wt = 0; wt < ht.length; wt++) {
            for (var Nt = new Array, Ft = It(wt, bt[wt]), Vt = Dt(wt, bt[wt]), Lt = 0; Lt < ft.length; Lt++) {
                Matrix.RotationAxisToRef(gt[wt], Rt, Ot);
                var kt = gt[wt].scale(ft[Lt].z).add(St[wt].scale(ft[Lt].x)).add(xt[wt].scale(ft[Lt].y))
                  , Bt = Nt[Lt] ? Nt[Lt] : Vector3.Zero();
                Vector3.TransformCoordinatesToRef(kt, Ot, Bt),
                Bt.scaleInPlace(Vt).addInPlace(ht[wt]),
                Nt[Lt] = Bt
            }
            dt[Ct] = Nt,
            Rt += Ft,
            Ct++
        }
        var Ut = function(Gt) {
            var Ht = Array(), zt = Vector3.Zero(), Wt;
            for (Wt = 0; Wt < Gt.length; Wt++)
                zt.addInPlace(Gt[Wt]);
            for (zt.scaleInPlace(1 / Gt.length),
            Wt = 0; Wt < Gt.length; Wt++)
                Ht.push(zt);
            return Ht
        };
        switch (Et) {
        case Mesh.NO_CAP:
            break;
        case Mesh.CAP_START:
            dt[0] = Ut(dt[2]),
            dt[1] = dt[2];
            break;
        case Mesh.CAP_END:
            dt[Ct] = dt[Ct - 1],
            dt[Ct + 1] = Ut(dt[Ct - 1]);
            break;
        case Mesh.CAP_ALL:
            dt[0] = Ut(dt[2]),
            dt[1] = dt[2],
            dt[Ct] = dt[Ct - 1],
            dt[Ct + 1] = Ut(dt[Ct - 1]);
            break
        }
        return dt
    }, at, st;
    if (tt) {
        var ut = tt._creationDataStorage;
        return at = ut.path3D.update(i),
        st = ot(e, i, ut.path3D, ut.pathArray, o, s, c, d, ut.cap, j),
        tt = CreateRibbon("", {
            pathArray: st,
            closeArray: !1,
            closePath: !1,
            offset: 0,
            updatable: !1,
            sideOrientation: 0,
            instance: tt
        }, $ || void 0),
        tt
    }
    at = new Path3D(i);
    var ct = new Array;
    k = k < 0 || k > 3 ? 0 : k,
    st = ot(e, i, at, ct, o, s, c, d, k, j);
    var lt = CreateRibbon(a, {
        pathArray: st,
        closeArray: _,
        closePath: b,
        updatable: _e,
        sideOrientation: et,
        invertUV: rt,
        frontUVs: it || void 0,
        backUVs: nt || void 0
    }, $);
    return lt._creationDataStorage.pathArray = st,
    lt._creationDataStorage.path3D = at,
    lt._creationDataStorage.cap = k,
    lt
}
Mesh.ExtrudeShape = function(a, e, i, o, s, c, d, _, b, k) {
    d === void 0 && (d = null);
    var j = {
        shape: e,
        path: i,
        scale: o,
        rotation: s,
        cap: c === 0 ? 0 : c || Mesh.NO_CAP,
        sideOrientation: b,
        instance: k,
        updatable: _
    };
    return ExtrudeShape(a, j, d)
}
;
Mesh.ExtrudeShapeCustom = function(a, e, i, o, s, c, d, _, b, k, j, $) {
    var _e = {
        shape: e,
        path: i,
        scaleFunction: o,
        rotationFunction: s,
        ribbonCloseArray: c,
        ribbonClosePath: d,
        cap: _ === 0 ? 0 : _ || Mesh.NO_CAP,
        sideOrientation: j,
        instance: $,
        updatable: k
    };
    return ExtrudeShapeCustom(a, _e, b)
}
;
function CreateLathe(a, e, i) {
    i === void 0 && (i = null);
    var o = e.arc ? e.arc <= 0 || e.arc > 1 ? 1 : e.arc : 1, s = e.closed === void 0 ? !0 : e.closed, c = e.shape, d = e.radius || 1, _ = e.tessellation || 64, b = e.clip || 0, k = e.updatable, j = Mesh._GetDefaultSideOrientation(e.sideOrientation), $ = e.cap || Mesh.NO_CAP, _e = Math.PI * 2, et = new Array, tt = e.invertUV || !1, rt = 0, it = 0, nt = _e / _ * o, ot, at = new Array;
    for (rt = 0; rt <= _ - b; rt++) {
        var at = [];
        for (($ == Mesh.CAP_START || $ == Mesh.CAP_ALL) && (at.push(new Vector3(0,c[0].y,0)),
        at.push(new Vector3(Math.cos(rt * nt) * c[0].x * d,c[0].y,Math.sin(rt * nt) * c[0].x * d))),
        it = 0; it < c.length; it++)
            ot = new Vector3(Math.cos(rt * nt) * c[it].x * d,c[it].y,Math.sin(rt * nt) * c[it].x * d),
            at.push(ot);
        ($ == Mesh.CAP_END || $ == Mesh.CAP_ALL) && (at.push(new Vector3(Math.cos(rt * nt) * c[c.length - 1].x * d,c[c.length - 1].y,Math.sin(rt * nt) * c[c.length - 1].x * d)),
        at.push(new Vector3(0,c[c.length - 1].y,0))),
        et.push(at)
    }
    var st = CreateRibbon(a, {
        pathArray: et,
        closeArray: s,
        sideOrientation: j,
        updatable: k,
        invertUV: tt,
        frontUVs: e.frontUVs,
        backUVs: e.backUVs
    }, i);
    return st
}
Mesh.CreateLathe = function(a, e, i, o, s, c, d) {
    var _ = {
        shape: e,
        radius: i,
        tessellation: o,
        sideOrientation: d,
        updatable: c
    };
    return CreateLathe(a, _, s)
}
;
function CreatePlaneVertexData(a) {
    var e = []
      , i = []
      , o = []
      , s = []
      , c = a.width || a.size || 1
      , d = a.height || a.size || 1
      , _ = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE
      , b = c / 2
      , k = d / 2;
    i.push(-b, -k, 0),
    o.push(0, 0, -1),
    s.push(0, 0),
    i.push(b, -k, 0),
    o.push(0, 0, -1),
    s.push(1, 0),
    i.push(b, k, 0),
    o.push(0, 0, -1),
    s.push(1, 1),
    i.push(-b, k, 0),
    o.push(0, 0, -1),
    s.push(0, 1),
    e.push(0),
    e.push(1),
    e.push(2),
    e.push(0),
    e.push(2),
    e.push(3),
    VertexData._ComputeSides(_, i, e, o, s, a.frontUVs, a.backUVs);
    var j = new VertexData;
    return j.indices = e,
    j.positions = i,
    j.normals = o,
    j.uvs = s,
    j
}
function CreatePlane(a, e, i) {
    e === void 0 && (e = {}),
    i === void 0 && (i = null);
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreatePlaneVertexData(e);
    return s.applyToMesh(o, e.updatable),
    e.sourcePlane && (o.translate(e.sourcePlane.normal, -e.sourcePlane.d),
    o.setDirection(e.sourcePlane.normal.scale(-1))),
    o
}
VertexData.CreatePlane = CreatePlaneVertexData;
Mesh.CreatePlane = function(a, e, i, o, s) {
    var c = {
        size: e,
        width: e,
        height: e,
        sideOrientation: s,
        updatable: o
    };
    return CreatePlane(a, c, i)
}
;
Mesh._GroundMeshParser = function(a, e) {
    return GroundMesh.Parse(a, e)
}
;
var GroundMesh = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o) || this;
        return s.generateOctree = !1,
        s
    }
    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(i, o) {
        o === void 0 && (o = 32),
        this._subdivisionsX = i,
        this._subdivisionsY = i,
        this.subdivide(i);
        var s = this;
        s.createOrUpdateSubmeshesOctree && s.createOrUpdateSubmeshesOctree(o)
    }
    ,
    e.prototype.getHeightAtCoordinates = function(i, o) {
        var s = this.getWorldMatrix()
          , c = TmpVectors.Matrix[5];
        s.invertToRef(c);
        var d = TmpVectors.Vector3[8];
        if (Vector3.TransformCoordinatesFromFloatsToRef(i, 0, o, c, d),
        i = d.x,
        o = d.z,
        i < this._minX || i > this._maxX || o < this._minZ || o > this._maxZ)
            return this.position.y;
        (!this._heightQuads || this._heightQuads.length == 0) && (this._initHeightQuads(),
        this._computeHeightQuads());
        var _ = this._getFacetAt(i, o)
          , b = -(_.x * i + _.z * o + _.w) / _.y;
        return Vector3.TransformCoordinatesFromFloatsToRef(0, b, 0, s, d),
        d.y
    }
    ,
    e.prototype.getNormalAtCoordinates = function(i, o) {
        var s = new Vector3(0,1,0);
        return this.getNormalAtCoordinatesToRef(i, o, s),
        s
    }
    ,
    e.prototype.getNormalAtCoordinatesToRef = function(i, o, s) {
        var c = this.getWorldMatrix()
          , d = TmpVectors.Matrix[5];
        c.invertToRef(d);
        var _ = TmpVectors.Vector3[8];
        if (Vector3.TransformCoordinatesFromFloatsToRef(i, 0, o, d, _),
        i = _.x,
        o = _.z,
        i < this._minX || i > this._maxX || o < this._minZ || o > this._maxZ)
            return this;
        (!this._heightQuads || this._heightQuads.length == 0) && (this._initHeightQuads(),
        this._computeHeightQuads());
        var b = this._getFacetAt(i, o);
        return Vector3.TransformNormalFromFloatsToRef(b.x, b.y, b.z, c, s),
        this
    }
    ,
    e.prototype.updateCoordinateHeights = function() {
        return (!this._heightQuads || this._heightQuads.length == 0) && this._initHeightQuads(),
        this._computeHeightQuads(),
        this
    }
    ,
    e.prototype._getFacetAt = function(i, o) {
        var s = Math.floor((i + this._maxX) * this._subdivisionsX / this._width), c = Math.floor(-(o + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY), d = this._heightQuads[c * this._subdivisionsX + s], _;
        return o < d.slope.x * i + d.slope.y ? _ = d.facet1 : _ = d.facet2,
        _
    }
    ,
    e.prototype._initHeightQuads = function() {
        var i = this._subdivisionsX
          , o = this._subdivisionsY;
        this._heightQuads = new Array;
        for (var s = 0; s < o; s++)
            for (var c = 0; c < i; c++) {
                var d = {
                    slope: Vector2.Zero(),
                    facet1: new Vector4(0,0,0,0),
                    facet2: new Vector4(0,0,0,0)
                };
                this._heightQuads[s * i + c] = d
            }
        return this
    }
    ,
    e.prototype._computeHeightQuads = function() {
        var i = this.getVerticesData(VertexBuffer.PositionKind);
        if (!i)
            return this;
        for (var o = TmpVectors.Vector3[3], s = TmpVectors.Vector3[2], c = TmpVectors.Vector3[1], d = TmpVectors.Vector3[0], _ = TmpVectors.Vector3[4], b = TmpVectors.Vector3[5], k = TmpVectors.Vector3[6], j = TmpVectors.Vector3[7], $ = TmpVectors.Vector3[8], _e = 0, et = 0, tt = 0, rt = 0, it = 0, nt = 0, ot = 0, at = this._subdivisionsX, st = this._subdivisionsY, ut = 0; ut < st; ut++)
            for (var ct = 0; ct < at; ct++) {
                _e = ct * 3,
                et = ut * (at + 1) * 3,
                tt = (ut + 1) * (at + 1) * 3,
                o.x = i[et + _e],
                o.y = i[et + _e + 1],
                o.z = i[et + _e + 2],
                s.x = i[et + _e + 3],
                s.y = i[et + _e + 4],
                s.z = i[et + _e + 5],
                c.x = i[tt + _e],
                c.y = i[tt + _e + 1],
                c.z = i[tt + _e + 2],
                d.x = i[tt + _e + 3],
                d.y = i[tt + _e + 4],
                d.z = i[tt + _e + 5],
                rt = (d.z - o.z) / (d.x - o.x),
                it = o.z - rt * o.x,
                s.subtractToRef(o, _),
                c.subtractToRef(o, b),
                d.subtractToRef(o, k),
                Vector3.CrossToRef(k, b, j),
                Vector3.CrossToRef(_, k, $),
                j.normalize(),
                $.normalize(),
                nt = -(j.x * o.x + j.y * o.y + j.z * o.z),
                ot = -($.x * s.x + $.y * s.y + $.z * s.z);
                var lt = this._heightQuads[ut * at + ct];
                lt.slope.copyFromFloats(rt, it),
                lt.facet1.copyFromFloats(j.x, j.y, j.z, nt),
                lt.facet2.copyFromFloats($.x, $.y, $.z, ot)
            }
        return this
    }
    ,
    e.prototype.serialize = function(i) {
        a.prototype.serialize.call(this, i),
        i.subdivisionsX = this._subdivisionsX,
        i.subdivisionsY = this._subdivisionsY,
        i.minX = this._minX,
        i.maxX = this._maxX,
        i.minZ = this._minZ,
        i.maxZ = this._maxZ,
        i.width = this._width,
        i.height = this._height
    }
    ,
    e.Parse = function(i, o) {
        var s = new e(i.name,o);
        return s._subdivisionsX = i.subdivisionsX || 1,
        s._subdivisionsY = i.subdivisionsY || 1,
        s._minX = i.minX,
        s._maxX = i.maxX,
        s._minZ = i.minZ,
        s._maxZ = i.maxZ,
        s._width = i.width,
        s._height = i.height,
        s
    }
    ,
    e
}(Mesh);
function CreateGroundVertexData(a) {
    var e = [], i = [], o = [], s = [], c, d, _ = a.width || 1, b = a.height || 1, k = a.subdivisionsX || a.subdivisions || 1, j = a.subdivisionsY || a.subdivisions || 1;
    for (c = 0; c <= j; c++)
        for (d = 0; d <= k; d++) {
            var $ = new Vector3(d * _ / k - _ / 2,0,(j - c) * b / j - b / 2)
              , _e = new Vector3(0,1,0);
            i.push($.x, $.y, $.z),
            o.push(_e.x, _e.y, _e.z),
            s.push(d / k, 1 - c / j)
        }
    for (c = 0; c < j; c++)
        for (d = 0; d < k; d++)
            e.push(d + 1 + (c + 1) * (k + 1)),
            e.push(d + 1 + c * (k + 1)),
            e.push(d + c * (k + 1)),
            e.push(d + (c + 1) * (k + 1)),
            e.push(d + 1 + (c + 1) * (k + 1)),
            e.push(d + c * (k + 1));
    var et = new VertexData;
    return et.indices = e,
    et.positions = i,
    et.normals = o,
    et.uvs = s,
    et
}
function CreateTiledGroundVertexData(a) {
    var e = a.xmin !== void 0 && a.xmin !== null ? a.xmin : -1, i = a.zmin !== void 0 && a.zmin !== null ? a.zmin : -1, o = a.xmax !== void 0 && a.xmax !== null ? a.xmax : 1, s = a.zmax !== void 0 && a.zmax !== null ? a.zmax : 1, c = a.subdivisions || {
        w: 1,
        h: 1
    }, d = a.precision || {
        w: 1,
        h: 1
    }, _ = new Array, b = new Array, k = new Array, j = new Array, $, _e, et, tt;
    c.h = c.h < 1 ? 1 : c.h,
    c.w = c.w < 1 ? 1 : c.w,
    d.w = d.w < 1 ? 1 : d.w,
    d.h = d.h < 1 ? 1 : d.h;
    var rt = {
        w: (o - e) / c.w,
        h: (s - i) / c.h
    };
    function it(ot, at, st, ut) {
        var ct = b.length / 3
          , lt = d.w + 1;
        for ($ = 0; $ < d.h; $++)
            for (_e = 0; _e < d.w; _e++) {
                var ft = [ct + _e + $ * lt, ct + (_e + 1) + $ * lt, ct + (_e + 1) + ($ + 1) * lt, ct + _e + ($ + 1) * lt];
                _.push(ft[1]),
                _.push(ft[2]),
                _.push(ft[3]),
                _.push(ft[0]),
                _.push(ft[1]),
                _.push(ft[3])
            }
        var ht = Vector3.Zero()
          , pt = new Vector3(0,1,0);
        for ($ = 0; $ <= d.h; $++)
            for (ht.z = $ * (ut - at) / d.h + at,
            _e = 0; _e <= d.w; _e++)
                ht.x = _e * (st - ot) / d.w + ot,
                ht.y = 0,
                b.push(ht.x, ht.y, ht.z),
                k.push(pt.x, pt.y, pt.z),
                j.push(_e / d.w, $ / d.h)
    }
    for (et = 0; et < c.h; et++)
        for (tt = 0; tt < c.w; tt++)
            it(e + tt * rt.w, i + et * rt.h, e + (tt + 1) * rt.w, i + (et + 1) * rt.h);
    var nt = new VertexData;
    return nt.indices = _,
    nt.positions = b,
    nt.normals = k,
    nt.uvs = j,
    nt
}
function CreateGroundFromHeightMapVertexData(a) {
    var e = [], i = [], o = [], s = [], c, d, _ = a.colorFilter || new Color3(.3,.59,.11), b = a.alphaFilter || 0, k = !1;
    if (a.minHeight > a.maxHeight) {
        k = !0;
        var j = a.maxHeight;
        a.maxHeight = a.minHeight,
        a.minHeight = j
    }
    for (c = 0; c <= a.subdivisions; c++)
        for (d = 0; d <= a.subdivisions; d++) {
            var $ = new Vector3(d * a.width / a.subdivisions - a.width / 2,0,(a.subdivisions - c) * a.height / a.subdivisions - a.height / 2)
              , _e = ($.x + a.width / 2) / a.width * (a.bufferWidth - 1) | 0
              , et = (1 - ($.z + a.height / 2) / a.height) * (a.bufferHeight - 1) | 0
              , tt = (_e + et * a.bufferWidth) * 4
              , rt = a.buffer[tt] / 255
              , it = a.buffer[tt + 1] / 255
              , nt = a.buffer[tt + 2] / 255
              , ot = a.buffer[tt + 3] / 255;
            k && (rt = 1 - rt,
            it = 1 - it,
            nt = 1 - nt);
            var at = rt * _.r + it * _.g + nt * _.b;
            ot >= b ? $.y = a.minHeight + (a.maxHeight - a.minHeight) * at : $.y = a.minHeight - Epsilon,
            i.push($.x, $.y, $.z),
            o.push(0, 0, 0),
            s.push(d / a.subdivisions, 1 - c / a.subdivisions)
        }
    for (c = 0; c < a.subdivisions; c++)
        for (d = 0; d < a.subdivisions; d++) {
            var st = d + 1 + (c + 1) * (a.subdivisions + 1)
              , ut = d + 1 + c * (a.subdivisions + 1)
              , ct = d + c * (a.subdivisions + 1)
              , lt = d + (c + 1) * (a.subdivisions + 1)
              , ft = i[st * 3 + 1] >= a.minHeight
              , ht = i[ut * 3 + 1] >= a.minHeight
              , pt = i[ct * 3 + 1] >= a.minHeight;
            ft && ht && pt && (e.push(st),
            e.push(ut),
            e.push(ct));
            var dt = i[lt * 3 + 1] >= a.minHeight;
            dt && ft && pt && (e.push(lt),
            e.push(st),
            e.push(ct))
        }
    VertexData.ComputeNormals(i, e, o);
    var _t = new VertexData;
    return _t.indices = e,
    _t.positions = i,
    _t.normals = o,
    _t.uvs = s,
    _t
}
function CreateGround(a, e, i) {
    e === void 0 && (e = {});
    var o = new GroundMesh(a,i);
    o._setReady(!1),
    o._subdivisionsX = e.subdivisionsX || e.subdivisions || 1,
    o._subdivisionsY = e.subdivisionsY || e.subdivisions || 1,
    o._width = e.width || 1,
    o._height = e.height || 1,
    o._maxX = o._width / 2,
    o._maxZ = o._height / 2,
    o._minX = -o._maxX,
    o._minZ = -o._maxZ;
    var s = CreateGroundVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o._setReady(!0),
    o
}
function CreateTiledGround(a, e, i) {
    i === void 0 && (i = null);
    var o = new Mesh(a,i)
      , s = CreateTiledGroundVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
function CreateGroundFromHeightMap(a, e, i, o) {
    i === void 0 && (i = {}),
    o === void 0 && (o = null);
    var s = i.width || 10
      , c = i.height || 10
      , d = i.subdivisions || 1
      , _ = i.minHeight || 0
      , b = i.maxHeight || 1
      , k = i.colorFilter || new Color3(.3,.59,.11)
      , j = i.alphaFilter || 0
      , $ = i.updatable
      , _e = i.onReady;
    o = o || EngineStore.LastCreatedScene;
    var et = new GroundMesh(a,o);
    et._subdivisionsX = d,
    et._subdivisionsY = d,
    et._width = s,
    et._height = c,
    et._maxX = et._width / 2,
    et._maxZ = et._height / 2,
    et._minX = -et._maxX,
    et._minZ = -et._maxZ,
    et._setReady(!1);
    var tt = function(rt) {
        var it = rt.width
          , nt = rt.height;
        if (!o.isDisposed) {
            var ot = o == null ? void 0 : o.getEngine().resizeImageBitmap(rt, it, nt)
              , at = CreateGroundFromHeightMapVertexData({
                width: s,
                height: c,
                subdivisions: d,
                minHeight: _,
                maxHeight: b,
                colorFilter: k,
                buffer: ot,
                bufferWidth: it,
                bufferHeight: nt,
                alphaFilter: j
            });
            at.applyToMesh(et, $),
            _e && _e(et),
            et._setReady(!0)
        }
    };
    return Tools.LoadImage(e, tt, function() {}, o.offlineProvider),
    et
}
VertexData.CreateGround = CreateGroundVertexData;
VertexData.CreateTiledGround = CreateTiledGroundVertexData;
VertexData.CreateGroundFromHeightMap = CreateGroundFromHeightMapVertexData;
Mesh.CreateGround = function(a, e, i, o, s, c) {
    var d = {
        width: e,
        height: i,
        subdivisions: o,
        updatable: c
    };
    return CreateGround(a, d, s)
}
;
Mesh.CreateTiledGround = function(a, e, i, o, s, c, d, _, b) {
    var k = {
        xmin: e,
        zmin: i,
        xmax: o,
        zmax: s,
        subdivisions: c,
        precision: d,
        updatable: b
    };
    return CreateTiledGround(a, k, _)
}
;
Mesh.CreateGroundFromHeightMap = function(a, e, i, o, s, c, d, _, b, k, j) {
    var $ = {
        width: i,
        height: o,
        subdivisions: s,
        minHeight: c,
        maxHeight: d,
        updatable: b,
        onReady: k,
        alphaFilter: j
    };
    return CreateGroundFromHeightMap(a, e, $, _)
}
;
function CreateTube(a, e, i) {
    i === void 0 && (i = null);
    var o = e.path
      , s = e.instance
      , c = 1;
    e.radius !== void 0 ? c = e.radius : s && (c = s._creationDataStorage.radius);
    var d = e.tessellation || 64
      , _ = e.radiusFunction || null
      , b = e.cap || Mesh.NO_CAP
      , k = e.invertUV || !1
      , j = e.updatable
      , $ = Mesh._GetDefaultSideOrientation(e.sideOrientation);
    e.arc = e.arc && (e.arc <= 0 || e.arc > 1) ? 1 : e.arc || 1;
    var _e = function(at, st, ut, ct, lt, ft, ht, pt) {
        for (var dt = st.getTangents(), _t = st.getNormals(), mt = st.getDistances(), vt = Math.PI * 2, yt = vt / lt * pt, Et = function() {
            return ct
        }, At = ft || Et, gt, St, xt, bt, Rt = TmpVectors.Matrix[0], Mt = ht === Mesh.NO_CAP || ht === Mesh.CAP_END ? 0 : 2, Pt = 0; Pt < at.length; Pt++) {
            St = At(Pt, mt[Pt]),
            gt = Array(),
            xt = _t[Pt];
            for (var It = 0; It < lt; It++)
                Matrix.RotationAxisToRef(dt[Pt], yt * It, Rt),
                bt = gt[It] ? gt[It] : Vector3.Zero(),
                Vector3.TransformCoordinatesToRef(xt, Rt, bt),
                bt.scaleInPlace(St).addInPlace(at[Pt]),
                gt[It] = bt;
            ut[Mt] = gt,
            Mt++
        }
        var Dt = function(Ct, Ot) {
            for (var wt = Array(), Nt = 0; Nt < Ct; Nt++)
                wt.push(at[Ot]);
            return wt
        };
        switch (ht) {
        case Mesh.NO_CAP:
            break;
        case Mesh.CAP_START:
            ut[0] = Dt(lt, 0),
            ut[1] = ut[2].slice(0);
            break;
        case Mesh.CAP_END:
            ut[Mt] = ut[Mt - 1].slice(0),
            ut[Mt + 1] = Dt(lt, at.length - 1);
            break;
        case Mesh.CAP_ALL:
            ut[0] = Dt(lt, 0),
            ut[1] = ut[2].slice(0),
            ut[Mt] = ut[Mt - 1].slice(0),
            ut[Mt + 1] = Dt(lt, at.length - 1);
            break
        }
        return ut
    }, et, tt;
    if (s) {
        var rt = s._creationDataStorage
          , it = e.arc || rt.arc;
        return et = rt.path3D.update(o),
        tt = _e(o, et, rt.pathArray, c, rt.tessellation, _, rt.cap, it),
        s = CreateRibbon("", {
            pathArray: tt,
            instance: s
        }),
        rt.path3D = et,
        rt.pathArray = tt,
        rt.arc = it,
        rt.radius = c,
        s
    }
    et = new Path3D(o);
    var nt = new Array;
    b = b < 0 || b > 3 ? 0 : b,
    tt = _e(o, et, nt, c, d, _, b, e.arc);
    var ot = CreateRibbon(a, {
        pathArray: tt,
        closePath: !0,
        closeArray: !1,
        updatable: j,
        sideOrientation: $,
        invertUV: k,
        frontUVs: e.frontUVs,
        backUVs: e.backUVs
    }, i);
    return ot._creationDataStorage.pathArray = tt,
    ot._creationDataStorage.path3D = et,
    ot._creationDataStorage.tessellation = d,
    ot._creationDataStorage.cap = b,
    ot._creationDataStorage.arc = e.arc,
    ot._creationDataStorage.radius = c,
    ot
}
Mesh.CreateTube = function(a, e, i, o, s, c, d, _, b, k) {
    var j = {
        path: e,
        radius: i,
        tessellation: o,
        radiusFunction: s,
        arc: 1,
        cap: c,
        updatable: _,
        sideOrientation: b,
        instance: k
    };
    return CreateTube(a, j, d)
}
;
function CreatePolyhedronVertexData(a) {
    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 i = a.type && (a.type < 0 || a.type >= e.length) ? 0 : a.type || 0, o = a.size, s = a.sizeX || o || 1, c = a.sizeY || o || 1, d = a.sizeZ || o || 1, _ = a.custom || e[i], b = _.face.length, k = a.faceUV || new Array(b), j = a.faceColors, $ = a.flat === void 0 ? !0 : a.flat, _e = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, et = new Array, tt = new Array, rt = new Array, it = new Array, nt = new Array, ot = 0, at = 0, st = new Array, ut = 0, ct = 0, lt, ft, ht, pt, dt, _t;
    if ($)
        for (ct = 0; ct < b; ct++)
            j && j[ct] === void 0 && (j[ct] = new Color4(1,1,1,1)),
            k && k[ct] === void 0 && (k[ct] = new Vector4(0,0,1,1));
    if ($)
        for (ct = 0; ct < b; ct++) {
            var mt = _.face[ct].length;
            for (ht = 2 * Math.PI / mt,
            pt = .5 * Math.tan(ht / 2),
            dt = .5,
            ut = 0; ut < mt; ut++)
                et.push(_.vertex[_.face[ct][ut]][0] * s, _.vertex[_.face[ct][ut]][1] * c, _.vertex[_.face[ct][ut]][2] * d),
                st.push(ot),
                ot++,
                lt = k[ct].x + (k[ct].z - k[ct].x) * (.5 + pt),
                ft = k[ct].y + (k[ct].w - k[ct].y) * (dt - .5),
                it.push(lt, ft),
                _t = pt * Math.cos(ht) - dt * Math.sin(ht),
                dt = pt * Math.sin(ht) + dt * Math.cos(ht),
                pt = _t,
                j && nt.push(j[ct].r, j[ct].g, j[ct].b, j[ct].a);
            for (ut = 0; ut < mt - 2; ut++)
                tt.push(st[0 + at], st[ut + 2 + at], st[ut + 1 + at]);
            at += mt
        }
    else {
        for (ut = 0; ut < _.vertex.length; ut++)
            et.push(_.vertex[ut][0] * s, _.vertex[ut][1] * c, _.vertex[ut][2] * d),
            it.push(0, 0);
        for (ct = 0; ct < b; ct++)
            for (ut = 0; ut < _.face[ct].length - 2; ut++)
                tt.push(_.face[ct][0], _.face[ct][ut + 2], _.face[ct][ut + 1])
    }
    VertexData.ComputeNormals(et, tt, rt),
    VertexData._ComputeSides(_e, et, tt, rt, it, a.frontUVs, a.backUVs);
    var vt = new VertexData;
    return vt.positions = et,
    vt.indices = tt,
    vt.normals = rt,
    vt.uvs = it,
    j && $ && (vt.colors = nt),
    vt
}
function CreatePolyhedron(a, e, i) {
    e === void 0 && (e = {}),
    i === void 0 && (i = null);
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreatePolyhedronVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreatePolyhedron = CreatePolyhedronVertexData;
Mesh.CreatePolyhedron = function(a, e, i) {
    return CreatePolyhedron(a, e, i)
}
;
function CreateIcoSphereVertexData(a) {
    var e = a.sideOrientation || VertexData.DEFAULTSIDE, i = a.radius || 1, o = a.flat === void 0 ? !0 : a.flat, s = a.subdivisions || 4, c = a.radiusX || i, d = a.radiusY || i, _ = a.radiusZ || i, b = (1 + Math.sqrt(5)) / 2, k = [-1, b, -0, 1, b, 0, -1, -b, 0, 1, -b, 0, 0, -1, -b, 0, 1, -b, 0, -1, b, 0, 1, b, b, 0, 1, b, 0, -1, -b, 0, 1, -b, 0, -1], j = [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], $ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 2, 3, 3, 3, 4, 7, 8, 9, 9, 10, 11], _e = [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], et = 138 / 1024, tt = 239 / 1024, rt = 60 / 1024, it = 26 / 1024, nt = -40 / 1024, ot = 20 / 1024, at = [0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0], st = new Array, ut = new Array, ct = new Array, lt = new Array, ft = 0, ht = new Array(3), pt = new Array(3), dt;
    for (dt = 0; dt < 3; dt++)
        ht[dt] = Vector3.Zero(),
        pt[dt] = Vector2.Zero();
    for (var _t = 0; _t < 20; _t++) {
        for (dt = 0; dt < 3; dt++) {
            var mt = j[3 * _t + dt];
            ht[dt].copyFromFloats(k[3 * $[mt]], k[3 * $[mt] + 1], k[3 * $[mt] + 2]),
            ht[dt].normalize().scaleInPlace(i),
            pt[dt].copyFromFloats(_e[2 * mt] * et + rt + at[_t] * nt, _e[2 * mt + 1] * tt + it + at[_t] * ot)
        }
        for (var vt = function(gt, St, xt, bt) {
            var Rt = Vector3.Lerp(ht[0], ht[2], St / s)
              , Mt = Vector3.Lerp(ht[1], ht[2], St / s)
              , Pt = s === St ? ht[2] : Vector3.Lerp(Rt, Mt, gt / (s - St));
            Pt.normalize();
            var It;
            if (o) {
                var Dt = Vector3.Lerp(ht[0], ht[2], bt / s)
                  , Ct = Vector3.Lerp(ht[1], ht[2], bt / s);
                It = Vector3.Lerp(Dt, Ct, xt / (s - bt))
            } else
                It = new Vector3(Pt.x,Pt.y,Pt.z);
            It.x /= c,
            It.y /= d,
            It.z /= _,
            It.normalize();
            var Ot = Vector2.Lerp(pt[0], pt[2], St / s)
              , wt = Vector2.Lerp(pt[1], pt[2], St / s)
              , Nt = s === St ? pt[2] : Vector2.Lerp(Ot, wt, gt / (s - St));
            ut.push(Pt.x * c, Pt.y * d, Pt.z * _),
            ct.push(It.x, It.y, It.z),
            lt.push(Nt.x, Nt.y),
            st.push(ft),
            ft++
        }, yt = 0; yt < s; yt++)
            for (var Et = 0; Et + yt < s; Et++)
                vt(Et, yt, Et + 1 / 3, yt + 1 / 3),
                vt(Et + 1, yt, Et + 1 / 3, yt + 1 / 3),
                vt(Et, yt + 1, Et + 1 / 3, yt + 1 / 3),
                Et + yt + 1 < s && (vt(Et + 1, yt, Et + 2 / 3, yt + 2 / 3),
                vt(Et + 1, yt + 1, Et + 2 / 3, yt + 2 / 3),
                vt(Et, yt + 1, Et + 2 / 3, yt + 2 / 3))
    }
    VertexData._ComputeSides(e, ut, st, ct, lt, a.frontUVs, a.backUVs);
    var At = new VertexData;
    return At.indices = st,
    At.positions = ut,
    At.normals = ct,
    At.uvs = lt,
    At
}
function CreateIcoSphere(a, e, i) {
    e === void 0 && (e = {}),
    i === void 0 && (i = null);
    var o = new Mesh(a,i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    o._originalBuilderSideOrientation = e.sideOrientation;
    var s = CreateIcoSphereVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
VertexData.CreateIcoSphere = CreateIcoSphereVertexData;
Mesh.CreateIcoSphere = function(a, e, i) {
    return CreateIcoSphere(a, e, i)
}
;
function CreateDecal(a, e, i) {
    var o = e.getIndices()
      , s = e.getVerticesData(VertexBuffer.PositionKind)
      , c = e.getVerticesData(VertexBuffer.NormalKind)
      , d = e.getVerticesData(VertexBuffer.UVKind)
      , _ = i.position || Vector3.Zero()
      , b = i.normal || Vector3.Up()
      , k = i.size || Vector3.One()
      , j = i.angle || 0;
    if (!b) {
        var $ = new Vector3(0,0,1)
          , _e = e.getScene().activeCamera
          , et = Vector3.TransformCoordinates($, _e.getWorldMatrix());
        b = _e.globalPosition.subtract(et)
    }
    var tt = -Math.atan2(b.z, b.x) - Math.PI / 2
      , rt = Math.sqrt(b.x * b.x + b.z * b.z)
      , it = Math.atan2(b.y, rt)
      , nt = Matrix.RotationYawPitchRoll(tt, it, j).multiply(Matrix.Translation(_.x, _.y, _.z))
      , ot = Matrix.Invert(nt)
      , at = e.getWorldMatrix()
      , st = at.multiply(ot)
      , ut = new VertexData;
    ut.indices = [],
    ut.positions = [],
    ut.normals = [],
    ut.uvs = [];
    for (var ct = 0, lt = function(vt) {
        var yt = new PositionNormalTextureVertex;
        if (!o || !s || !c)
            return yt;
        var Et = o[vt];
        return yt.position = new Vector3(s[Et * 3],s[Et * 3 + 1],s[Et * 3 + 2]),
        yt.position = Vector3.TransformCoordinates(yt.position, st),
        yt.normal = new Vector3(c[Et * 3],c[Et * 3 + 1],c[Et * 3 + 2]),
        yt.normal = Vector3.TransformNormal(yt.normal, st),
        i.captureUVS && d && (yt.uv = new Vector2(d[Et * 2],d[Et * 2 + 1])),
        yt
    }, ft = function(vt, yt) {
        if (vt.length === 0)
            return vt;
        for (var Et = .5 * Math.abs(Vector3.Dot(k, yt)), At = function(Ft, Vt) {
            var Lt = Vector3.GetClipFactor(Ft.position, Vt.position, yt, Et);
            return new PositionNormalTextureVertex(Vector3.Lerp(Ft.position, Vt.position, Lt),Vector3.Lerp(Ft.normal, Vt.normal, Lt))
        }, gt = new Array, St = 0; St < vt.length; St += 3) {
            var xt, bt, Rt, Mt = 0, Pt = null, It = null, Dt = null, Ct = null, Ot = Vector3.Dot(vt[St].position, yt) - Et, wt = Vector3.Dot(vt[St + 1].position, yt) - Et, Nt = Vector3.Dot(vt[St + 2].position, yt) - Et;
            switch (xt = Ot > 0,
            bt = wt > 0,
            Rt = Nt > 0,
            Mt = (xt ? 1 : 0) + (bt ? 1 : 0) + (Rt ? 1 : 0),
            Mt) {
            case 0:
                gt.push(vt[St]),
                gt.push(vt[St + 1]),
                gt.push(vt[St + 2]);
                break;
            case 1:
                if (xt && (Pt = vt[St + 1],
                It = vt[St + 2],
                Dt = At(vt[St], Pt),
                Ct = At(vt[St], It)),
                bt) {
                    Pt = vt[St],
                    It = vt[St + 2],
                    Dt = At(vt[St + 1], Pt),
                    Ct = At(vt[St + 1], It),
                    gt.push(Dt),
                    gt.push(It.clone()),
                    gt.push(Pt.clone()),
                    gt.push(It.clone()),
                    gt.push(Dt.clone()),
                    gt.push(Ct);
                    break
                }
                Rt && (Pt = vt[St],
                It = vt[St + 1],
                Dt = At(vt[St + 2], Pt),
                Ct = At(vt[St + 2], It)),
                Pt && It && Dt && Ct && (gt.push(Pt.clone()),
                gt.push(It.clone()),
                gt.push(Dt),
                gt.push(Ct),
                gt.push(Dt.clone()),
                gt.push(It.clone()));
                break;
            case 2:
                xt || (Pt = vt[St].clone(),
                It = At(Pt, vt[St + 1]),
                Dt = At(Pt, vt[St + 2]),
                gt.push(Pt),
                gt.push(It),
                gt.push(Dt)),
                bt || (Pt = vt[St + 1].clone(),
                It = At(Pt, vt[St + 2]),
                Dt = At(Pt, vt[St]),
                gt.push(Pt),
                gt.push(It),
                gt.push(Dt)),
                Rt || (Pt = vt[St + 2].clone(),
                It = At(Pt, vt[St]),
                Dt = At(Pt, vt[St + 1]),
                gt.push(Pt),
                gt.push(It),
                gt.push(Dt));
                break
            }
        }
        return gt
    }, ht = 0; ht < o.length; ht += 3) {
        var pt = new Array;
        if (pt.push(lt(ht)),
        pt.push(lt(ht + 1)),
        pt.push(lt(ht + 2)),
        pt = ft(pt, new Vector3(1,0,0)),
        pt = ft(pt, new Vector3(-1,0,0)),
        pt = ft(pt, new Vector3(0,1,0)),
        pt = ft(pt, new Vector3(0,-1,0)),
        pt = ft(pt, new Vector3(0,0,1)),
        pt = ft(pt, new Vector3(0,0,-1)),
        pt.length !== 0)
            for (var dt = 0; dt < pt.length; dt++) {
                var _t = pt[dt];
                ut.indices.push(ct),
                _t.position.toArray(ut.positions, ct * 3),
                _t.normal.toArray(ut.normals, ct * 3),
                i.captureUVS ? _t.uv.toArray(ut.uvs, ct * 2) : (ut.uvs.push(.5 + _t.position.x / k.x),
                ut.uvs.push(.5 + _t.position.y / k.y)),
                ct++
            }
    }
    var mt = new Mesh(a,e.getScene());
    return ut.applyToMesh(mt),
    mt.position = _.clone(),
    mt.rotation = new Vector3(it,tt,j),
    mt
}
Mesh.CreateDecal = function(a, e, i, o, s, c) {
    var d = {
        position: i,
        normal: o,
        size: s,
        angle: c
    };
    return CreateDecal(a, e, d)
}
;
function CreateCapsuleVertexData(a) {
    a === void 0 && (a = {
        subdivisions: 2,
        tessellation: 16,
        height: 1,
        radius: .25,
        capSubdivisions: 6
    });
    var e = Math.max(a.subdivisions ? a.subdivisions : 2, 1), i = Math.max(a.tessellation ? a.tessellation : 16, 3), o = Math.max(a.height ? a.height : 1, 0), s = Math.max(a.radius ? a.radius : .25, 0), c = Math.max(a.capSubdivisions ? a.capSubdivisions : 6, 1), d = i, _ = e, b = Math.max(a.radiusTop ? a.radiusTop : s, 0), k = Math.max(a.radiusBottom ? a.radiusBottom : s, 0), j = o - (b + k), $ = 0, _e = 2 * Math.PI, et = Math.max(a.topCapSubdivisions ? a.topCapSubdivisions : c, 1), tt = Math.max(a.bottomCapSubdivisions ? a.bottomCapSubdivisions : c, 1), rt = Math.acos((k - b) / o), it = [], nt = [], ot = [], at = [], st = 0, ut = [], ct = j * .5, lt = Math.PI * .5, ft, ht, pt = Vector3.Zero(), dt = Vector3.Zero(), _t = Math.cos(rt), mt = Math.sin(rt), vt = new Vector2(b * mt,ct + b * _t).subtract(new Vector2(k * mt,-ct + k * _t)).length(), yt = b * rt + vt + k * (lt - rt), Et = 0;
    for (ht = 0; ht <= et; ht++) {
        var At = []
          , gt = lt - rt * (ht / et);
        Et += b * rt / et;
        var St = Math.cos(gt)
          , xt = Math.sin(gt)
          , bt = St * b;
        for (ft = 0; ft <= d; ft++) {
            var Rt = ft / d
              , Mt = Rt * _e + $
              , Pt = Math.sin(Mt)
              , It = Math.cos(Mt);
            dt.x = bt * Pt,
            dt.y = ct + xt * b,
            dt.z = bt * It,
            nt.push(dt.x, dt.y, dt.z),
            pt.set(St * Pt, xt, St * It),
            ot.push(pt.x, pt.y, pt.z),
            at.push(Rt, 1 - Et / yt),
            At.push(st),
            st++
        }
        ut.push(At)
    }
    var Dt = o - b - k + _t * b - _t * k
      , Ct = mt * (k - b) / Dt;
    for (ht = 1; ht <= _; ht++) {
        var At = [];
        Et += vt / _;
        var bt = mt * (ht * (k - b) / _ + b);
        for (ft = 0; ft <= d; ft++) {
            var Rt = ft / d
              , Mt = Rt * _e + $
              , Pt = Math.sin(Mt)
              , It = Math.cos(Mt);
            dt.x = bt * Pt,
            dt.y = ct + _t * b - ht * Dt / _,
            dt.z = bt * It,
            nt.push(dt.x, dt.y, dt.z),
            pt.set(Pt, Ct, It).normalize(),
            ot.push(pt.x, pt.y, pt.z),
            at.push(Rt, 1 - Et / yt),
            At.push(st),
            st++
        }
        ut.push(At)
    }
    for (ht = 1; ht <= tt; ht++) {
        var At = []
          , gt = lt - rt - (Math.PI - rt) * (ht / tt);
        Et += k * rt / tt;
        var St = Math.cos(gt)
          , xt = Math.sin(gt)
          , bt = St * k;
        for (ft = 0; ft <= d; ft++) {
            var Rt = ft / d
              , Mt = Rt * _e + $
              , Pt = Math.sin(Mt)
              , It = Math.cos(Mt);
            dt.x = bt * Pt,
            dt.y = -ct + xt * k,
            dt.z = bt * It,
            nt.push(dt.x, dt.y, dt.z),
            pt.set(St * Pt, xt, St * It),
            ot.push(pt.x, pt.y, pt.z),
            at.push(Rt, 1 - Et / yt),
            At.push(st),
            st++
        }
        ut.push(At)
    }
    for (ft = 0; ft < d; ft++)
        for (ht = 0; ht < et + _ + tt; ht++) {
            var Ot = ut[ht][ft]
              , wt = ut[ht + 1][ft]
              , Nt = ut[ht + 1][ft + 1]
              , Ft = ut[ht][ft + 1];
            it.push(Ot),
            it.push(wt),
            it.push(Ft),
            it.push(wt),
            it.push(Nt),
            it.push(Ft)
        }
    if (it = it.reverse(),
    a.orientation && !a.orientation.equals(Vector3.Up())) {
        var Vt = new Matrix;
        a.orientation.clone().scale(Math.PI * .5).cross(Vector3.Up()).toQuaternion().toRotationMatrix(Vt);
        for (var Lt = Vector3.Zero(), kt = 0; kt < nt.length; kt += 3)
            Lt.set(nt[kt], nt[kt + 1], nt[kt + 2]),
            Vector3.TransformCoordinatesToRef(Lt.clone(), Vt, Lt),
            nt[kt] = Lt.x,
            nt[kt + 1] = Lt.y,
            nt[kt + 2] = Lt.z
    }
    var Bt = new VertexData;
    return Bt.positions = nt,
    Bt.normals = ot,
    Bt.uvs = at,
    Bt.indices = it,
    Bt
}
function CreateCapsule(a, e, i) {
    e === void 0 && (e = {
        orientation: Vector3.Up(),
        subdivisions: 2,
        tessellation: 16,
        height: 1,
        radius: .25,
        capSubdivisions: 6,
        updatable: !1
    }),
    i === void 0 && (i = null);
    var o = new Mesh(a,i)
      , s = CreateCapsuleVertexData(e);
    return s.applyToMesh(o, e.updatable),
    o
}
Mesh.CreateCapsule = function(a, e, i) {
    return CreateCapsule(a, e, i)
}
;
VertexData.CreateCapsule = CreateCapsuleVertexData;
var _IsoVector = function() {
    function a(e, i) {
        e === void 0 && (e = 0),
        i === void 0 && (i = 0),
        this.x = e,
        this.y = i,
        e !== Math.floor(e) && Logger$2.Warn("x is not an integer, floor(x) used"),
        i !== Math.floor(i) && Logger$2.Warn("y is not an integer, floor(y) used")
    }
    return a.prototype.clone = function() {
        return new a(this.x,this.y)
    }
    ,
    a.prototype.rotate60About = function(e) {
        var i = this.x;
        return this.x = e.x + e.y - this.y,
        this.y = i + this.y - e.x,
        this
    }
    ,
    a.prototype.rotateNeg60About = function(e) {
        var i = this.x;
        return this.x = i + this.y - e.y,
        this.y = e.x + e.y - i,
        this
    }
    ,
    a.prototype.rotate120 = function(e, i) {
        e !== Math.floor(e) && Logger$2.Warn("m not an integer only floor(m) used"),
        i !== Math.floor(i) && Logger$2.Warn("n not an integer only floor(n) used");
        var o = this.x;
        return this.x = e - o - this.y,
        this.y = i + o,
        this
    }
    ,
    a.prototype.rotateNeg120 = function(e, i) {
        e !== Math.floor(e) && Logger$2.Warn("m is not an integer, floor(m) used"),
        i !== Math.floor(i) && Logger$2.Warn("n is not an integer,   floor(n) used");
        var o = this.x;
        return this.x = this.y - i,
        this.y = e + i - o - this.y,
        this
    }
    ,
    a.prototype.toCartesianOrigin = function(e, i) {
        var o = Vector3.Zero();
        return o.x = e.x + 2 * this.x * i + this.y * i,
        o.y = e.y + Math.sqrt(3) * this.y * i,
        o
    }
    ,
    a.Zero = function() {
        return new a(0,0)
    }
    ,
    a
}()
  , _PrimaryIsoTriangle = function() {
    function a() {
        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 a.prototype.setIndices = function() {
        var e = 12
          , i = {}
          , o = this.m
          , s = this.n
          , c = o
          , d = 1
          , _ = 0;
        s !== 0 && (c = Scalar.HCF(o, s)),
        d = o / c,
        _ = s / c;
        var b, k, j, $, _e, et = _IsoVector.Zero(), tt = new _IsoVector(o,s), rt = new _IsoVector(-s,o + s), it = _IsoVector.Zero(), nt = _IsoVector.Zero(), ot = _IsoVector.Zero(), at = [], st, ut, ct, lt, ft = [], ht = 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 pt = 0; pt < 20; pt++) {
            if (at = this.IDATA.face[pt],
            j = at[2],
            $ = at[1],
            _e = at[0],
            ct = et.x + "|" + et.y,
            st = pt + "|" + ct,
            st in i || (i[st] = j,
            ft[j] = [at[ht[ct][0]], ht[ct][1]]),
            ct = tt.x + "|" + tt.y,
            st = pt + "|" + ct,
            st in i || (i[st] = $,
            ft[$] = [at[ht[ct][0]], ht[ct][1]]),
            ct = rt.x + "|" + rt.y,
            st = pt + "|" + ct,
            st in i || (i[st] = _e,
            ft[_e] = [at[ht[ct][0]], ht[ct][1]]),
            b = this.IDATA.edgematch[pt][0],
            k = this.IDATA.edgematch[pt][1],
            k === "B")
                for (var dt = 1; dt < c; dt++)
                    nt.x = o - dt * (d + _),
                    nt.y = s + dt * d,
                    ot.x = -dt * _,
                    ot.y = dt * (d + _),
                    ct = nt.x + "|" + nt.y,
                    lt = ot.x + "|" + ot.y,
                    _t(pt, b, ct, lt);
            if (k === "O")
                for (var dt = 1; dt < c; dt++)
                    ot.x = -dt * _,
                    ot.y = dt * (d + _),
                    it.x = dt * d,
                    it.y = dt * _,
                    ct = ot.x + "|" + ot.y,
                    lt = it.x + "|" + it.y,
                    _t(pt, b, ct, lt);
            if (b = this.IDATA.edgematch[pt][2],
            k = this.IDATA.edgematch[pt][3],
            k && k === "A")
                for (var dt = 1; dt < c; dt++)
                    it.x = dt * d,
                    it.y = dt * _,
                    nt.x = o - (c - dt) * (d + _),
                    nt.y = s + (c - dt) * d,
                    ct = it.x + "|" + it.y,
                    lt = nt.x + "|" + nt.y,
                    _t(pt, b, ct, lt);
            for (var dt = 0; dt < this.vertices.length; dt++)
                ct = this.vertices[dt].x + "|" + this.vertices[dt].y,
                st = pt + "|" + ct,
                st in i || (i[st] = e++,
                ht[ct][0] > 2 ? ft[i[st]] = [-ht[ct][0], ht[ct][1], i[st]] : ft[i[st]] = [at[ht[ct][0]], ht[ct][1], i[st]])
        }
        function _t(mt, vt, yt, Et) {
            st = mt + "|" + yt,
            ut = vt + "|" + Et,
            st in i || ut in i ? st in i && !(ut in i) ? i[ut] = i[st] : ut in i && !(st in i) && (i[st] = i[ut]) : (i[st] = e,
            i[ut] = e,
            e++),
            ht[yt][0] > 2 ? ft[i[st]] = [-ht[yt][0], ht[yt][1], i[st]] : ft[i[st]] = [at[ht[yt][0]], ht[yt][1], i[st]]
        }
        this.closestTo = ft,
        this.vecToIdx = i
    }
    ,
    a.prototype.calcCoeffs = function() {
        var e = this.m
          , i = this.n
          , o = Math.sqrt(3) / 3
          , s = e * e + i * i + e * i;
        this.coau = (e + i) / s,
        this.cobu = -i / s,
        this.coav = -o * (e - i) / s,
        this.cobv = o * (2 * e + i) / s
    }
    ,
    a.prototype.createInnerFacets = function() {
        for (var e = this.m, i = this.n, o = 0; o < i + e + 1; o++)
            for (var s = this.min[o]; s < this.max[o] + 1; s++)
                s < this.max[o] && s < this.max[o + 1] + 1 && this.innerFacets.push(["|" + s + "|" + o, "|" + s + "|" + (o + 1), "|" + (s + 1) + "|" + o]),
                o > 0 && s < this.max[o - 1] && s + 1 < this.max[o] + 1 && this.innerFacets.push(["|" + s + "|" + o, "|" + (s + 1) + "|" + o, "|" + (s + 1) + "|" + (o - 1)])
    }
    ,
    a.prototype.edgeVecsABOB = function() {
        for (var e = this.m, i = this.n, o = new _IsoVector(-i,e + i), s = 1; s < e + i; s++) {
            var c = new _IsoVector(this.min[s],s)
              , d = new _IsoVector(this.min[s - 1],s - 1)
              , _ = new _IsoVector(this.min[s + 1],s + 1)
              , b = c.clone()
              , k = d.clone()
              , j = _.clone();
            b.rotate60About(o),
            k.rotate60About(o),
            j.rotate60About(o);
            var $ = new _IsoVector(this.max[b.y],b.y)
              , _e = new _IsoVector(this.max[b.y - 1],b.y - 1)
              , et = new _IsoVector(this.max[b.y - 1] - 1,b.y - 1);
            (b.x !== $.x || b.y !== $.y) && (b.x !== _e.x ? (this.vertexTypes.push([1, 0, 0]),
            this.isoVecsABOB.push([c, _e, et]),
            this.vertexTypes.push([1, 0, 0]),
            this.isoVecsABOB.push([c, et, $])) : b.y === j.y ? (this.vertexTypes.push([1, 1, 0]),
            this.isoVecsABOB.push([c, d, _e]),
            this.vertexTypes.push([1, 0, 1]),
            this.isoVecsABOB.push([c, _e, _])) : (this.vertexTypes.push([1, 1, 0]),
            this.isoVecsABOB.push([c, d, _e]),
            this.vertexTypes.push([1, 0, 0]),
            this.isoVecsABOB.push([c, _e, $])))
        }
    }
    ,
    a.prototype.mapABOBtoOBOA = function() {
        for (var e = new _IsoVector(0,0), i = 0; i < this.isoVecsABOB.length; i++) {
            for (var o = [], s = 0; s < 3; s++)
                e.x = this.isoVecsABOB[i][s].x,
                e.y = this.isoVecsABOB[i][s].y,
                this.vertexTypes[i][s] === 0 && e.rotateNeg120(this.m, this.n),
                o.push(e.clone());
            this.isoVecsOBOA.push(o)
        }
    }
    ,
    a.prototype.mapABOBtoBAOA = function() {
        for (var e = new _IsoVector(0,0), i = 0; i < this.isoVecsABOB.length; i++) {
            for (var o = [], s = 0; s < 3; s++)
                e.x = this.isoVecsABOB[i][s].x,
                e.y = this.isoVecsABOB[i][s].y,
                this.vertexTypes[i][s] === 1 && e.rotate120(this.m, this.n),
                o.push(e.clone());
            this.isoVecsBAOA.push(o)
        }
    }
    ,
    a.prototype.MapToFace = function(e, i) {
        for (var o = this.IDATA.face[e], s = o[2], c = o[1], d = o[0], _ = Vector3.FromArray(this.IDATA.vertex[s]), b = Vector3.FromArray(this.IDATA.vertex[c]), k = Vector3.FromArray(this.IDATA.vertex[d]), j = b.subtract(_), $ = k.subtract(_), _e = j.scale(this.coau).add($.scale(this.cobu)), et = j.scale(this.coav).add($.scale(this.cobv)), tt = [], rt, it = TmpVectors.Vector3[0], nt = 0; nt < this.cartesian.length; nt++)
            it = _e.scale(this.cartesian[nt].x).add(et.scale(this.cartesian[nt].y)).add(_),
            tt[nt] = [it.x, it.y, it.z],
            rt = e + "|" + this.vertices[nt].x + "|" + this.vertices[nt].y,
            i.vertex[this.vecToIdx[rt]] = [it.x, it.y, it.z]
    }
    ,
    a.prototype.build = function(e, i) {
        var o = new Array
          , s = _IsoVector.Zero()
          , c = new _IsoVector(e,i)
          , d = new _IsoVector(-i,e + i);
        o.push(s, c, d);
        for (var _ = i; _ < e + 1; _++)
            for (var b = 0; b < e + 1 - _; b++)
                o.push(new _IsoVector(b,_));
        if (i > 0) {
            for (var k = Scalar.HCF(e, i), j = e / k, $ = i / k, _e = 1; _e < k; _e++)
                o.push(new _IsoVector(_e * j,_e * $)),
                o.push(new _IsoVector(-_e * $,_e * (j + $))),
                o.push(new _IsoVector(e - _e * (j + $),i + _e * j));
            for (var et = e / i, tt = 1; tt < i; tt++)
                for (var rt = 0; rt < tt * et; rt++)
                    o.push(new _IsoVector(rt,tt)),
                    o.push(new _IsoVector(rt,tt).rotate120(e, i)),
                    o.push(new _IsoVector(rt,tt).rotateNeg120(e, i))
        }
        o.sort(function(yt, Et) {
            return yt.x - Et.x
        }),
        o.sort(function(yt, Et) {
            return yt.y - Et.y
        });
        for (var it = new Array(e + i + 1), nt = new Array(e + i + 1), _e = 0; _e < it.length; _e++)
            it[_e] = 1 / 0,
            nt[_e] = -1 / 0;
        for (var ot = 0, at = 0, st = o.length, _e = 0; _e < st; _e++)
            at = o[_e].x,
            ot = o[_e].y,
            it[ot] = Math.min(at, it[ot]),
            nt[ot] = Math.max(at, nt[ot]);
        for (var ut = function(yt, Et) {
            var At = yt.clone();
            return Et === "A" && At.rotateNeg120(e, i),
            Et === "B" && At.rotate120(e, i),
            At.x < 0 ? At.y : At.x + At.y
        }, ct = [], lt = [], ft = [], ht = [], pt = {}, dt = [], _t = -1, mt = -1, _e = 0; _e < st; _e++)
            ct[_e] = o[_e].toCartesianOrigin(new _IsoVector(0,0), .5),
            lt[_e] = ut(o[_e], "O"),
            ft[_e] = ut(o[_e], "A"),
            ht[_e] = ut(o[_e], "B"),
            lt[_e] === ft[_e] && ft[_e] === ht[_e] ? (_t = 3,
            mt = lt[_e]) : lt[_e] === ft[_e] ? (_t = 4,
            mt = lt[_e]) : ft[_e] === ht[_e] ? (_t = 5,
            mt = ft[_e]) : ht[_e] === lt[_e] && (_t = 6,
            mt = lt[_e]),
            lt[_e] < ft[_e] && lt[_e] < ht[_e] && (_t = 2,
            mt = lt[_e]),
            ft[_e] < lt[_e] && ft[_e] < ht[_e] && (_t = 1,
            mt = ft[_e]),
            ht[_e] < ft[_e] && ht[_e] < lt[_e] && (_t = 0,
            mt = ht[_e]),
            dt.push([_t, mt, o[_e].x, o[_e].y]);
        dt.sort(function(yt, Et) {
            return yt[2] - Et[2]
        }),
        dt.sort(function(yt, Et) {
            return yt[3] - Et[3]
        }),
        dt.sort(function(yt, Et) {
            return yt[1] - Et[1]
        }),
        dt.sort(function(yt, Et) {
            return yt[0] - Et[0]
        });
        for (var vt = 0; vt < dt.length; vt++)
            pt[dt[vt][2] + "|" + dt[vt][3]] = [dt[vt][0], dt[vt][1], vt];
        return this.m = e,
        this.n = i,
        this.vertices = o,
        this.vertByDist = pt,
        this.cartesian = ct,
        this.min = it,
        this.max = nt,
        this
    }
    ,
    a
}()
  , PolyhedronData = function() {
    function a(e, i, o, s) {
        this.name = e,
        this.category = i,
        this.vertex = o,
        this.face = s
    }
    return a
}()
  , GeodesicData = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e.prototype.innerToData = function(i, o) {
        for (var s = 0; s < o.innerFacets.length; s++)
            this.face.push(o.innerFacets[s].map(function(c) {
                return o.vecToIdx[i + c]
            }))
    }
    ,
    e.prototype.mapABOBtoDATA = function(i, o) {
        for (var s = o.IDATA.edgematch[i][0], c = 0; c < o.isoVecsABOB.length; c++) {
            for (var d = [], _ = 0; _ < 3; _++)
                o.vertexTypes[c][_] === 0 ? d.push(i + "|" + o.isoVecsABOB[c][_].x + "|" + o.isoVecsABOB[c][_].y) : d.push(s + "|" + o.isoVecsABOB[c][_].x + "|" + o.isoVecsABOB[c][_].y);
            this.face.push([o.vecToIdx[d[0]], o.vecToIdx[d[1]], o.vecToIdx[d[2]]])
        }
    }
    ,
    e.prototype.mapOBOAtoDATA = function(i, o) {
        for (var s = o.IDATA.edgematch[i][0], c = 0; c < o.isoVecsOBOA.length; c++) {
            for (var d = [], _ = 0; _ < 3; _++)
                o.vertexTypes[c][_] === 1 ? d.push(i + "|" + o.isoVecsOBOA[c][_].x + "|" + o.isoVecsOBOA[c][_].y) : d.push(s + "|" + o.isoVecsOBOA[c][_].x + "|" + o.isoVecsOBOA[c][_].y);
            this.face.push([o.vecToIdx[d[0]], o.vecToIdx[d[1]], o.vecToIdx[d[2]]])
        }
    }
    ,
    e.prototype.mapBAOAtoDATA = function(i, o) {
        for (var s = o.IDATA.edgematch[i][2], c = 0; c < o.isoVecsBAOA.length; c++) {
            for (var d = [], _ = 0; _ < 3; _++)
                o.vertexTypes[c][_] === 1 ? d.push(i + "|" + o.isoVecsBAOA[c][_].x + "|" + o.isoVecsBAOA[c][_].y) : d.push(s + "|" + o.isoVecsBAOA[c][_].x + "|" + o.isoVecsBAOA[c][_].y);
            this.face.push([o.vecToIdx[d[0]], o.vecToIdx[d[1]], o.vecToIdx[d[2]]])
        }
    }
    ,
    e.prototype.orderData = function(i) {
        for (var o = [], s = 0; s < 13; s++)
            o[s] = [];
        for (var c = i.closestTo, s = 0; s < c.length; s++)
            c[s][0] > -1 ? c[s][1] > 0 && o[c[s][0]].push([s, c[s][1]]) : o[12].push([s, c[s][0]]);
        for (var d = [], s = 0; s < 12; s++)
            d[s] = s;
        for (var _ = 12, s = 0; s < 12; s++) {
            o[s].sort(function(j, $) {
                return j[1] - $[1]
            });
            for (var b = 0; b < o[s].length; b++)
                d[o[s][b][0]] = _++
        }
        for (var b = 0; b < o[12].length; b++)
            d[o[12][b][0]] = _++;
        for (var s = 0; s < this.vertex.length; s++)
            this.vertex[s].push(d[s]);
        this.vertex.sort(function(k, j) {
            return k[3] - j[3]
        });
        for (var s = 0; s < this.vertex.length; s++)
            this.vertex[s].pop();
        for (var s = 0; s < this.face.length; s++)
            for (var b = 0; b < this.face[s].length; b++)
                this.face[s][b] = d[this.face[s][b]];
        this.sharedNodes = o[12].length,
        this.poleNodes = this.vertex.length - this.sharedNodes
    }
    ,
    e.prototype.setOrder = function(i, o) {
        var s = []
          , c = []
          , d = o.pop();
        c.push(d);
        var _ = this.face[d].indexOf(i);
        _ = (_ + 2) % 3;
        var b = this.face[d][_];
        s.push(b);
        for (var k = 0; o.length > 0; )
            d = o[k],
            this.face[d].indexOf(b) > -1 ? (_ = (this.face[d].indexOf(b) + 1) % 3,
            b = this.face[d][_],
            s.push(b),
            c.push(d),
            o.splice(k, 1),
            k = 0) : k++;
        return this.adjacentFaces.push(s),
        c
    }
    ,
    e.prototype.toGoldbergData = function() {
        var i = this
          , o = new PolyhedronData("GeoDual","Goldberg",[],[]);
        o.name = "GD dual";
        for (var s = this.vertex.length, c = new Array(s), d = 0; d < s; d++)
            c[d] = [];
        for (var _ = 0; _ < this.face.length; _++)
            for (var b = 0; b < 3; b++)
                c[this.face[_][b]].push(_);
        var k = 0
          , j = 0
          , $ = 0
          , _e = []
          , et = [];
        this.adjacentFaces = [];
        for (var tt = 0; tt < c.length; tt++)
            o.face[tt] = this.setOrder(tt, c[tt].concat([])),
            c[tt].forEach(function(rt) {
                k = 0,
                j = 0,
                $ = 0,
                _e = i.face[rt];
                for (var it = 0; it < 3; it++)
                    et = i.vertex[_e[it]],
                    k += et[0],
                    j += et[1],
                    $ += et[2];
                o.vertex[rt] = [k / 3, j / 3, $ / 3]
            });
        return o
    }
    ,
    e.BuildGeodesicData = function(i) {
        var o = 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]],[]);
        i.setIndices(),
        i.calcCoeffs(),
        i.createInnerFacets(),
        i.edgeVecsABOB(),
        i.mapABOBtoOBOA(),
        i.mapABOBtoBAOA();
        for (var s = 0; s < i.IDATA.face.length; s++)
            i.MapToFace(s, o),
            o.innerToData(s, i),
            i.IDATA.edgematch[s][1] === "B" && o.mapABOBtoDATA(s, i),
            i.IDATA.edgematch[s][1] === "O" && o.mapOBOAtoDATA(s, i),
            i.IDATA.edgematch[s][3] === "A" && o.mapBAOAtoDATA(s, i);
        o.orderData(i);
        var c = 1;
        return o.vertex = o.vertex.map(function(d) {
            var _ = d[0]
              , b = d[1]
              , k = d[2]
              , j = Math.sqrt(_ * _ + b * b + k * k);
            return d[0] *= c / j,
            d[1] *= c / j,
            d[2] *= c / j,
            d
        }),
        o
    }
    ,
    e
}(PolyhedronData);
function CreateGeodesic(a, e, i) {
    i === void 0 && (i = null);
    var o = e.m || 1;
    o !== Math.floor(o) && Logger$2.Warn("m not an integer only floor(m) used");
    var s = e.n || 0;
    if (s !== Math.floor(s) && Logger$2.Warn("n not an integer only floor(n) used"),
    s > o) {
        var c = s;
        s = o,
        o = c,
        Logger$2.Warn("n > m therefore m and n swapped")
    }
    var d = new _PrimaryIsoTriangle;
    d.build(o, s);
    var _ = GeodesicData.BuildGeodesicData(d)
      , b = {
        custom: _,
        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
    }
      , k = CreatePolyhedron(a, b, i);
    return k
}
function CreateGoldbergVertexData(a, e) {
    for (var i = a.size, o = a.sizeX || i || 1, s = a.sizeY || i || 1, c = a.sizeZ || i || 1, d = a.sideOrientation === 0 ? 0 : a.sideOrientation || VertexData.DEFAULTSIDE, _ = new Array, b = new Array, k = new Array, j = new Array, $ = 1 / 0, _e = -1 / 0, et = 1 / 0, tt = -1 / 0, rt = 0; rt < e.vertex.length; rt++)
        $ = Math.min($, e.vertex[rt][0] * o),
        _e = Math.max(_e, e.vertex[rt][0] * o),
        et = Math.min(et, e.vertex[rt][1] * s),
        tt = Math.max(tt, e.vertex[rt][1] * s);
    for (var it = 0, nt = 0; nt < e.face.length; nt++) {
        for (var ot = e.face[nt], at = Vector3.FromArray(e.vertex[ot[0]]), st = Vector3.FromArray(e.vertex[ot[2]]), ut = Vector3.FromArray(e.vertex[ot[1]]), ct = st.subtract(at), lt = ut.subtract(at), ft = Vector3.Cross(lt, ct).normalize(), rt = 0; rt < ot.length; rt++) {
            k.push(ft.x, ft.y, ft.z);
            var ht = e.vertex[ot[rt]];
            _.push(ht[0] * o, ht[1] * s, ht[2] * c),
            j.push((ht[0] * o - $) / (_e - $), (ht[1] * s - et) / (tt - et))
        }
        for (var rt = 0; rt < ot.length - 2; rt++)
            b.push(it, it + rt + 2, it + rt + 1);
        it += ot.length
    }
    VertexData._ComputeSides(d, _, b, k, j);
    var pt = new VertexData;
    return pt.positions = _,
    pt.indices = b,
    pt.normals = k,
    pt.uvs = j,
    pt
}
function CreateGoldberg(a, e, i) {
    var o = e.m || 1;
    o !== Math.floor(o) && Logger$2.Warn("m not an integer only floor(m) used");
    var s = e.n || 0;
    if (s !== Math.floor(s) && Logger$2.Warn("n not an integer only floor(n) used"),
    s > o) {
        var c = s;
        s = o,
        o = c,
        Logger$2.Warn("n > m therefore m and n swapped")
    }
    var d = new _PrimaryIsoTriangle;
    d.build(o, s);
    var _ = GeodesicData.BuildGeodesicData(d)
      , b = _.toGoldbergData()
      , k = new GoldbergMesh(a);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    k._originalBuilderSideOrientation = e.sideOrientation;
    var j = CreateGoldbergVertexData(e, b);
    j.applyToMesh(k, e.updatable),
    k.nbSharedFaces = _.sharedNodes,
    k.nbUnsharedFaces = _.poleNodes,
    k.adjacentFaces = _.adjacentFaces,
    k.nbFaces = k.nbSharedFaces + k.nbUnsharedFaces,
    k.nbFacesAtPole = (k.nbUnsharedFaces - 12) / 12;
    for (var $ = 0; $ < _.vertex.length; $++)
        k.faceCenters.push(Vector3.FromArray(_.vertex[$])),
        k.faceColors.push(new Color4(1,1,1,1));
    for (var $ = 0; $ < b.face.length; $++) {
        var _e = b.face[$]
          , et = Vector3.FromArray(b.vertex[_e[0]])
          , tt = Vector3.FromArray(b.vertex[_e[2]])
          , rt = Vector3.FromArray(b.vertex[_e[1]])
          , it = tt.subtract(et)
          , nt = rt.subtract(et)
          , ot = Vector3.Cross(nt, it).normalize()
          , at = Vector3.Cross(nt, ot).normalize();
        k.faceXaxis.push(nt.normalize()),
        k.faceYaxis.push(ot),
        k.faceZaxis.push(at)
    }
    return k.setMetadata(),
    k
}
function GoldbergCreate(a) {
    return function(e) {
        __extends(i, e);
        function i() {
            var o = e !== null && e.apply(this, arguments) || this;
            return o.faceColors = [],
            o.faceCenters = [],
            o.faceZaxis = [],
            o.faceXaxis = [],
            o.faceYaxis = [],
            o
        }
        return i.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
            }
        }
        ,
        i.prototype.relFace = function(o, s) {
            return s === void 0 ? (o > this.nbUnsharedFaces - 1 && (Logger$2.Warn("Maximum number of unshared faces used"),
            o = this.nbUnsharedFaces - 1),
            this.nbUnsharedFaces + o) : (o > 11 && (Logger$2.Warn("Last pole used"),
            o = 11),
            s > this.nbFacesAtPole - 1 && (Logger$2.Warn("Maximum number of faces at a pole used"),
            s = this.nbFacesAtPole - 1),
            12 + o * this.nbFacesAtPole + s)
        }
        ,
        i.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
        }
        ,
        i.prototype.changeFaceColors = function(o) {
            for (var s = 0; s < o.length; s++)
                for (var c = o[s][0], d = o[s][1], _ = o[s][2], b = c; b < d + 1; b++)
                    this.faceColors[b] = _;
            for (var k = [], b = 0; b < 12; b++)
                for (var s = 0; s < 5; s++)
                    k.push(this.faceColors[b].r, this.faceColors[b].g, this.faceColors[b].b, this.faceColors[b].a);
            for (var b = 12; b < this.faceColors.length; b++)
                for (var s = 0; s < 6; s++)
                    k.push(this.faceColors[b].r, this.faceColors[b].g, this.faceColors[b].b, this.faceColors[b].a);
            return k
        }
        ,
        i.prototype.setFaceColors = function(o) {
            var s = this.changeFaceColors(o);
            this.setVerticesData(VertexBuffer.ColorKind, s)
        }
        ,
        i.prototype.updateFaceColors = function(o) {
            var s = this.changeFaceColors(o);
            this.updateVerticesData(VertexBuffer.ColorKind, s)
        }
        ,
        i.prototype.changeFaceUVs = function(o) {
            for (var s = this.getVerticesData(VertexBuffer.UVKind), c = 0; c < o.length; c++) {
                for (var d = o[c][0], _ = o[c][1], b = o[c][2], k = o[c][3], j = o[c][4], $ = [], _e = [], et = void 0, tt = void 0, rt = 0; rt < 5; rt++)
                    et = b.x + k * Math.cos(j + rt * Math.PI / 2.5),
                    tt = b.y + k * Math.sin(j + rt * Math.PI / 2.5),
                    et < 0 && (et = 0),
                    et > 1 && (et = 1),
                    $.push(et, tt);
                for (var rt = 0; rt < 6; rt++)
                    et = b.x + k * Math.cos(j + rt * Math.PI / 3),
                    tt = b.y + k * Math.sin(j + rt * Math.PI / 3),
                    et < 0 && (et = 0),
                    et > 1 && (et = 1),
                    _e.push(et, tt);
                for (var it = d; it < Math.min(12, _ + 1); it++)
                    for (var rt = 0; rt < 5; rt++)
                        s[10 * it + 2 * rt] = $[2 * rt],
                        s[10 * it + 2 * rt + 1] = $[2 * rt + 1];
                for (var it = Math.max(12, d); it < _ + 1; it++)
                    for (var rt = 0; rt < 6; rt++)
                        s[12 * it - 24 + 2 * rt] = _e[2 * rt],
                        s[12 * it - 23 + 2 * rt] = _e[2 * rt + 1]
            }
            return s
        }
        ,
        i.prototype.setFaceUVs = function(o) {
            var s = this.changeFaceUVs(o);
            this.setVerticesData(VertexBuffer.UVKind, s)
        }
        ,
        i.prototype.updateFaceUVs = function(o) {
            var s = this.changeFaceUVs(o);
            this.updateVerticesData(VertexBuffer.UVKind, s)
        }
        ,
        i.prototype.placeOnFaceAt = function(o, s, c) {
            var d = Vector3.RotationFromAxis(this.faceXaxis[s], this.faceYaxis[s], this.faceZaxis[s]);
            o.rotation = d,
            o.position = this.faceCenters[s].add(this.faceXaxis[s].scale(c.x)).add(this.faceYaxis[s].scale(c.y)).add(this.faceZaxis[s].scale(c.z))
        }
        ,
        i
    }(a)
}
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 a(e, i, o) {
        o === void 0 && (o = Number.MAX_VALUE),
        this.origin = e,
        this.direction = i,
        this.length = o
    }
    return a.prototype.clone = function() {
        return new a(this.origin.clone(),this.direction.clone(),this.length)
    }
    ,
    a.prototype.intersectsBoxMinMax = function(e, i, o) {
        o === void 0 && (o = 0);
        var s = a._TmpVector3[0].copyFromFloats(e.x - o, e.y - o, e.z - o), c = a._TmpVector3[1].copyFromFloats(i.x + o, i.y + o, i.z + o), d = 0, _ = Number.MAX_VALUE, b, k, j, $;
        if (Math.abs(this.direction.x) < 1e-7) {
            if (this.origin.x < s.x || this.origin.x > c.x)
                return !1
        } else if (b = 1 / this.direction.x,
        k = (s.x - this.origin.x) * b,
        j = (c.x - this.origin.x) * b,
        j === -1 / 0 && (j = 1 / 0),
        k > j && ($ = k,
        k = j,
        j = $),
        d = Math.max(k, d),
        _ = Math.min(j, _),
        d > _)
            return !1;
        if (Math.abs(this.direction.y) < 1e-7) {
            if (this.origin.y < s.y || this.origin.y > c.y)
                return !1
        } else if (b = 1 / this.direction.y,
        k = (s.y - this.origin.y) * b,
        j = (c.y - this.origin.y) * b,
        j === -1 / 0 && (j = 1 / 0),
        k > j && ($ = k,
        k = j,
        j = $),
        d = Math.max(k, d),
        _ = Math.min(j, _),
        d > _)
            return !1;
        if (Math.abs(this.direction.z) < 1e-7) {
            if (this.origin.z < s.z || this.origin.z > c.z)
                return !1
        } else if (b = 1 / this.direction.z,
        k = (s.z - this.origin.z) * b,
        j = (c.z - this.origin.z) * b,
        j === -1 / 0 && (j = 1 / 0),
        k > j && ($ = k,
        k = j,
        j = $),
        d = Math.max(k, d),
        _ = Math.min(j, _),
        d > _)
            return !1;
        return !0
    }
    ,
    a.prototype.intersectsBox = function(e, i) {
        return i === void 0 && (i = 0),
        this.intersectsBoxMinMax(e.minimum, e.maximum, i)
    }
    ,
    a.prototype.intersectsSphere = function(e, i) {
        i === void 0 && (i = 0);
        var o = e.center.x - this.origin.x
          , s = e.center.y - this.origin.y
          , c = e.center.z - this.origin.z
          , d = o * o + s * s + c * c
          , _ = e.radius + i
          , b = _ * _;
        if (d <= b)
            return !0;
        var k = o * this.direction.x + s * this.direction.y + c * this.direction.z;
        if (k < 0)
            return !1;
        var j = d - k * k;
        return j <= b
    }
    ,
    a.prototype.intersectsTriangle = function(e, i, o) {
        var s = a._TmpVector3[0]
          , c = a._TmpVector3[1]
          , d = a._TmpVector3[2]
          , _ = a._TmpVector3[3]
          , b = a._TmpVector3[4];
        i.subtractToRef(e, s),
        o.subtractToRef(e, c),
        Vector3.CrossToRef(this.direction, c, d);
        var k = Vector3.Dot(s, d);
        if (k === 0)
            return null;
        var j = 1 / k;
        this.origin.subtractToRef(e, _);
        var $ = Vector3.Dot(_, d) * j;
        if ($ < 0 || $ > 1)
            return null;
        Vector3.CrossToRef(_, s, b);
        var _e = Vector3.Dot(this.direction, b) * j;
        if (_e < 0 || $ + _e > 1)
            return null;
        var et = Vector3.Dot(c, b) * j;
        return et > this.length ? null : new IntersectionInfo(1 - $ - _e,$,et)
    }
    ,
    a.prototype.intersectsPlane = function(e) {
        var i, o = Vector3.Dot(e.normal, this.direction);
        if (Math.abs(o) < 999999997475243e-21)
            return null;
        var s = Vector3.Dot(e.normal, this.origin);
        return i = (-e.d - s) / o,
        i < 0 ? i < -999999997475243e-21 ? null : 0 : i
    }
    ,
    a.prototype.intersectsAxis = function(e, i) {
        switch (i === void 0 && (i = 0),
        e) {
        case "y":
            var o = (this.origin.y - i) / this.direction.y;
            return o > 0 ? null : new Vector3(this.origin.x + this.direction.x * -o,i,this.origin.z + this.direction.z * -o);
        case "x":
            var o = (this.origin.x - i) / this.direction.x;
            return o > 0 ? null : new Vector3(i,this.origin.y + this.direction.y * -o,this.origin.z + this.direction.z * -o);
        case "z":
            var o = (this.origin.z - i) / this.direction.z;
            return o > 0 ? null : new Vector3(this.origin.x + this.direction.x * -o,this.origin.y + this.direction.y * -o,i);
        default:
            return null
        }
    }
    ,
    a.prototype.intersectsMesh = function(e, i) {
        var o = TmpVectors.Matrix[0];
        return e.getWorldMatrix().invertToRef(o),
        this._tmpRay ? a.TransformToRef(this, o, this._tmpRay) : this._tmpRay = a.Transform(this, o),
        e.intersects(this._tmpRay, i)
    }
    ,
    a.prototype.intersectsMeshes = function(e, i, o) {
        o ? o.length = 0 : o = [];
        for (var s = 0; s < e.length; s++) {
            var c = this.intersectsMesh(e[s], i);
            c.hit && o.push(c)
        }
        return o.sort(this._comparePickingInfo),
        o
    }
    ,
    a.prototype._comparePickingInfo = function(e, i) {
        return e.distance < i.distance ? -1 : e.distance > i.distance ? 1 : 0
    }
    ,
    a.prototype.intersectionSegment = function(e, i, o) {
        var s = this.origin
          , c = TmpVectors.Vector3[0]
          , d = TmpVectors.Vector3[1]
          , _ = TmpVectors.Vector3[2]
          , b = TmpVectors.Vector3[3];
        i.subtractToRef(e, c),
        this.direction.scaleToRef(a.rayl, _),
        s.addToRef(_, d),
        e.subtractToRef(s, b);
        var k = Vector3.Dot(c, c), j = Vector3.Dot(c, _), $ = Vector3.Dot(_, _), _e = Vector3.Dot(c, b), et = Vector3.Dot(_, b), tt = k * $ - j * j, rt, it, nt = tt, ot, at, st = tt;
        tt < a.smallnum ? (it = 0,
        nt = 1,
        at = et,
        st = $) : (it = j * et - $ * _e,
        at = k * et - j * _e,
        it < 0 ? (it = 0,
        at = et,
        st = $) : it > nt && (it = nt,
        at = et + j,
        st = $)),
        at < 0 ? (at = 0,
        -_e < 0 ? it = 0 : -_e > k ? it = nt : (it = -_e,
        nt = k)) : at > st && (at = st,
        -_e + j < 0 ? it = 0 : -_e + j > k ? it = nt : (it = -_e + j,
        nt = k)),
        rt = Math.abs(it) < a.smallnum ? 0 : it / nt,
        ot = Math.abs(at) < a.smallnum ? 0 : at / st;
        var ut = TmpVectors.Vector3[4];
        _.scaleToRef(ot, ut);
        var ct = TmpVectors.Vector3[5];
        c.scaleToRef(rt, ct),
        ct.addInPlace(b);
        var lt = TmpVectors.Vector3[6];
        ct.subtractToRef(ut, lt);
        var ft = ot > 0 && ot <= this.length && lt.lengthSquared() < o * o;
        return ft ? ct.length() : -1
    }
    ,
    a.prototype.update = function(e, i, o, s, c, d, _) {
        return this.unprojectRayToRef(e, i, o, s, c, d, _),
        this
    }
    ,
    a.Zero = function() {
        return new a(Vector3.Zero(),Vector3.Zero())
    }
    ,
    a.CreateNew = function(e, i, o, s, c, d, _) {
        var b = a.Zero();
        return b.update(e, i, o, s, c, d, _)
    }
    ,
    a.CreateNewFromTo = function(e, i, o) {
        o === void 0 && (o = Matrix.IdentityReadOnly);
        var s = i.subtract(e)
          , c = Math.sqrt(s.x * s.x + s.y * s.y + s.z * s.z);
        return s.normalize(),
        a.Transform(new a(e,s,c), o)
    }
    ,
    a.Transform = function(e, i) {
        var o = new a(new Vector3(0,0,0),new Vector3(0,0,0));
        return a.TransformToRef(e, i, o),
        o
    }
    ,
    a.TransformToRef = function(e, i, o) {
        Vector3.TransformCoordinatesToRef(e.origin, i, o.origin),
        Vector3.TransformNormalToRef(e.direction, i, o.direction),
        o.length = e.length;
        var s = o.direction
          , c = s.length();
        if (!(c === 0 || c === 1)) {
            var d = 1 / c;
            s.x *= d,
            s.y *= d,
            s.z *= d,
            o.length *= c
        }
    }
    ,
    a.prototype.unprojectRayToRef = function(e, i, o, s, c, d, _) {
        var b = TmpVectors.Matrix[0];
        c.multiplyToRef(d, b),
        b.multiplyToRef(_, b),
        b.invert();
        var k = TmpVectors.Vector3[0];
        k.x = e / o * 2 - 1,
        k.y = -(i / s * 2 - 1),
        k.z = -1;
        var j = TmpVectors.Vector3[1].copyFromFloats(k.x, k.y, 1)
          , $ = TmpVectors.Vector3[2]
          , _e = TmpVectors.Vector3[3];
        Vector3._UnprojectFromInvertedMatrixToRef(k, b, $),
        Vector3._UnprojectFromInvertedMatrixToRef(j, b, _e),
        this.origin.copyFrom($),
        _e.subtractToRef($, this.direction),
        this.direction.normalize()
    }
    ,
    a._TmpVector3 = ArrayTools.BuildArray(6, Vector3.Zero),
    a.smallnum = 1e-8,
    a.rayl = 1e9,
    a
}();
Scene.prototype.createPickingRay = function(a, e, i, o, s) {
    s === void 0 && (s = !1);
    var c = Ray.Zero();
    return this.createPickingRayToRef(a, e, i, c, o, s),
    c
}
;
Scene.prototype.createPickingRayToRef = function(a, e, i, o, s, c) {
    c === void 0 && (c = !1);
    var d = this.getEngine();
    if (!s) {
        if (!this.activeCamera)
            return this;
        s = this.activeCamera
    }
    var _ = s.viewport
      , b = _.toGlobal(d.getRenderWidth(), d.getRenderHeight());
    return a = a / d.getHardwareScalingLevel() - b.x,
    e = e / d.getHardwareScalingLevel() - (d.getRenderHeight() - b.y - b.height),
    o.update(a, e, b.width, b.height, i || Matrix.IdentityReadOnly, c ? Matrix.IdentityReadOnly : s.getViewMatrix(), s.getProjectionMatrix()),
    this
}
;
Scene.prototype.createPickingRayInCameraSpace = function(a, e, i) {
    var o = Ray.Zero();
    return this.createPickingRayInCameraSpaceToRef(a, e, o, i),
    o
}
;
Scene.prototype.createPickingRayInCameraSpaceToRef = function(a, e, i, o) {
    if (!PickingInfo)
        return this;
    var s = this.getEngine();
    if (!o) {
        if (!this.activeCamera)
            throw new Error("Active camera not set");
        o = this.activeCamera
    }
    var c = o.viewport
      , d = c.toGlobal(s.getRenderWidth(), s.getRenderHeight())
      , _ = Matrix.Identity();
    return a = a / s.getHardwareScalingLevel() - d.x,
    e = e / s.getHardwareScalingLevel() - (s.getRenderHeight() - d.y - d.height),
    i.update(a, e, d.width, d.height, _, _, o.getProjectionMatrix()),
    this
}
;
Scene.prototype._internalPickForMesh = function(a, e, i, o, s, c, d, _) {
    var b = e(o)
      , k = i.intersects(b, s, d, c, o, _);
    return !k || !k.hit || !s && a != null && k.distance >= a.distance ? null : k
}
;
Scene.prototype._internalPick = function(a, e, i, o, s) {
    if (!PickingInfo)
        return null;
    for (var c = null, d = 0; d < this.meshes.length; d++) {
        var _ = this.meshes[d];
        if (e) {
            if (!e(_))
                continue
        } else if (!_.isEnabled() || !_.isVisible || !_.isPickable)
            continue;
        var b = _.skeleton && _.skeleton.overrideMesh ? _.skeleton.overrideMesh.getWorldMatrix() : _.getWorldMatrix();
        if (_.hasThinInstances && _.thinInstanceEnablePicking) {
            var k = this._internalPickForMesh(c, a, _, b, !0, !0, s);
            if (k) {
                if (o)
                    return c;
                for (var j = TmpVectors.Matrix[1], $ = _.thinInstanceGetWorldMatrices(), _e = 0; _e < $.length; _e++) {
                    var et = $[_e];
                    et.multiplyToRef(b, j);
                    var tt = this._internalPickForMesh(c, a, _, j, i, o, s, !0);
                    if (tt && (c = tt,
                    c.thinInstanceIndex = _e,
                    i))
                        return c
                }
            }
        } else {
            var k = this._internalPickForMesh(c, a, _, b, i, o, s);
            if (k && (c = k,
            i))
                return c
        }
    }
    return c || new PickingInfo
}
;
Scene.prototype._internalMultiPick = function(a, e, i) {
    if (!PickingInfo)
        return null;
    for (var o = new Array, s = 0; s < this.meshes.length; s++) {
        var c = this.meshes[s];
        if (e) {
            if (!e(c))
                continue
        } else if (!c.isEnabled() || !c.isVisible || !c.isPickable)
            continue;
        var d = c.skeleton && c.skeleton.overrideMesh ? c.skeleton.overrideMesh.getWorldMatrix() : c.getWorldMatrix();
        if (c.hasThinInstances && c.thinInstanceEnablePicking) {
            var _ = this._internalPickForMesh(null, a, c, d, !0, !0, i);
            if (_)
                for (var b = TmpVectors.Matrix[1], k = c.thinInstanceGetWorldMatrices(), j = 0; j < k.length; j++) {
                    var $ = k[j];
                    $.multiplyToRef(d, b);
                    var _e = this._internalPickForMesh(null, a, c, b, !1, !1, i, !0);
                    _e && (_e.thinInstanceIndex = j,
                    o.push(_e))
                }
        } else {
            var _ = this._internalPickForMesh(null, a, c, d, !1, !1, i);
            _ && o.push(_)
        }
    }
    return o
}
;
Scene.prototype.pickWithBoundingInfo = function(a, e, i, o, s) {
    var c = this;
    if (!PickingInfo)
        return null;
    var d = this._internalPick(function(_) {
        return c._tempPickingRay || (c._tempPickingRay = Ray.Zero()),
        c.createPickingRayToRef(a, e, _, c._tempPickingRay, s || null),
        c._tempPickingRay
    }, i, o, !0);
    return d && (d.ray = this.createPickingRay(a, e, Matrix.Identity(), s || null)),
    d
}
;
Scene.prototype.pick = function(a, e, i, o, s, c) {
    var d = this;
    if (!PickingInfo)
        return null;
    var _ = this._internalPick(function(b) {
        return d._tempPickingRay || (d._tempPickingRay = Ray.Zero()),
        d.createPickingRayToRef(a, e, b, d._tempPickingRay, s || null),
        d._tempPickingRay
    }, i, o, !1, c);
    return _ && (_.ray = this.createPickingRay(a, e, Matrix.Identity(), s || null)),
    _
}
;
Scene.prototype.pickWithRay = function(a, e, i, o) {
    var s = this
      , c = this._internalPick(function(d) {
        return s._pickWithRayInverseMatrix || (s._pickWithRayInverseMatrix = Matrix.Identity()),
        d.invertToRef(s._pickWithRayInverseMatrix),
        s._cachedRayForTransform || (s._cachedRayForTransform = Ray.Zero()),
        Ray.TransformToRef(a, s._pickWithRayInverseMatrix, s._cachedRayForTransform),
        s._cachedRayForTransform
    }, e, i, !1, o);
    return c && (c.ray = a),
    c
}
;
Scene.prototype.multiPick = function(a, e, i, o, s) {
    var c = this;
    return this._internalMultiPick(function(d) {
        return c.createPickingRay(a, e, d, o || null)
    }, i, s)
}
;
Scene.prototype.multiPickWithRay = function(a, e, i) {
    var o = this;
    return this._internalMultiPick(function(s) {
        return o._pickWithRayInverseMatrix || (o._pickWithRayInverseMatrix = Matrix.Identity()),
        s.invertToRef(o._pickWithRayInverseMatrix),
        o._cachedRayForTransform || (o._cachedRayForTransform = Ray.Zero()),
        Ray.TransformToRef(a, o._pickWithRayInverseMatrix, o._cachedRayForTransform),
        o._cachedRayForTransform
    }, e, i)
}
;
Camera$1.prototype.getForwardRay = function(a, e, i) {
    return a === void 0 && (a = 100),
    this.getForwardRayToRef(new Ray(Vector3.Zero(),Vector3.Zero(),a), a, e, i)
}
;
Camera$1.prototype.getForwardRayToRef = function(a, e, i, o) {
    return e === void 0 && (e = 100),
    i || (i = this.getWorldMatrix()),
    a.length = e,
    o ? a.origin.copyFrom(o) : a.origin.copyFrom(this.position),
    TmpVectors.Vector3[2].set(0, 0, this._scene.useRightHandedSystem ? -1 : 1),
    Vector3.TransformNormalToRef(TmpVectors.Vector3[2], i, TmpVectors.Vector3[3]),
    Vector3.NormalizeToRef(TmpVectors.Vector3[3], a.direction),
    a
}
;
var ColorGradient = function() {
    function a(e, i, o) {
        this.gradient = e,
        this.color1 = i,
        this.color2 = o
    }
    return a.prototype.getColorToRef = function(e) {
        if (!this.color2) {
            e.copyFrom(this.color1);
            return
        }
        Color4.LerpToRef(this.color1, this.color2, Math.random(), e)
    }
    ,
    a
}(), Color3Gradient = function() {
    function a(e, i) {
        this.gradient = e,
        this.color = i
    }
    return a
}(), FactorGradient = function() {
    function a(e, i, o) {
        this.gradient = e,
        this.factor1 = i,
        this.factor2 = o
    }
    return a.prototype.getFactor = function() {
        return this.factor2 === void 0 || this.factor2 === this.factor1 ? this.factor1 : this.factor1 + (this.factor2 - this.factor1) * Math.random()
    }
    ,
    a
}(), GradientHelper = function() {
    function a() {}
    return a.GetCurrentGradient = function(e, i, o) {
        if (i[0].gradient > e) {
            o(i[0], i[0], 1);
            return
        }
        for (var s = 0; s < i.length - 1; s++) {
            var c = i[s]
              , d = i[s + 1];
            if (e >= c.gradient && e <= d.gradient) {
                var _ = (e - c.gradient) / (d.gradient - c.gradient);
                o(c, d, _);
                return
            }
        }
        var b = i.length - 1;
        o(i[b], i[b], 1)
    }
    ,
    a
}(), BoxParticleEmitter = function() {
    function a() {
        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 a.prototype.startDirectionFunction = function(e, i, o, s) {
        var c = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , d = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , _ = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        if (s) {
            i.x = c,
            i.y = d,
            i.z = _;
            return
        }
        Vector3.TransformNormalFromFloatsToRef(c, d, _, e, i)
    }
    ,
    a.prototype.startPositionFunction = function(e, i, o, s) {
        var c = Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x)
          , d = Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y)
          , _ = Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
        if (s) {
            i.x = c,
            i.y = d,
            i.z = _;
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(c, d, _, e, i)
    }
    ,
    a.prototype.clone = function() {
        var e = new a;
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    a.prototype.applyToShader = function(e) {
        e.setVector3("direction1", this.direction1),
        e.setVector3("direction2", this.direction2),
        e.setVector3("minEmitBox", this.minEmitBox),
        e.setVector3("maxEmitBox", this.maxEmitBox)
    }
    ,
    a.prototype.buildUniformLayout = function(e) {
        e.addUniform("direction1", 3),
        e.addUniform("direction2", 3),
        e.addUniform("minEmitBox", 3),
        e.addUniform("maxEmitBox", 3)
    }
    ,
    a.prototype.getEffectDefines = function() {
        return "#define BOXEMITTER"
    }
    ,
    a.prototype.getClassName = function() {
        return "BoxParticleEmitter"
    }
    ,
    a.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
    }
    ,
    a.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)
    }
    ,
    a
}(), ConeParticleEmitter = function() {
    function a(e, i, o) {
        e === void 0 && (e = 1),
        i === void 0 && (i = Math.PI),
        o === void 0 && (o = 0),
        this.directionRandomizer = o,
        this.radiusRange = 1,
        this.heightRange = 1,
        this.emitFromSpawnPointOnly = !1,
        this.angle = i,
        this.radius = e
    }
    return Object.defineProperty(a.prototype, "radius", {
        get: function() {
            return this._radius
        },
        set: function(e) {
            this._radius = e,
            this._buildHeight()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "angle", {
        get: function() {
            return this._angle
        },
        set: function(e) {
            this._angle = e,
            this._buildHeight()
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._buildHeight = function() {
        this._angle !== 0 ? this._height = this._radius / Math.tan(this._angle / 2) : this._height = 1
    }
    ,
    a.prototype.startDirectionFunction = function(e, i, o, s) {
        s ? TmpVectors.Vector3[0].copyFrom(o._localPosition).normalize() : o.position.subtractToRef(e.getTranslation(), TmpVectors.Vector3[0]).normalize();
        var c = Scalar.RandomRange(0, this.directionRandomizer)
          , d = Scalar.RandomRange(0, this.directionRandomizer)
          , _ = Scalar.RandomRange(0, this.directionRandomizer);
        i.x = TmpVectors.Vector3[0].x + c,
        i.y = TmpVectors.Vector3[0].y + d,
        i.z = TmpVectors.Vector3[0].z + _,
        i.normalize()
    }
    ,
    a.prototype.startPositionFunction = function(e, i, o, s) {
        var c = Scalar.RandomRange(0, Math.PI * 2), d;
        this.emitFromSpawnPointOnly ? d = 1e-4 : (d = Scalar.RandomRange(0, this.heightRange),
        d = 1 - d * d);
        var _ = this._radius - Scalar.RandomRange(0, this._radius * this.radiusRange);
        _ = _ * d;
        var b = _ * Math.sin(c)
          , k = _ * Math.cos(c)
          , j = d * this._height;
        if (s) {
            i.x = b,
            i.y = j,
            i.z = k;
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(b, j, k, e, i)
    }
    ,
    a.prototype.clone = function() {
        var e = new a(this._radius,this._angle,this.directionRandomizer);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    a.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)
    }
    ,
    a.prototype.buildUniformLayout = function(e) {
        e.addUniform("radius", 2),
        e.addUniform("coneAngle", 1),
        e.addUniform("height", 2),
        e.addUniform("directionRandomizer", 1)
    }
    ,
    a.prototype.getEffectDefines = function() {
        var e = "#define CONEEMITTER";
        return this.emitFromSpawnPointOnly && (e += `
#define CONEEMITTERSPAWNPOINT`),
        e
    }
    ,
    a.prototype.getClassName = function() {
        return "ConeParticleEmitter"
    }
    ,
    a.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
    }
    ,
    a.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
    }
    ,
    a
}(), CylinderParticleEmitter = function() {
    function a(e, i, o, s) {
        e === void 0 && (e = 1),
        i === void 0 && (i = 1),
        o === void 0 && (o = 1),
        s === void 0 && (s = 0),
        this.radius = e,
        this.height = i,
        this.radiusRange = o,
        this.directionRandomizer = s,
        this._tempVector = Vector3.Zero()
    }
    return a.prototype.startDirectionFunction = function(e, i, o, s, c) {
        o.position.subtractToRef(e.getTranslation(), this._tempVector),
        this._tempVector.normalize(),
        Vector3.TransformNormalToRef(this._tempVector, c, this._tempVector);
        var d = Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2)
          , _ = Math.atan2(this._tempVector.x, this._tempVector.z);
        if (_ += Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer,
        this._tempVector.y = d,
        this._tempVector.x = Math.sin(_),
        this._tempVector.z = Math.cos(_),
        this._tempVector.normalize(),
        s) {
            i.copyFrom(this._tempVector);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(this._tempVector.x, this._tempVector.y, this._tempVector.z, e, i)
    }
    ,
    a.prototype.startPositionFunction = function(e, i, o, s) {
        var c = Scalar.RandomRange(-this.height / 2, this.height / 2)
          , d = Scalar.RandomRange(0, 2 * Math.PI)
          , _ = Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1)
          , b = Math.sqrt(_) * this.radius
          , k = b * Math.cos(d)
          , j = b * Math.sin(d);
        if (s) {
            i.copyFromFloats(k, c, j);
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(k, c, j, e, i)
    }
    ,
    a.prototype.clone = function() {
        var e = new a(this.radius,this.directionRandomizer);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    a.prototype.applyToShader = function(e) {
        e.setFloat("radius", this.radius),
        e.setFloat("height", this.height),
        e.setFloat("radiusRange", this.radiusRange),
        e.setFloat("directionRandomizer", this.directionRandomizer)
    }
    ,
    a.prototype.buildUniformLayout = function(e) {
        e.addUniform("radius", 1),
        e.addUniform("height", 1),
        e.addUniform("radiusRange", 1),
        e.addUniform("directionRandomizer", 1)
    }
    ,
    a.prototype.getEffectDefines = function() {
        return "#define CYLINDEREMITTER"
    }
    ,
    a.prototype.getClassName = function() {
        return "CylinderParticleEmitter"
    }
    ,
    a.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
    }
    ,
    a.prototype.parse = function(e) {
        this.radius = e.radius,
        this.height = e.height,
        this.radiusRange = e.radiusRange,
        this.directionRandomizer = e.directionRandomizer
    }
    ,
    a
}(), CylinderDirectedParticleEmitter = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        i === void 0 && (i = 1),
        o === void 0 && (o = 1),
        s === void 0 && (s = 1),
        c === void 0 && (c = new Vector3(0,1,0)),
        d === void 0 && (d = new Vector3(0,1,0));
        var _ = a.call(this, i, o, s) || this;
        return _.direction1 = c,
        _.direction2 = d,
        _
    }
    return e.prototype.startDirectionFunction = function(i, o, s) {
        var c = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , d = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , _ = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        Vector3.TransformNormalFromFloatsToRef(c, d, _, i, o)
    }
    ,
    e.prototype.clone = function() {
        var i = new e(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);
        return DeepCopier.DeepCopy(this, i),
        i
    }
    ,
    e.prototype.applyToShader = function(i) {
        i.setFloat("radius", this.radius),
        i.setFloat("height", this.height),
        i.setFloat("radiusRange", this.radiusRange),
        i.setVector3("direction1", this.direction1),
        i.setVector3("direction2", this.direction2)
    }
    ,
    e.prototype.buildUniformLayout = function(i) {
        i.addUniform("radius", 1),
        i.addUniform("height", 1),
        i.addUniform("radiusRange", 1),
        i.addUniform("direction1", 3),
        i.addUniform("direction2", 3)
    }
    ,
    e.prototype.getEffectDefines = function() {
        return `#define CYLINDEREMITTER
#define DIRECTEDCYLINDEREMITTER`
    }
    ,
    e.prototype.getClassName = function() {
        return "CylinderDirectedParticleEmitter"
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.direction1 = this.direction1.asArray(),
        i.direction2 = this.direction2.asArray(),
        i
    }
    ,
    e.prototype.parse = function(i) {
        a.prototype.parse.call(this, i),
        this.direction1.copyFrom(i.direction1),
        this.direction2.copyFrom(i.direction2)
    }
    ,
    e
}(CylinderParticleEmitter), HemisphericParticleEmitter = function() {
    function a(e, i, o) {
        e === void 0 && (e = 1),
        i === void 0 && (i = 1),
        o === void 0 && (o = 0),
        this.radius = e,
        this.radiusRange = i,
        this.directionRandomizer = o
    }
    return a.prototype.startDirectionFunction = function(e, i, o, s) {
        var c = o.position.subtract(e.getTranslation()).normalize()
          , d = Scalar.RandomRange(0, this.directionRandomizer)
          , _ = Scalar.RandomRange(0, this.directionRandomizer)
          , b = Scalar.RandomRange(0, this.directionRandomizer);
        if (c.x += d,
        c.y += _,
        c.z += b,
        c.normalize(),
        s) {
            i.copyFrom(c);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(c.x, c.y, c.z, e, i)
    }
    ,
    a.prototype.startPositionFunction = function(e, i, o, s) {
        var c = this.radius - Scalar.RandomRange(0, this.radius * this.radiusRange)
          , d = Scalar.RandomRange(0, 1)
          , _ = Scalar.RandomRange(0, 2 * Math.PI)
          , b = Math.acos(2 * d - 1)
          , k = c * Math.cos(_) * Math.sin(b)
          , j = c * Math.cos(b)
          , $ = c * Math.sin(_) * Math.sin(b);
        if (s) {
            i.copyFromFloats(k, Math.abs(j), $);
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(k, Math.abs(j), $, e, i)
    }
    ,
    a.prototype.clone = function() {
        var e = new a(this.radius,this.directionRandomizer);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    a.prototype.applyToShader = function(e) {
        e.setFloat("radius", this.radius),
        e.setFloat("radiusRange", this.radiusRange),
        e.setFloat("directionRandomizer", this.directionRandomizer)
    }
    ,
    a.prototype.buildUniformLayout = function(e) {
        e.addUniform("radius", 1),
        e.addUniform("radiusRange", 1),
        e.addUniform("directionRandomizer", 1)
    }
    ,
    a.prototype.getEffectDefines = function() {
        return "#define HEMISPHERICEMITTER"
    }
    ,
    a.prototype.getClassName = function() {
        return "HemisphericParticleEmitter"
    }
    ,
    a.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.radius = this.radius,
        e.radiusRange = this.radiusRange,
        e.directionRandomizer = this.directionRandomizer,
        e
    }
    ,
    a.prototype.parse = function(e) {
        this.radius = e.radius,
        this.radiusRange = e.radiusRange,
        this.directionRandomizer = e.directionRandomizer
    }
    ,
    a
}(), PointParticleEmitter = function() {
    function a() {
        this.direction1 = new Vector3(0,1,0),
        this.direction2 = new Vector3(0,1,0)
    }
    return a.prototype.startDirectionFunction = function(e, i, o, s) {
        var c = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , d = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , _ = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        if (s) {
            i.copyFromFloats(c, d, _);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(c, d, _, e, i)
    }
    ,
    a.prototype.startPositionFunction = function(e, i, o, s) {
        if (s) {
            i.copyFromFloats(0, 0, 0);
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, e, i)
    }
    ,
    a.prototype.clone = function() {
        var e = new a;
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    a.prototype.applyToShader = function(e) {
        e.setVector3("direction1", this.direction1),
        e.setVector3("direction2", this.direction2)
    }
    ,
    a.prototype.buildUniformLayout = function(e) {
        e.addUniform("direction1", 3),
        e.addUniform("direction2", 3)
    }
    ,
    a.prototype.getEffectDefines = function() {
        return "#define POINTEMITTER"
    }
    ,
    a.prototype.getClassName = function() {
        return "PointParticleEmitter"
    }
    ,
    a.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.direction1 = this.direction1.asArray(),
        e.direction2 = this.direction2.asArray(),
        e
    }
    ,
    a.prototype.parse = function(e) {
        Vector3.FromArrayToRef(e.direction1, 0, this.direction1),
        Vector3.FromArrayToRef(e.direction2, 0, this.direction2)
    }
    ,
    a
}(), SphereParticleEmitter = function() {
    function a(e, i, o) {
        e === void 0 && (e = 1),
        i === void 0 && (i = 1),
        o === void 0 && (o = 0),
        this.radius = e,
        this.radiusRange = i,
        this.directionRandomizer = o
    }
    return a.prototype.startDirectionFunction = function(e, i, o, s) {
        var c = o.position.subtract(e.getTranslation()).normalize()
          , d = Scalar.RandomRange(0, this.directionRandomizer)
          , _ = Scalar.RandomRange(0, this.directionRandomizer)
          , b = Scalar.RandomRange(0, this.directionRandomizer);
        if (c.x += d,
        c.y += _,
        c.z += b,
        c.normalize(),
        s) {
            i.copyFrom(c);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(c.x, c.y, c.z, e, i)
    }
    ,
    a.prototype.startPositionFunction = function(e, i, o, s) {
        var c = this.radius - Scalar.RandomRange(0, this.radius * this.radiusRange)
          , d = Scalar.RandomRange(0, 1)
          , _ = Scalar.RandomRange(0, 2 * Math.PI)
          , b = Math.acos(2 * d - 1)
          , k = c * Math.cos(_) * Math.sin(b)
          , j = c * Math.cos(b)
          , $ = c * Math.sin(_) * Math.sin(b);
        if (s) {
            i.copyFromFloats(k, j, $);
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(k, j, $, e, i)
    }
    ,
    a.prototype.clone = function() {
        var e = new a(this.radius,this.directionRandomizer);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    a.prototype.applyToShader = function(e) {
        e.setFloat("radius", this.radius),
        e.setFloat("radiusRange", this.radiusRange),
        e.setFloat("directionRandomizer", this.directionRandomizer)
    }
    ,
    a.prototype.buildUniformLayout = function(e) {
        e.addUniform("radius", 1),
        e.addUniform("radiusRange", 1),
        e.addUniform("directionRandomizer", 1)
    }
    ,
    a.prototype.getEffectDefines = function() {
        return "#define SPHEREEMITTER"
    }
    ,
    a.prototype.getClassName = function() {
        return "SphereParticleEmitter"
    }
    ,
    a.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.radius = this.radius,
        e.radiusRange = this.radiusRange,
        e.directionRandomizer = this.directionRandomizer,
        e
    }
    ,
    a.prototype.parse = function(e) {
        this.radius = e.radius,
        this.radiusRange = e.radiusRange,
        this.directionRandomizer = e.directionRandomizer
    }
    ,
    a
}(), SphereDirectedParticleEmitter = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        i === void 0 && (i = 1),
        o === void 0 && (o = new Vector3(0,1,0)),
        s === void 0 && (s = new Vector3(0,1,0));
        var c = a.call(this, i) || this;
        return c.direction1 = o,
        c.direction2 = s,
        c
    }
    return e.prototype.startDirectionFunction = function(i, o, s) {
        var c = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , d = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , _ = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        Vector3.TransformNormalFromFloatsToRef(c, d, _, i, o)
    }
    ,
    e.prototype.clone = function() {
        var i = new e(this.radius,this.direction1,this.direction2);
        return DeepCopier.DeepCopy(this, i),
        i
    }
    ,
    e.prototype.applyToShader = function(i) {
        i.setFloat("radius", this.radius),
        i.setFloat("radiusRange", this.radiusRange),
        i.setVector3("direction1", this.direction1),
        i.setVector3("direction2", this.direction2)
    }
    ,
    e.prototype.buildUniformLayout = function(i) {
        i.addUniform("radius", 1),
        i.addUniform("radiusRange", 1),
        i.addUniform("direction1", 3),
        i.addUniform("direction2", 3)
    }
    ,
    e.prototype.getEffectDefines = function() {
        return `#define SPHEREEMITTER
#define DIRECTEDSPHEREEMITTER`
    }
    ,
    e.prototype.getClassName = function() {
        return "SphereDirectedParticleEmitter"
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.direction1 = this.direction1.asArray(),
        i.direction2 = this.direction2.asArray(),
        i
    }
    ,
    e.prototype.parse = function(i) {
        a.prototype.parse.call(this, i),
        this.direction1.copyFrom(i.direction1),
        this.direction2.copyFrom(i.direction2)
    }
    ,
    e
}(SphereParticleEmitter), CustomParticleEmitter = function() {
    function a() {
        this.particlePositionGenerator = function() {}
        ,
        this.particleDestinationGenerator = function() {}
    }
    return a.prototype.startDirectionFunction = function(e, i, o, s) {
        var c = TmpVectors.Vector3[0];
        if (this.particleDestinationGenerator) {
            this.particleDestinationGenerator(-1, o, c);
            var d = TmpVectors.Vector3[1];
            c.subtractToRef(o.position, d),
            d.scaleToRef(1 / o.lifeTime, c)
        } else
            c.set(0, 0, 0);
        if (s) {
            i.copyFrom(c);
            return
        }
        Vector3.TransformNormalToRef(c, e, i)
    }
    ,
    a.prototype.startPositionFunction = function(e, i, o, s) {
        var c = TmpVectors.Vector3[0];
        if (this.particlePositionGenerator ? this.particlePositionGenerator(-1, o, c) : c.set(0, 0, 0),
        s) {
            i.copyFrom(c);
            return
        }
        Vector3.TransformCoordinatesToRef(c, e, i)
    }
    ,
    a.prototype.clone = function() {
        var e = new a;
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    a.prototype.applyToShader = function(e) {}
    ,
    a.prototype.buildUniformLayout = function(e) {}
    ,
    a.prototype.getEffectDefines = function() {
        return "#define CUSTOMEMITTER"
    }
    ,
    a.prototype.getClassName = function() {
        return "CustomParticleEmitter"
    }
    ,
    a.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e
    }
    ,
    a.prototype.parse = function(e) {}
    ,
    a
}(), MeshParticleEmitter = function() {
    function a(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(a.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
    }),
    a.prototype.startDirectionFunction = function(e, i, o, s) {
        if (this.useMeshNormalsForDirection && this._normals) {
            Vector3.TransformNormalToRef(this._storedNormal, e, i);
            return
        }
        var c = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , d = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , _ = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        if (s) {
            i.copyFromFloats(c, d, _);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(c, d, _, e, i)
    }
    ,
    a.prototype.startPositionFunction = function(e, i, o, s) {
        if (!(!this._indices || !this._positions)) {
            var c = 3 * Math.random() * (this._indices.length / 3) | 0
              , d = Math.random()
              , _ = Math.random() * (1 - d)
              , b = 1 - d - _
              , k = this._indices[c]
              , j = this._indices[c + 1]
              , $ = this._indices[c + 2]
              , _e = TmpVectors.Vector3[0]
              , et = TmpVectors.Vector3[1]
              , tt = TmpVectors.Vector3[2]
              , rt = TmpVectors.Vector3[3];
            Vector3.FromArrayToRef(this._positions, k * 3, _e),
            Vector3.FromArrayToRef(this._positions, j * 3, et),
            Vector3.FromArrayToRef(this._positions, $ * 3, tt),
            rt.x = d * _e.x + _ * et.x + b * tt.x,
            rt.y = d * _e.y + _ * et.y + b * tt.y,
            rt.z = d * _e.z + _ * et.z + b * tt.z,
            s ? i.copyFromFloats(rt.x, rt.y, rt.z) : Vector3.TransformCoordinatesFromFloatsToRef(rt.x, rt.y, rt.z, e, i),
            this.useMeshNormalsForDirection && this._normals && (Vector3.FromArrayToRef(this._normals, k * 3, _e),
            Vector3.FromArrayToRef(this._normals, j * 3, et),
            Vector3.FromArrayToRef(this._normals, $ * 3, tt),
            this._storedNormal.x = d * _e.x + _ * et.x + b * tt.x,
            this._storedNormal.y = d * _e.y + _ * et.y + b * tt.y,
            this._storedNormal.z = d * _e.z + _ * et.z + b * tt.z)
        }
    }
    ,
    a.prototype.clone = function() {
        var e = new a(this.mesh);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    a.prototype.applyToShader = function(e) {
        e.setVector3("direction1", this.direction1),
        e.setVector3("direction2", this.direction2)
    }
    ,
    a.prototype.buildUniformLayout = function(e) {
        e.addUniform("direction1", 3),
        e.addUniform("direction2", 3)
    }
    ,
    a.prototype.getEffectDefines = function() {
        return ""
    }
    ,
    a.prototype.getClassName = function() {
        return "MeshParticleEmitter"
    }
    ,
    a.prototype.serialize = function() {
        var e, i = {};
        return i.type = this.getClassName(),
        i.direction1 = this.direction1.asArray(),
        i.direction2 = this.direction2.asArray(),
        i.meshId = (e = this.mesh) === null || e === void 0 ? void 0 : e.id,
        i.useMeshNormalsForDirection = this.useMeshNormalsForDirection,
        i
    }
    ,
    a.prototype.parse = function(e, i) {
        Vector3.FromArrayToRef(e.direction1, 0, this.direction1),
        Vector3.FromArrayToRef(e.direction2, 0, this.direction2),
        e.meshId && i && (this.mesh = i.getLastMeshById(e.meshId)),
        this.useMeshNormalsForDirection = e.useMeshNormalsForDirection
    }
    ,
    a
}(), BaseParticleSystem = function() {
    function a(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 = a.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(a.prototype, "noiseTexture", {
        get: function() {
            return this._noiseTexture
        },
        set: function(e) {
            this._noiseTexture !== e && (this._noiseTexture = e,
            this._reset())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isAnimationSheetEnabled", {
        get: function() {
            return this._isAnimationSheetEnabled
        },
        set: function(e) {
            this._isAnimationSheetEnabled != e && (this._isAnimationSheetEnabled = e,
            this._reset())
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getScene = function() {
        return this._scene
    }
    ,
    a.prototype._hasTargetStopDurationDependantGradient = function() {
        return this._startSizeGradients && this._startSizeGradients.length > 0 || this._emitRateGradients && this._emitRateGradients.length > 0 || this._lifeTimeGradients && this._lifeTimeGradients.length > 0
    }
    ,
    a.prototype.getDragGradients = function() {
        return this._dragGradients
    }
    ,
    a.prototype.getLimitVelocityGradients = function() {
        return this._limitVelocityGradients
    }
    ,
    a.prototype.getColorGradients = function() {
        return this._colorGradients
    }
    ,
    a.prototype.getSizeGradients = function() {
        return this._sizeGradients
    }
    ,
    a.prototype.getColorRemapGradients = function() {
        return this._colorRemapGradients
    }
    ,
    a.prototype.getAlphaRemapGradients = function() {
        return this._alphaRemapGradients
    }
    ,
    a.prototype.getLifeTimeGradients = function() {
        return this._lifeTimeGradients
    }
    ,
    a.prototype.getAngularSpeedGradients = function() {
        return this._angularSpeedGradients
    }
    ,
    a.prototype.getVelocityGradients = function() {
        return this._velocityGradients
    }
    ,
    a.prototype.getStartSizeGradients = function() {
        return this._startSizeGradients
    }
    ,
    a.prototype.getEmitRateGradients = function() {
        return this._emitRateGradients
    }
    ,
    Object.defineProperty(a.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(a.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(a.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(a.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(a.prototype, "isBillboardBased", {
        get: function() {
            return this._isBillboardBased
        },
        set: function(e) {
            this._isBillboardBased !== e && (this._isBillboardBased = e,
            this._reset())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(e) {
            this._attachImageProcessingConfiguration(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._attachImageProcessingConfiguration = function(e) {
        e !== this._imageProcessingConfiguration && (!e && this._scene ? this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration : this._imageProcessingConfiguration = e)
    }
    ,
    a.prototype._reset = function() {}
    ,
    a.prototype._removeGradientAndTexture = function(e, i, o) {
        if (!i)
            return this;
        for (var s = 0, c = 0, d = i; c < d.length; c++) {
            var _ = d[c];
            if (_.gradient === e) {
                i.splice(s, 1);
                break
            }
            s++
        }
        return o && o.dispose(),
        this
    }
    ,
    a.prototype.createPointEmitter = function(e, i) {
        var o = new PointParticleEmitter;
        return o.direction1 = e,
        o.direction2 = i,
        this.particleEmitterType = o,
        o
    }
    ,
    a.prototype.createHemisphericEmitter = function(e, i) {
        e === void 0 && (e = 1),
        i === void 0 && (i = 1);
        var o = new HemisphericParticleEmitter(e,i);
        return this.particleEmitterType = o,
        o
    }
    ,
    a.prototype.createSphereEmitter = function(e, i) {
        e === void 0 && (e = 1),
        i === void 0 && (i = 1);
        var o = new SphereParticleEmitter(e,i);
        return this.particleEmitterType = o,
        o
    }
    ,
    a.prototype.createDirectedSphereEmitter = function(e, i, o) {
        e === void 0 && (e = 1),
        i === void 0 && (i = new Vector3(0,1,0)),
        o === void 0 && (o = new Vector3(0,1,0));
        var s = new SphereDirectedParticleEmitter(e,i,o);
        return this.particleEmitterType = s,
        s
    }
    ,
    a.prototype.createCylinderEmitter = function(e, i, o, s) {
        e === void 0 && (e = 1),
        i === void 0 && (i = 1),
        o === void 0 && (o = 1),
        s === void 0 && (s = 0);
        var c = new CylinderParticleEmitter(e,i,o,s);
        return this.particleEmitterType = c,
        c
    }
    ,
    a.prototype.createDirectedCylinderEmitter = function(e, i, o, s, c) {
        e === void 0 && (e = 1),
        i === void 0 && (i = 1),
        o === void 0 && (o = 1),
        s === void 0 && (s = new Vector3(0,1,0)),
        c === void 0 && (c = new Vector3(0,1,0));
        var d = new CylinderDirectedParticleEmitter(e,i,o,s,c);
        return this.particleEmitterType = d,
        d
    }
    ,
    a.prototype.createConeEmitter = function(e, i) {
        e === void 0 && (e = 1),
        i === void 0 && (i = Math.PI / 4);
        var o = new ConeParticleEmitter(e,i);
        return this.particleEmitterType = o,
        o
    }
    ,
    a.prototype.createBoxEmitter = function(e, i, o, s) {
        var c = new BoxParticleEmitter;
        return this.particleEmitterType = c,
        this.direction1 = e,
        this.direction2 = i,
        this.minEmitBox = o,
        this.maxEmitBox = s,
        c
    }
    ,
    a.BLENDMODE_ONEONE = 0,
    a.BLENDMODE_STANDARD = 1,
    a.BLENDMODE_ADD = 2,
    a.BLENDMODE_MULTIPLY = 3,
    a.BLENDMODE_MULTIPLYADD = 4,
    a
}(), Particle = function() {
    function a(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 = a._Count++,
        this.particleSystem.isAnimationSheetEnabled && this.updateCellInfoFromSystem()
    }
    return a.prototype.updateCellInfoFromSystem = function() {
        this.cellIndex = this.particleSystem.startSpriteCellID
    }
    ,
    a.prototype.updateCellIndex = function() {
        var e = this.age
          , i = this.particleSystem.spriteCellChangeSpeed;
        this.particleSystem.spriteRandomStartCell && (this._randomCellOffset === void 0 && (this._randomCellOffset = Math.random() * this.lifeTime),
        i === 0 ? (i = 1,
        e = this._randomCellOffset) : e += this._randomCellOffset);
        var o = this._initialEndSpriteCellID - this._initialStartSpriteCellID, s;
        this._initialSpriteCellLoop ? s = Scalar.Clamp(e * i % this.lifeTime / this.lifeTime) : s = Scalar.Clamp(e * i / this.lifeTime),
        this.cellIndex = this._initialStartSpriteCellID + s * o | 0
    }
    ,
    a.prototype._inheritParticleInfoToSubEmitter = function(e) {
        if (e.particleSystem.emitter.position) {
            var i = e.particleSystem.emitter;
            if (i.position.copyFrom(this.position),
            e.inheritDirection) {
                var o = TmpVectors.Vector3[0];
                this.direction.normalizeToRef(o),
                i.setDirection(o, 0, Math.PI / 2)
            }
        } else {
            var s = e.particleSystem.emitter;
            s.copyFrom(this.position)
        }
        this.direction.scaleToRef(e.inheritedVelocityAmount / 2, TmpVectors.Vector3[0]),
        e.particleSystem._inheritedVelocityOffset.copyFrom(TmpVectors.Vector3[0])
    }
    ,
    a.prototype._inheritParticleInfoToSubEmitters = function() {
        var e = this;
        this._attachedSubEmitters && this._attachedSubEmitters.length > 0 && this._attachedSubEmitters.forEach(function(i) {
            e._inheritParticleInfoToSubEmitter(i)
        })
    }
    ,
    a.prototype._reset = function() {
        this.age = 0,
        this.id = a._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
    }
    ,
    a.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()))
    }
    ,
    a._Count = 0,
    a
}(), SubEmitterType;
(function(a) {
    a[a.ATTACHED = 0] = "ATTACHED",
    a[a.END = 1] = "END"
}
)(SubEmitterType || (SubEmitterType = {}));
var SubEmitter = function() {
    function a(e) {
        if (this.particleSystem = e,
        this.type = SubEmitterType.END,
        this.inheritDirection = !1,
        this.inheritedVelocityAmount = 0,
        !e.emitter || !e.emitter.dispose) {
            var i = GetClass("BABYLON.AbstractMesh");
            e.emitter = new i("SubemitterSystemEmitter",e.getScene()),
            e._disposeEmitterOnDispose = !0
        }
    }
    return a.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 i = GetClass("BABYLON.Mesh");
            e = new i("",e.getScene()),
            e.isVisible = !1
        }
        var o = new a(this.particleSystem.clone(this.particleSystem.name, e));
        return o.particleSystem.name += "Clone",
        o.type = this.type,
        o.inheritDirection = this.inheritDirection,
        o.inheritedVelocityAmount = this.inheritedVelocityAmount,
        o.particleSystem._disposeEmitterOnDispose = !0,
        o.particleSystem.disposeOnStop = !0,
        o
    }
    ,
    a.prototype.serialize = function(e) {
        e === void 0 && (e = !1);
        var i = {};
        return i.type = this.type,
        i.inheritDirection = this.inheritDirection,
        i.inheritedVelocityAmount = this.inheritedVelocityAmount,
        i.particleSystem = this.particleSystem.serialize(e),
        i
    }
    ,
    a._ParseParticleSystem = function(e, i, o, s) {
        throw _WarnImport("ParseParticle")
    }
    ,
    a.Parse = function(e, i, o) {
        var s = e.particleSystem
          , c = new a(a._ParseParticleSystem(s, i, o, !0));
        return c.type = e.type,
        c.inheritDirection = e.inheritDirection,
        c.inheritedVelocityAmount = e.inheritedVelocityAmount,
        c.particleSystem._isSubEmitter = !0,
        c
    }
    ,
    a.prototype.dispose = function() {
        this.particleSystem.dispose()
    }
    ,
    a
}()
  , name$1m = "particlesPixelShader"
  , shader$1m = `
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$1m] = shader$1m;
var name$1l = "particlesVertexShader"
  , shader$1l = `
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$1l] = shader$1l;
var ParticleSystem = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _) {
        c === void 0 && (c = null),
        d === void 0 && (d = !1),
        _ === void 0 && (_ = .01);
        var b = a.call(this, i) || this;
        b._emitterInverseWorldMatrix = Matrix.Identity(),
        b._inheritedVelocityOffset = new Vector3,
        b.onDisposeObservable = new Observable,
        b.onStoppedObservable = new Observable,
        b._particles = new Array,
        b._stockParticles = new Array,
        b._newPartsExcess = 0,
        b._vertexBuffers = {},
        b._scaledColorStep = new Color4(0,0,0,0),
        b._colorDiff = new Color4(0,0,0,0),
        b._scaledDirection = Vector3.Zero(),
        b._scaledGravity = Vector3.Zero(),
        b._currentRenderId = -1,
        b._useInstancing = !1,
        b._started = !1,
        b._stopped = !1,
        b._actualFrame = 0,
        b._currentEmitRate1 = 0,
        b._currentEmitRate2 = 0,
        b._currentStartSize1 = 0,
        b._currentStartSize2 = 0,
        b._rawTextureWidth = 256,
        b._useRampGradients = !1,
        b._disposeEmitterOnDispose = !1,
        b.isLocal = !1,
        b._onBeforeDrawParticlesObservable = null,
        b.recycleParticle = function(j) {
            var $ = b._particles.pop();
            $ !== j && $.copyTo(j),
            b._stockParticles.push($)
        }
        ,
        b._createParticle = function() {
            var j;
            if (b._stockParticles.length !== 0 ? (j = b._stockParticles.pop(),
            j._reset()) : j = new Particle(b),
            b._subEmitters && b._subEmitters.length > 0) {
                var $ = b._subEmitters[Math.floor(Math.random() * b._subEmitters.length)];
                j._attachedSubEmitters = [],
                $.forEach(function(_e) {
                    if (_e.type === SubEmitterType.ATTACHED) {
                        var et = _e.clone();
                        j._attachedSubEmitters.push(et),
                        et.particleSystem.start()
                    }
                })
            }
            return j
        }
        ,
        b._emitFromParticle = function(j) {
            if (!(!b._subEmitters || b._subEmitters.length === 0)) {
                var $ = Math.floor(Math.random() * b._subEmitters.length);
                b._subEmitters[$].forEach(function(_e) {
                    if (_e.type === SubEmitterType.END) {
                        var et = _e.clone();
                        j._inheritParticleInfoToSubEmitter(et),
                        et.particleSystem._rootParticleSystem = b,
                        b.activeSubSystems.push(et.particleSystem),
                        et.particleSystem.start()
                    }
                })
            }
        }
        ,
        b._capacity = o,
        b._epsilon = _,
        b._isAnimationSheetEnabled = d,
        !s || s.getClassName() === "Scene" ? (b._scene = s || EngineStore.LastCreatedScene,
        b._engine = b._scene.getEngine(),
        b.uniqueId = b._scene.getUniqueId(),
        b._scene.particleSystems.push(b)) : (b._engine = s,
        b.defaultProjectionMatrix = Matrix.PerspectiveFovLH(.8, 1, .1, 100, b._engine.isNDCHalfZRange)),
        b._engine.getCaps().vertexArrayObject && (b._vertexArrayObject = null),
        b._attachImageProcessingConfiguration(null),
        b._customWrappers = {
            0: new DrawWrapper(b._engine)
        },
        b._customWrappers[0].effect = c,
        b._drawWrappers = [],
        b._useInstancing = b._engine.getCaps().instancedArrays,
        b._createIndexBuffer(),
        b._createVertexBuffers(),
        b.particleEmitterType = new BoxParticleEmitter;
        var k = null;
        return b.updateFunction = function(j) {
            var $, _e = null;
            b.noiseTexture && (_e = b.noiseTexture.getSize(),
            ($ = b.noiseTexture.getContent()) === null || $ === void 0 || $.then(function(it) {
                k = it
            }));
            for (var et = function() {
                tt = j[rt];
                var it = b._scaledUpdateSpeed
                  , nt = tt.age;
                if (tt.age += it,
                tt.age > tt.lifeTime) {
                    var ot = tt.age - nt
                      , at = tt.lifeTime - nt;
                    it = at * it / ot,
                    tt.age = tt.lifeTime
                }
                var st = tt.age / tt.lifeTime;
                b._colorGradients && b._colorGradients.length > 0 ? GradientHelper.GetCurrentGradient(st, b._colorGradients, function(dt, _t, mt) {
                    dt !== tt._currentColorGradient && (tt._currentColor1.copyFrom(tt._currentColor2),
                    _t.getColorToRef(tt._currentColor2),
                    tt._currentColorGradient = dt),
                    Color4.LerpToRef(tt._currentColor1, tt._currentColor2, mt, tt.color)
                }) : (tt.colorStep.scaleToRef(it, b._scaledColorStep),
                tt.color.addInPlace(b._scaledColorStep),
                tt.color.a < 0 && (tt.color.a = 0)),
                b._angularSpeedGradients && b._angularSpeedGradients.length > 0 && GradientHelper.GetCurrentGradient(st, b._angularSpeedGradients, function(dt, _t, mt) {
                    dt !== tt._currentAngularSpeedGradient && (tt._currentAngularSpeed1 = tt._currentAngularSpeed2,
                    tt._currentAngularSpeed2 = _t.getFactor(),
                    tt._currentAngularSpeedGradient = dt),
                    tt.angularSpeed = Scalar.Lerp(tt._currentAngularSpeed1, tt._currentAngularSpeed2, mt)
                }),
                tt.angle += tt.angularSpeed * it;
                var ut = it;
                if (b._velocityGradients && b._velocityGradients.length > 0 && GradientHelper.GetCurrentGradient(st, b._velocityGradients, function(dt, _t, mt) {
                    dt !== tt._currentVelocityGradient && (tt._currentVelocity1 = tt._currentVelocity2,
                    tt._currentVelocity2 = _t.getFactor(),
                    tt._currentVelocityGradient = dt),
                    ut *= Scalar.Lerp(tt._currentVelocity1, tt._currentVelocity2, mt)
                }),
                tt.direction.scaleToRef(ut, b._scaledDirection),
                b._limitVelocityGradients && b._limitVelocityGradients.length > 0 && GradientHelper.GetCurrentGradient(st, b._limitVelocityGradients, function(dt, _t, mt) {
                    dt !== tt._currentLimitVelocityGradient && (tt._currentLimitVelocity1 = tt._currentLimitVelocity2,
                    tt._currentLimitVelocity2 = _t.getFactor(),
                    tt._currentLimitVelocityGradient = dt);
                    var vt = Scalar.Lerp(tt._currentLimitVelocity1, tt._currentLimitVelocity2, mt)
                      , yt = tt.direction.length();
                    yt > vt && tt.direction.scaleInPlace(b.limitVelocityDamping)
                }),
                b._dragGradients && b._dragGradients.length > 0 && GradientHelper.GetCurrentGradient(st, b._dragGradients, function(dt, _t, mt) {
                    dt !== tt._currentDragGradient && (tt._currentDrag1 = tt._currentDrag2,
                    tt._currentDrag2 = _t.getFactor(),
                    tt._currentDragGradient = dt);
                    var vt = Scalar.Lerp(tt._currentDrag1, tt._currentDrag2, mt);
                    b._scaledDirection.scaleInPlace(1 - vt)
                }),
                b.isLocal && tt._localPosition ? (tt._localPosition.addInPlace(b._scaledDirection),
                Vector3.TransformCoordinatesToRef(tt._localPosition, b._emitterWorldMatrix, tt.position)) : tt.position.addInPlace(b._scaledDirection),
                k && _e && tt._randomNoiseCoordinates1) {
                    var ct = b._fetchR(tt._randomNoiseCoordinates1.x, tt._randomNoiseCoordinates1.y, _e.width, _e.height, k)
                      , lt = b._fetchR(tt._randomNoiseCoordinates1.z, tt._randomNoiseCoordinates2.x, _e.width, _e.height, k)
                      , ft = b._fetchR(tt._randomNoiseCoordinates2.y, tt._randomNoiseCoordinates2.z, _e.width, _e.height, k)
                      , ht = TmpVectors.Vector3[0]
                      , pt = TmpVectors.Vector3[1];
                    ht.copyFromFloats((2 * ct - 1) * b.noiseStrength.x, (2 * lt - 1) * b.noiseStrength.y, (2 * ft - 1) * b.noiseStrength.z),
                    ht.scaleToRef(it, pt),
                    tt.direction.addInPlace(pt)
                }
                if (b.gravity.scaleToRef(it, b._scaledGravity),
                tt.direction.addInPlace(b._scaledGravity),
                b._sizeGradients && b._sizeGradients.length > 0 && GradientHelper.GetCurrentGradient(st, b._sizeGradients, function(dt, _t, mt) {
                    dt !== tt._currentSizeGradient && (tt._currentSize1 = tt._currentSize2,
                    tt._currentSize2 = _t.getFactor(),
                    tt._currentSizeGradient = dt),
                    tt.size = Scalar.Lerp(tt._currentSize1, tt._currentSize2, mt)
                }),
                b._useRampGradients && (b._colorRemapGradients && b._colorRemapGradients.length > 0 && GradientHelper.GetCurrentGradient(st, b._colorRemapGradients, function(dt, _t, mt) {
                    var vt = Scalar.Lerp(dt.factor1, _t.factor1, mt)
                      , yt = Scalar.Lerp(dt.factor2, _t.factor2, mt);
                    tt.remapData.x = vt,
                    tt.remapData.y = yt - vt
                }),
                b._alphaRemapGradients && b._alphaRemapGradients.length > 0 && GradientHelper.GetCurrentGradient(st, b._alphaRemapGradients, function(dt, _t, mt) {
                    var vt = Scalar.Lerp(dt.factor1, _t.factor1, mt)
                      , yt = Scalar.Lerp(dt.factor2, _t.factor2, mt);
                    tt.remapData.z = vt,
                    tt.remapData.w = yt - vt
                })),
                b._isAnimationSheetEnabled && tt.updateCellIndex(),
                tt._inheritParticleInfoToSubEmitters(),
                tt.age >= tt.lifeTime)
                    return b._emitFromParticle(tt),
                    tt._attachedSubEmitters && (tt._attachedSubEmitters.forEach(function(dt) {
                        dt.particleSystem.disposeOnStop = !0,
                        dt.particleSystem.stop()
                    }),
                    tt._attachedSubEmitters = null),
                    b.recycleParticle(tt),
                    rt--,
                    "continue"
            }, tt, rt = 0; rt < j.length; rt++)
                et()
        }
        ,
        b
    }
    return Object.defineProperty(e.prototype, "onDispose", {
        set: function(i) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useRampGradients", {
        get: function() {
            return this._useRampGradients
        },
        set: function(i) {
            this._useRampGradients !== i && (this._useRampGradients = i,
            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(i) {
        var o, s;
        return i === void 0 && (i = 0),
        (s = (o = this._customWrappers[i]) === null || o === void 0 ? void 0 : o.effect) !== null && s !== void 0 ? s : this._customWrappers[0].effect
    }
    ,
    e.prototype._getCustomDrawWrapper = function(i) {
        var o;
        return i === void 0 && (i = 0),
        (o = this._customWrappers[i]) !== null && o !== void 0 ? o : this._customWrappers[0]
    }
    ,
    e.prototype.setCustomEffect = function(i, o) {
        o === void 0 && (o = 0),
        this._customWrappers[o] = new DrawWrapper(this._engine),
        this._customWrappers[o].effect = i,
        this._customWrappers[o].drawContext && (this._customWrappers[o].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(i, o, s, c) {
        var d = new FactorGradient(o,s,c);
        i.push(d),
        i.sort(function(_, b) {
            return _.gradient < b.gradient ? -1 : _.gradient > b.gradient ? 1 : 0
        })
    }
    ,
    e.prototype._removeFactorGradient = function(i, o) {
        if (!!i)
            for (var s = 0, c = 0, d = i; c < d.length; c++) {
                var _ = d[c];
                if (_.gradient === o) {
                    i.splice(s, 1);
                    break
                }
                s++
            }
    }
    ,
    e.prototype.addLifeTimeGradient = function(i, o, s) {
        return this._lifeTimeGradients || (this._lifeTimeGradients = []),
        this._addFactorGradient(this._lifeTimeGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeLifeTimeGradient = function(i) {
        return this._removeFactorGradient(this._lifeTimeGradients, i),
        this
    }
    ,
    e.prototype.addSizeGradient = function(i, o, s) {
        return this._sizeGradients || (this._sizeGradients = []),
        this._addFactorGradient(this._sizeGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeSizeGradient = function(i) {
        return this._removeFactorGradient(this._sizeGradients, i),
        this
    }
    ,
    e.prototype.addColorRemapGradient = function(i, o, s) {
        return this._colorRemapGradients || (this._colorRemapGradients = []),
        this._addFactorGradient(this._colorRemapGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeColorRemapGradient = function(i) {
        return this._removeFactorGradient(this._colorRemapGradients, i),
        this
    }
    ,
    e.prototype.addAlphaRemapGradient = function(i, o, s) {
        return this._alphaRemapGradients || (this._alphaRemapGradients = []),
        this._addFactorGradient(this._alphaRemapGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeAlphaRemapGradient = function(i) {
        return this._removeFactorGradient(this._alphaRemapGradients, i),
        this
    }
    ,
    e.prototype.addAngularSpeedGradient = function(i, o, s) {
        return this._angularSpeedGradients || (this._angularSpeedGradients = []),
        this._addFactorGradient(this._angularSpeedGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeAngularSpeedGradient = function(i) {
        return this._removeFactorGradient(this._angularSpeedGradients, i),
        this
    }
    ,
    e.prototype.addVelocityGradient = function(i, o, s) {
        return this._velocityGradients || (this._velocityGradients = []),
        this._addFactorGradient(this._velocityGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeVelocityGradient = function(i) {
        return this._removeFactorGradient(this._velocityGradients, i),
        this
    }
    ,
    e.prototype.addLimitVelocityGradient = function(i, o, s) {
        return this._limitVelocityGradients || (this._limitVelocityGradients = []),
        this._addFactorGradient(this._limitVelocityGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeLimitVelocityGradient = function(i) {
        return this._removeFactorGradient(this._limitVelocityGradients, i),
        this
    }
    ,
    e.prototype.addDragGradient = function(i, o, s) {
        return this._dragGradients || (this._dragGradients = []),
        this._addFactorGradient(this._dragGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeDragGradient = function(i) {
        return this._removeFactorGradient(this._dragGradients, i),
        this
    }
    ,
    e.prototype.addEmitRateGradient = function(i, o, s) {
        return this._emitRateGradients || (this._emitRateGradients = []),
        this._addFactorGradient(this._emitRateGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeEmitRateGradient = function(i) {
        return this._removeFactorGradient(this._emitRateGradients, i),
        this
    }
    ,
    e.prototype.addStartSizeGradient = function(i, o, s) {
        return this._startSizeGradients || (this._startSizeGradients = []),
        this._addFactorGradient(this._startSizeGradients, i, o, s),
        this
    }
    ,
    e.prototype.removeStartSizeGradient = function(i) {
        return this._removeFactorGradient(this._startSizeGradients, i),
        this
    }
    ,
    e.prototype._createRampGradientTexture = function() {
        if (!(!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene)) {
            for (var i = new Uint8Array(this._rawTextureWidth * 4), o = TmpColors.Color3[0], s = 0; s < this._rawTextureWidth; s++) {
                var c = s / this._rawTextureWidth;
                GradientHelper.GetCurrentGradient(c, this._rampGradients, function(d, _, b) {
                    Color3.LerpToRef(d.color, _.color, b, o),
                    i[s * 4] = o.r * 255,
                    i[s * 4 + 1] = o.g * 255,
                    i[s * 4 + 2] = o.b * 255,
                    i[s * 4 + 3] = 255
                })
            }
            this._rampGradientsTexture = RawTexture.CreateRGBATexture(i, 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(i, o) {
            return i.gradient < o.gradient ? -1 : i.gradient > o.gradient ? 1 : 0
        }),
        this._rampGradientsTexture && (this._rampGradientsTexture.dispose(),
        this._rampGradientsTexture = null),
        this._createRampGradientTexture())
    }
    ,
    e.prototype.addRampGradient = function(i, o) {
        this._rampGradients || (this._rampGradients = []);
        var s = new Color3Gradient(i,o);
        return this._rampGradients.push(s),
        this._syncRampGradientTexture(),
        this
    }
    ,
    e.prototype.removeRampGradient = function(i) {
        return this._removeGradientAndTexture(i, this._rampGradients, this._rampGradientsTexture),
        this._rampGradientsTexture = null,
        this._rampGradients && this._rampGradients.length > 0 && this._createRampGradientTexture(),
        this
    }
    ,
    e.prototype.addColorGradient = function(i, o, s) {
        this._colorGradients || (this._colorGradients = []);
        var c = new ColorGradient(i,o,s);
        return this._colorGradients.push(c),
        this._colorGradients.sort(function(d, _) {
            return d.gradient < _.gradient ? -1 : d.gradient > _.gradient ? 1 : 0
        }),
        this
    }
    ,
    e.prototype.removeColorGradient = function(i) {
        if (!this._colorGradients)
            return this;
        for (var o = 0, s = 0, c = this._colorGradients; s < c.length; s++) {
            var d = c[s];
            if (d.gradient === i) {
                this._colorGradients.splice(o, 1);
                break
            }
            o++
        }
        return this
    }
    ,
    e.prototype.resetDrawCache = function() {
        for (var i = 0, o = this._drawWrappers; i < o.length; i++) {
            var s = o[i];
            if (s)
                for (var c = 0, d = s; c < d.length; c++) {
                    var _ = d[c];
                    _ == null || _.dispose()
                }
        }
        this._drawWrappers = []
    }
    ,
    e.prototype._fetchR = function(i, o, s, c, d) {
        i = Math.abs(i) * .5 + .5,
        o = Math.abs(o) * .5 + .5;
        var _ = i * s % s | 0
          , b = o * c % c | 0
          , k = (_ + b * s) * 4;
        return d[k] / 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 i = this._engine;
        this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4)),
        this._vertexBuffer = new Buffer(i,this._vertexData,!0,this._vertexBufferSize);
        var o = 0
          , s = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, o, 3, this._vertexBufferSize, this._useInstancing);
        this._vertexBuffers[VertexBuffer.PositionKind] = s,
        o += 3;
        var c = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, o, 4, this._vertexBufferSize, this._useInstancing);
        this._vertexBuffers[VertexBuffer.ColorKind] = c,
        o += 4;
        var d = this._vertexBuffer.createVertexBuffer("angle", o, 1, this._vertexBufferSize, this._useInstancing);
        this._vertexBuffers.angle = d,
        o += 1;
        var _ = this._vertexBuffer.createVertexBuffer("size", o, 2, this._vertexBufferSize, this._useInstancing);
        if (this._vertexBuffers.size = _,
        o += 2,
        this._isAnimationSheetEnabled) {
            var b = this._vertexBuffer.createVertexBuffer("cellIndex", o, 1, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers.cellIndex = b,
            o += 1
        }
        if (!this._isBillboardBased || this.billboardMode === e.BILLBOARDMODE_STRETCHED) {
            var k = this._vertexBuffer.createVertexBuffer("direction", o, 3, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers.direction = k,
            o += 3
        }
        if (this._useRampGradients) {
            var j = this._vertexBuffer.createVertexBuffer("remapData", o, 4, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers.remapData = j,
            o += 4
        }
        var $;
        if (this._useInstancing) {
            var _e = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
            this._spriteBuffer = new Buffer(i,_e,!1,2),
            $ = this._spriteBuffer.createVertexBuffer("offset", 0, 2)
        } else
            $ = this._vertexBuffer.createVertexBuffer("offset", o, 2, this._vertexBufferSize, this._useInstancing),
            o += 2;
        this._vertexBuffers.offset = $,
        this.resetDrawCache()
    }
    ,
    e.prototype._createIndexBuffer = function() {
        if (!this._useInstancing) {
            for (var i = [], o = 0, s = 0; s < this._capacity; s++)
                i.push(o),
                i.push(o + 1),
                i.push(o + 2),
                i.push(o),
                i.push(o + 2),
                i.push(o + 3),
                o += 4;
            this._indexBuffer = this._engine.createIndexBuffer(i)
        }
    }
    ,
    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 i = this;
        this._subEmitters = new Array,
        this.subEmitters && this.subEmitters.forEach(function(o) {
            o instanceof e ? i._subEmitters.push([new SubEmitter(o)]) : o instanceof SubEmitter ? i._subEmitters.push([o]) : o instanceof Array && i._subEmitters.push(o)
        })
    }
    ,
    e.prototype.start = function(i) {
        var o = this, s;
        if (i === void 0 && (i = this.startDelay),
        !this.targetStopDuration && this._hasTargetStopDurationDependantGradient())
            throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
        if (i) {
            setTimeout(function() {
                o.start(0)
            }, i);
            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) {
            ((s = this.emitter) === null || s === void 0 ? void 0 : s.getClassName().indexOf("Mesh")) !== -1 && this.emitter.computeWorldMatrix(!0);
            var c = this.noiseTexture;
            if (c && c.onGeneratedObservable)
                c.onGeneratedObservable.addOnce(function() {
                    setTimeout(function() {
                        for (var _ = 0; _ < o.preWarmCycles; _++)
                            o.animate(!0),
                            c.render()
                    })
                });
            else
                for (var d = 0; d < this.preWarmCycles; d++)
                    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(i) {
        i === void 0 && (i = !0),
        !this._stopped && (this.onStoppedObservable.notifyObservers(this),
        this._stopped = !0,
        i && this._stopSubEmitters())
    }
    ,
    e.prototype.reset = function() {
        this._stockParticles = [],
        this._particles = []
    }
    ,
    e.prototype._appendParticleVertex = function(i, o, s, c) {
        var d = i * this._vertexBufferSize;
        if (this._vertexData[d++] = o.position.x + this.worldOffset.x,
        this._vertexData[d++] = o.position.y + this.worldOffset.y,
        this._vertexData[d++] = o.position.z + this.worldOffset.z,
        this._vertexData[d++] = o.color.r,
        this._vertexData[d++] = o.color.g,
        this._vertexData[d++] = o.color.b,
        this._vertexData[d++] = o.color.a,
        this._vertexData[d++] = o.angle,
        this._vertexData[d++] = o.scale.x * o.size,
        this._vertexData[d++] = o.scale.y * o.size,
        this._isAnimationSheetEnabled && (this._vertexData[d++] = o.cellIndex),
        this._isBillboardBased)
            this.billboardMode === e.BILLBOARDMODE_STRETCHED && (this._vertexData[d++] = o.direction.x,
            this._vertexData[d++] = o.direction.y,
            this._vertexData[d++] = o.direction.z);
        else if (o._initialDirection) {
            var _ = o._initialDirection;
            this.isLocal && (Vector3.TransformNormalToRef(_, this._emitterWorldMatrix, TmpVectors.Vector3[0]),
            _ = TmpVectors.Vector3[0]),
            _.x === 0 && _.z === 0 && (_.x = .001),
            this._vertexData[d++] = _.x,
            this._vertexData[d++] = _.y,
            this._vertexData[d++] = _.z
        } else {
            var b = o.direction;
            this.isLocal && (Vector3.TransformNormalToRef(b, this._emitterWorldMatrix, TmpVectors.Vector3[0]),
            b = TmpVectors.Vector3[0]),
            b.x === 0 && b.z === 0 && (b.x = .001),
            this._vertexData[d++] = b.x,
            this._vertexData[d++] = b.y,
            this._vertexData[d++] = b.z
        }
        this._useRampGradients && o.remapData && (this._vertexData[d++] = o.remapData.x,
        this._vertexData[d++] = o.remapData.y,
        this._vertexData[d++] = o.remapData.z,
        this._vertexData[d++] = o.remapData.w),
        this._useInstancing || (this._isAnimationSheetEnabled && (s === 0 ? s = this._epsilon : s === 1 && (s = 1 - this._epsilon),
        c === 0 ? c = this._epsilon : c === 1 && (c = 1 - this._epsilon)),
        this._vertexData[d++] = s,
        this._vertexData[d++] = c)
    }
    ,
    e.prototype._stopSubEmitters = function() {
        !this.activeSubSystems || (this.activeSubSystems.forEach(function(i) {
            i.stop(!0)
        }),
        this.activeSubSystems = new Array)
    }
    ,
    e.prototype._removeFromRoot = function() {
        if (!!this._rootParticleSystem) {
            var i = this._rootParticleSystem.activeSubSystems.indexOf(this);
            i !== -1 && this._rootParticleSystem.activeSubSystems.splice(i, 1),
            this._rootParticleSystem = null
        }
    }
    ,
    e.prototype._update = function(i) {
        var o = this;
        if (this._alive = this._particles.length > 0,
        this.emitter.position) {
            var s = this.emitter;
            this._emitterWorldMatrix = s.getWorldMatrix()
        } else {
            var c = this.emitter;
            this._emitterWorldMatrix = Matrix.Translation(c.x, c.y, c.z)
        }
        this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),
        this.updateFunction(this._particles);
        for (var d, _ = function() {
            if (b._particles.length === b._capacity)
                return "break";
            if (d = b._createParticle(),
            b._particles.push(d),
            b.targetStopDuration && b._lifeTimeGradients && b._lifeTimeGradients.length > 0) {
                var _e = Scalar.Clamp(b._actualFrame / b.targetStopDuration);
                GradientHelper.GetCurrentGradient(_e, b._lifeTimeGradients, function(rt, it) {
                    var nt = rt
                      , ot = it
                      , at = nt.getFactor()
                      , st = ot.getFactor()
                      , ut = (_e - nt.gradient) / (ot.gradient - nt.gradient);
                    d.lifeTime = Scalar.Lerp(at, st, ut)
                })
            } else
                d.lifeTime = Scalar.RandomRange(b.minLifeTime, b.maxLifeTime);
            var et = Scalar.RandomRange(b.minEmitPower, b.maxEmitPower);
            if (b.startPositionFunction ? b.startPositionFunction(b._emitterWorldMatrix, d.position, d, b.isLocal) : b.particleEmitterType.startPositionFunction(b._emitterWorldMatrix, d.position, d, b.isLocal),
            b.isLocal && (d._localPosition ? d._localPosition.copyFrom(d.position) : d._localPosition = d.position.clone(),
            Vector3.TransformCoordinatesToRef(d._localPosition, b._emitterWorldMatrix, d.position)),
            b.startDirectionFunction ? b.startDirectionFunction(b._emitterWorldMatrix, d.direction, d, b.isLocal) : b.particleEmitterType.startDirectionFunction(b._emitterWorldMatrix, d.direction, d, b.isLocal, b._emitterInverseWorldMatrix),
            et === 0 ? d._initialDirection ? d._initialDirection.copyFrom(d.direction) : d._initialDirection = d.direction.clone() : d._initialDirection = null,
            d.direction.scaleInPlace(et),
            !b._sizeGradients || b._sizeGradients.length === 0 ? d.size = Scalar.RandomRange(b.minSize, b.maxSize) : (d._currentSizeGradient = b._sizeGradients[0],
            d._currentSize1 = d._currentSizeGradient.getFactor(),
            d.size = d._currentSize1,
            b._sizeGradients.length > 1 ? d._currentSize2 = b._sizeGradients[1].getFactor() : d._currentSize2 = d._currentSize1),
            d.scale.copyFromFloats(Scalar.RandomRange(b.minScaleX, b.maxScaleX), Scalar.RandomRange(b.minScaleY, b.maxScaleY)),
            b._startSizeGradients && b._startSizeGradients[0] && b.targetStopDuration) {
                var tt = b._actualFrame / b.targetStopDuration;
                GradientHelper.GetCurrentGradient(tt, b._startSizeGradients, function(rt, it, nt) {
                    rt !== o._currentStartSizeGradient && (o._currentStartSize1 = o._currentStartSize2,
                    o._currentStartSize2 = it.getFactor(),
                    o._currentStartSizeGradient = rt);
                    var ot = Scalar.Lerp(o._currentStartSize1, o._currentStartSize2, nt);
                    d.scale.scaleInPlace(ot)
                })
            }
            !b._angularSpeedGradients || b._angularSpeedGradients.length === 0 ? d.angularSpeed = Scalar.RandomRange(b.minAngularSpeed, b.maxAngularSpeed) : (d._currentAngularSpeedGradient = b._angularSpeedGradients[0],
            d.angularSpeed = d._currentAngularSpeedGradient.getFactor(),
            d._currentAngularSpeed1 = d.angularSpeed,
            b._angularSpeedGradients.length > 1 ? d._currentAngularSpeed2 = b._angularSpeedGradients[1].getFactor() : d._currentAngularSpeed2 = d._currentAngularSpeed1),
            d.angle = Scalar.RandomRange(b.minInitialRotation, b.maxInitialRotation),
            b._velocityGradients && b._velocityGradients.length > 0 && (d._currentVelocityGradient = b._velocityGradients[0],
            d._currentVelocity1 = d._currentVelocityGradient.getFactor(),
            b._velocityGradients.length > 1 ? d._currentVelocity2 = b._velocityGradients[1].getFactor() : d._currentVelocity2 = d._currentVelocity1),
            b._limitVelocityGradients && b._limitVelocityGradients.length > 0 && (d._currentLimitVelocityGradient = b._limitVelocityGradients[0],
            d._currentLimitVelocity1 = d._currentLimitVelocityGradient.getFactor(),
            b._limitVelocityGradients.length > 1 ? d._currentLimitVelocity2 = b._limitVelocityGradients[1].getFactor() : d._currentLimitVelocity2 = d._currentLimitVelocity1),
            b._dragGradients && b._dragGradients.length > 0 && (d._currentDragGradient = b._dragGradients[0],
            d._currentDrag1 = d._currentDragGradient.getFactor(),
            b._dragGradients.length > 1 ? d._currentDrag2 = b._dragGradients[1].getFactor() : d._currentDrag2 = d._currentDrag1),
            !b._colorGradients || b._colorGradients.length === 0 ? (k = Scalar.RandomRange(0, 1),
            Color4.LerpToRef(b.color1, b.color2, k, d.color),
            b.colorDead.subtractToRef(d.color, b._colorDiff),
            b._colorDiff.scaleToRef(1 / d.lifeTime, d.colorStep)) : (d._currentColorGradient = b._colorGradients[0],
            d._currentColorGradient.getColorToRef(d.color),
            d._currentColor1.copyFrom(d.color),
            b._colorGradients.length > 1 ? b._colorGradients[1].getColorToRef(d._currentColor2) : d._currentColor2.copyFrom(d.color)),
            b._isAnimationSheetEnabled && (d._initialStartSpriteCellID = b.startSpriteCellID,
            d._initialEndSpriteCellID = b.endSpriteCellID,
            d._initialSpriteCellLoop = b.spriteCellLoop),
            d.direction.addInPlace(b._inheritedVelocityOffset),
            b._useRampGradients && (d.remapData = new Vector4(0,1,0,1)),
            b.noiseTexture && (d._randomNoiseCoordinates1 ? (d._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random()),
            d._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random())) : (d._randomNoiseCoordinates1 = new Vector3(Math.random(),Math.random(),Math.random()),
            d._randomNoiseCoordinates2 = new Vector3(Math.random(),Math.random(),Math.random()))),
            d._inheritParticleInfoToSubEmitters()
        }, b = this, k, j = 0; j < i; j++) {
            var $ = _();
            if ($ === "break")
                break
        }
    }
    ,
    e._GetAttributeNamesOrOptions = function(i, o, s) {
        i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        s === void 0 && (s = !1);
        var c = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"];
        return i && c.push("cellIndex"),
        o || c.push("direction"),
        s && c.push("remapData"),
        c
    }
    ,
    e._GetEffectCreationOptions = function(i) {
        i === void 0 && (i = !1);
        var o = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "textureMask", "translationPivot", "eyePosition"];
        return i && o.push("particlesInfos"),
        o
    }
    ,
    e.prototype.fillDefines = function(i, o) {
        if (this._scene && (this._scene.clipPlane && i.push("#define CLIPPLANE"),
        this._scene.clipPlane2 && i.push("#define CLIPPLANE2"),
        this._scene.clipPlane3 && i.push("#define CLIPPLANE3"),
        this._scene.clipPlane4 && i.push("#define CLIPPLANE4"),
        this._scene.clipPlane5 && i.push("#define CLIPPLANE5"),
        this._scene.clipPlane6 && i.push("#define CLIPPLANE6")),
        this._isAnimationSheetEnabled && i.push("#define ANIMATESHEET"),
        o === e.BLENDMODE_MULTIPLY && i.push("#define BLENDMULTIPLYMODE"),
        this._useRampGradients && i.push("#define RAMPGRADIENT"),
        this._isBillboardBased)
            switch (i.push("#define BILLBOARD"),
            this.billboardMode) {
            case e.BILLBOARDMODE_Y:
                i.push("#define BILLBOARDY");
                break;
            case e.BILLBOARDMODE_STRETCHED:
                i.push("#define BILLBOARDSTRETCHED");
                break;
            case e.BILLBOARDMODE_ALL:
                i.push("#define BILLBOARDMODE_ALL");
                break
            }
        this._imageProcessingConfiguration && (this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),
        i.push(this._imageProcessingConfigurationDefines.toString()))
    }
    ,
    e.prototype.fillUniformsAttributesAndSamplerNames = function(i, o, s) {
        o.push.apply(o, e._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== e.BILLBOARDMODE_STRETCHED, this._useRampGradients)),
        i.push.apply(i, e._GetEffectCreationOptions(this._isAnimationSheetEnabled)),
        s.push("diffuseSampler", "rampSampler"),
        this._imageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms(i, this._imageProcessingConfigurationDefines),
        ImageProcessingConfiguration.PrepareSamplers(s, this._imageProcessingConfigurationDefines))
    }
    ,
    e.prototype._getWrapper = function(i) {
        var o = this._getCustomDrawWrapper(i);
        if (o != null && o.effect)
            return o;
        var s = [];
        this.fillDefines(s, i);
        var c = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0
          , d = this._drawWrappers[c];
        d || (d = this._drawWrappers[c] = []);
        var _ = d[i];
        _ || (_ = new DrawWrapper(this._engine),
        _.drawContext && (_.drawContext.useInstancing = this._useInstancing),
        d[i] = _);
        var b = s.join(`
`);
        if (_.defines !== b) {
            var k = []
              , j = []
              , $ = [];
            this.fillUniformsAttributesAndSamplerNames(j, k, $),
            _.setEffect(this._engine.createEffect("particles", k, j, $, b), b)
        }
        return _
    }
    ,
    e.prototype.animate = function(i) {
        var o = this, s;
        if (i === void 0 && (i = !1),
        !!this._started) {
            if (!i && this._scene) {
                if (!this.isReady() || this._currentRenderId === this._scene.getFrameId())
                    return;
                this._currentRenderId = this._scene.getFrameId()
            }
            this._scaledUpdateSpeed = this.updateSpeed * (i ? this.preWarmStepOffset : ((s = this._scene) === null || s === void 0 ? void 0 : s.getAnimationRatio()) || 1);
            var c;
            if (this.manualEmitCount > -1)
                c = this.manualEmitCount,
                this._newPartsExcess = 0,
                this.manualEmitCount = 0;
            else {
                var d = this.emitRate;
                if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
                    var _ = this._actualFrame / this.targetStopDuration;
                    GradientHelper.GetCurrentGradient(_, this._emitRateGradients, function($, _e, et) {
                        $ !== o._currentEmitRateGradient && (o._currentEmitRate1 = o._currentEmitRate2,
                        o._currentEmitRate2 = _e.getFactor(),
                        o._currentEmitRateGradient = $),
                        d = Scalar.Lerp(o._currentEmitRate1, o._currentEmitRate2, et)
                    })
                }
                c = d * this._scaledUpdateSpeed >> 0,
                this._newPartsExcess += d * this._scaledUpdateSpeed - c
            }
            if (this._newPartsExcess > 1 && (c += this._newPartsExcess >> 0,
            this._newPartsExcess -= this._newPartsExcess >> 0),
            this._alive = !1,
            this._stopped ? c = 0 : (this._actualFrame += this._scaledUpdateSpeed,
            this.targetStopDuration && this._actualFrame >= this.targetStopDuration && this.stop()),
            this._update(c),
            this._stopped && (this._alive || (this._started = !1,
            this.onAnimationEnd && this.onAnimationEnd(),
            this.disposeOnStop && this._scene && this._scene._toBeDisposed.push(this))),
            !i) {
                for (var b = 0, k = 0; k < this._particles.length; k++) {
                    var j = this._particles[k];
                    this._appendParticleVertices(b, j),
                    b += 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(i, o) {
        this._appendParticleVertex(i++, o, 0, 0),
        this._useInstancing || (this._appendParticleVertex(i++, o, 1, 0),
        this._appendParticleVertex(i++, o, 1, 1),
        this._appendParticleVertex(i++, o, 0, 1))
    }
    ,
    e.prototype.rebuild = function() {
        var i, o;
        this._engine.getCaps().vertexArrayObject && (this._vertexArrayObject = null),
        this._createIndexBuffer(),
        (i = this._spriteBuffer) === null || i === void 0 || i._rebuild(),
        (o = this._vertexBuffer) === null || o === void 0 || o._rebuild();
        for (var s in this._vertexBuffers)
            this._vertexBuffers[s]._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(i) {
        var o, s, c = this._getWrapper(i), d = c.effect, _ = this._engine;
        _.enableEffect(c);
        var b = (o = this.defaultViewMatrix) !== null && o !== void 0 ? o : this._scene.getViewMatrix();
        if (d.setTexture("diffuseSampler", this.particleTexture),
        d.setMatrix("view", b),
        d.setMatrix("projection", (s = this.defaultProjectionMatrix) !== null && s !== void 0 ? s : this._scene.getProjectionMatrix()),
        this._isAnimationSheetEnabled && this.particleTexture) {
            var k = this.particleTexture.getBaseSize();
            d.setFloat3("particlesInfos", this.spriteCellWidth / k.width, this.spriteCellHeight / k.height, this.spriteCellWidth / k.width)
        }
        if (d.setVector2("translationPivot", this.translationPivot),
        d.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a),
        this._isBillboardBased && this._scene) {
            var j = this._scene.activeCamera;
            d.setVector3("eyePosition", j.globalPosition)
        }
        this._rampGradientsTexture && ((!this._rampGradients || !this._rampGradients.length) && (this._rampGradientsTexture.dispose(),
        this._rampGradientsTexture = null),
        d.setTexture("rampSampler", this._rampGradientsTexture));
        var $ = d.defines;
        switch (this._scene && (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4 || this._scene.clipPlane5 || this._scene.clipPlane6) && ThinMaterialHelper.BindClipPlane(d, this._scene),
        $.indexOf("#define BILLBOARDMODE_ALL") >= 0 && (b.invertToRef(TmpVectors.Matrix[0]),
        d.setMatrix("invView", TmpVectors.Matrix[0])),
        this._vertexArrayObject !== void 0 ? (this._vertexArrayObject || (this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, d)),
        this._engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer)) : _.bindBuffers(this._vertexBuffers, this._indexBuffer, d),
        this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess && this._imageProcessingConfiguration.bind(d),
        i) {
        case e.BLENDMODE_ADD:
            _.setAlphaMode(1);
            break;
        case e.BLENDMODE_ONEONE:
            _.setAlphaMode(6);
            break;
        case e.BLENDMODE_STANDARD:
            _.setAlphaMode(2);
            break;
        case e.BLENDMODE_MULTIPLY:
            _.setAlphaMode(4);
            break
        }
        return this._onBeforeDrawParticlesObservable && this._onBeforeDrawParticlesObservable.notifyObservers(d),
        this._useInstancing ? _.drawArraysType(7, 0, 4, this._particles.length) : _.drawElementsType(0, 0, this._particles.length * 6),
        this._particles.length
    }
    ,
    e.prototype.render = function() {
        if (!this.isReady() || !this._particles.length)
            return 0;
        var i = this._engine;
        i.setState && (i.setState(!1),
        this.forceDepthWrite && i.setDepthWrite(!0));
        var o = 0;
        return this.blendMode === e.BLENDMODE_MULTIPLYADD ? o = this._render(e.BLENDMODE_MULTIPLY) + this._render(e.BLENDMODE_ADD) : o = this._render(this.blendMode),
        this._engine.unbindInstanceAttributes(),
        this._engine.setAlphaMode(0),
        o
    }
    ,
    e.prototype.dispose = function(i) {
        if (i === void 0 && (i = !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),
        i && this.particleTexture && (this.particleTexture.dispose(),
        this.particleTexture = null),
        i && 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 o = 0; o < this._subEmitters.length; o++)
                for (var s = 0, c = this._subEmitters[o]; s < c.length; s++) {
                    var d = c[s];
                    d.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 o = this._scene.particleSystems.indexOf(this);
            o > -1 && this._scene.particleSystems.splice(o, 1),
            this._scene._activeParticleSystems.dispose()
        }
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.onStoppedObservable.clear(),
        this.reset()
    }
    ,
    e.prototype.clone = function(i, o) {
        var s = __assign({}, this._customWrappers)
          , c = null
          , d = this._engine;
        if (d.createEffectForParticles && this.customShader != null) {
            c = this.customShader;
            var _ = c.shaderOptions.defines.length > 0 ? c.shaderOptions.defines.join(`
`) : "";
            s[0] = d.createEffectForParticles(c.shaderPath.fragmentElement, c.shaderOptions.uniforms, c.shaderOptions.samplers, _)
        }
        var b = this.serialize()
          , k = e.Parse(b, this._scene || this._engine, this._rootUrl);
        return k.name = i,
        k.customShader = c,
        k._customWrappers = s,
        o === void 0 && (o = this.emitter),
        this.noiseTexture && (k.noiseTexture = this.noiseTexture.clone()),
        k.emitter = o,
        this.preventAutoStart || k.start(),
        k
    }
    ,
    e.prototype.serialize = function(i) {
        i === void 0 && (i = !1);
        var o = {};
        if (e._Serialize(o, this, i),
        o.textureMask = this.textureMask.asArray(),
        o.customShader = this.customShader,
        o.preventAutoStart = this.preventAutoStart,
        this.subEmitters) {
            o.subEmitters = [],
            this._subEmitters || this._prepareSubEmitterInternalArray();
            for (var s = 0, c = this._subEmitters; s < c.length; s++) {
                for (var d = c[s], _ = [], b = 0, k = d; b < k.length; b++) {
                    var j = k[b];
                    _.push(j.serialize(i))
                }
                o.subEmitters.push(_)
            }
        }
        return o
    }
    ,
    e._Serialize = function(i, o, s) {
        if (i.name = o.name,
        i.id = o.id,
        i.capacity = o.getCapacity(),
        i.disposeOnStop = o.disposeOnStop,
        i.manualEmitCount = o.manualEmitCount,
        o.emitter.position) {
            var c = o.emitter;
            i.emitterId = c.id
        } else {
            var d = o.emitter;
            i.emitter = d.asArray()
        }
        o.particleEmitterType && (i.particleEmitterType = o.particleEmitterType.serialize()),
        o.particleTexture && (s ? i.texture = o.particleTexture.serialize() : (i.textureName = o.particleTexture.name,
        i.invertY = !!o.particleTexture._invertY)),
        i.isLocal = o.isLocal,
        SerializationHelper.AppendSerializedAnimations(o, i),
        i.beginAnimationOnStart = o.beginAnimationOnStart,
        i.beginAnimationFrom = o.beginAnimationFrom,
        i.beginAnimationTo = o.beginAnimationTo,
        i.beginAnimationLoop = o.beginAnimationLoop,
        i.startDelay = o.startDelay,
        i.renderingGroupId = o.renderingGroupId,
        i.isBillboardBased = o.isBillboardBased,
        i.billboardMode = o.billboardMode,
        i.minAngularSpeed = o.minAngularSpeed,
        i.maxAngularSpeed = o.maxAngularSpeed,
        i.minSize = o.minSize,
        i.maxSize = o.maxSize,
        i.minScaleX = o.minScaleX,
        i.maxScaleX = o.maxScaleX,
        i.minScaleY = o.minScaleY,
        i.maxScaleY = o.maxScaleY,
        i.minEmitPower = o.minEmitPower,
        i.maxEmitPower = o.maxEmitPower,
        i.minLifeTime = o.minLifeTime,
        i.maxLifeTime = o.maxLifeTime,
        i.emitRate = o.emitRate,
        i.gravity = o.gravity.asArray(),
        i.noiseStrength = o.noiseStrength.asArray(),
        i.color1 = o.color1.asArray(),
        i.color2 = o.color2.asArray(),
        i.colorDead = o.colorDead.asArray(),
        i.updateSpeed = o.updateSpeed,
        i.targetStopDuration = o.targetStopDuration,
        i.blendMode = o.blendMode,
        i.preWarmCycles = o.preWarmCycles,
        i.preWarmStepOffset = o.preWarmStepOffset,
        i.minInitialRotation = o.minInitialRotation,
        i.maxInitialRotation = o.maxInitialRotation,
        i.startSpriteCellID = o.startSpriteCellID,
        i.spriteCellLoop = o.spriteCellLoop,
        i.endSpriteCellID = o.endSpriteCellID,
        i.spriteCellChangeSpeed = o.spriteCellChangeSpeed,
        i.spriteCellWidth = o.spriteCellWidth,
        i.spriteCellHeight = o.spriteCellHeight,
        i.spriteRandomStartCell = o.spriteRandomStartCell,
        i.isAnimationSheetEnabled = o.isAnimationSheetEnabled;
        var _ = o.getColorGradients();
        if (_) {
            i.colorGradients = [];
            for (var b = 0, k = _; b < k.length; b++) {
                var j = k[b]
                  , $ = {
                    gradient: j.gradient,
                    color1: j.color1.asArray()
                };
                j.color2 ? $.color2 = j.color2.asArray() : $.color2 = j.color1.asArray(),
                i.colorGradients.push($)
            }
        }
        var _e = o.getRampGradients();
        if (_e) {
            i.rampGradients = [];
            for (var et = 0, tt = _e; et < tt.length; et++) {
                var rt = tt[et]
                  , $ = {
                    gradient: rt.gradient,
                    color: rt.color.asArray()
                };
                i.rampGradients.push($)
            }
            i.useRampGradients = o.useRampGradients
        }
        var it = o.getColorRemapGradients();
        if (it) {
            i.colorRemapGradients = [];
            for (var nt = 0, ot = it; nt < ot.length; nt++) {
                var at = ot[nt]
                  , $ = {
                    gradient: at.gradient,
                    factor1: at.factor1
                };
                at.factor2 !== void 0 ? $.factor2 = at.factor2 : $.factor2 = at.factor1,
                i.colorRemapGradients.push($)
            }
        }
        var st = o.getAlphaRemapGradients();
        if (st) {
            i.alphaRemapGradients = [];
            for (var ut = 0, ct = st; ut < ct.length; ut++) {
                var lt = ct[ut]
                  , $ = {
                    gradient: lt.gradient,
                    factor1: lt.factor1
                };
                lt.factor2 !== void 0 ? $.factor2 = lt.factor2 : $.factor2 = lt.factor1,
                i.alphaRemapGradients.push($)
            }
        }
        var ft = o.getSizeGradients();
        if (ft) {
            i.sizeGradients = [];
            for (var ht = 0, pt = ft; ht < pt.length; ht++) {
                var dt = pt[ht]
                  , $ = {
                    gradient: dt.gradient,
                    factor1: dt.factor1
                };
                dt.factor2 !== void 0 ? $.factor2 = dt.factor2 : $.factor2 = dt.factor1,
                i.sizeGradients.push($)
            }
        }
        var _t = o.getAngularSpeedGradients();
        if (_t) {
            i.angularSpeedGradients = [];
            for (var mt = 0, vt = _t; mt < vt.length; mt++) {
                var yt = vt[mt]
                  , $ = {
                    gradient: yt.gradient,
                    factor1: yt.factor1
                };
                yt.factor2 !== void 0 ? $.factor2 = yt.factor2 : $.factor2 = yt.factor1,
                i.angularSpeedGradients.push($)
            }
        }
        var Et = o.getVelocityGradients();
        if (Et) {
            i.velocityGradients = [];
            for (var At = 0, gt = Et; At < gt.length; At++) {
                var St = gt[At]
                  , $ = {
                    gradient: St.gradient,
                    factor1: St.factor1
                };
                St.factor2 !== void 0 ? $.factor2 = St.factor2 : $.factor2 = St.factor1,
                i.velocityGradients.push($)
            }
        }
        var xt = o.getDragGradients();
        if (xt) {
            i.dragGradients = [];
            for (var bt = 0, Rt = xt; bt < Rt.length; bt++) {
                var Mt = Rt[bt]
                  , $ = {
                    gradient: Mt.gradient,
                    factor1: Mt.factor1
                };
                Mt.factor2 !== void 0 ? $.factor2 = Mt.factor2 : $.factor2 = Mt.factor1,
                i.dragGradients.push($)
            }
        }
        var Pt = o.getEmitRateGradients();
        if (Pt) {
            i.emitRateGradients = [];
            for (var It = 0, Dt = Pt; It < Dt.length; It++) {
                var Ct = Dt[It]
                  , $ = {
                    gradient: Ct.gradient,
                    factor1: Ct.factor1
                };
                Ct.factor2 !== void 0 ? $.factor2 = Ct.factor2 : $.factor2 = Ct.factor1,
                i.emitRateGradients.push($)
            }
        }
        var Ot = o.getStartSizeGradients();
        if (Ot) {
            i.startSizeGradients = [];
            for (var wt = 0, Nt = Ot; wt < Nt.length; wt++) {
                var Ft = Nt[wt]
                  , $ = {
                    gradient: Ft.gradient,
                    factor1: Ft.factor1
                };
                Ft.factor2 !== void 0 ? $.factor2 = Ft.factor2 : $.factor2 = Ft.factor1,
                i.startSizeGradients.push($)
            }
        }
        var Vt = o.getLifeTimeGradients();
        if (Vt) {
            i.lifeTimeGradients = [];
            for (var Lt = 0, kt = Vt; Lt < kt.length; Lt++) {
                var Bt = kt[Lt]
                  , $ = {
                    gradient: Bt.gradient,
                    factor1: Bt.factor1
                };
                Bt.factor2 !== void 0 ? $.factor2 = Bt.factor2 : $.factor2 = Bt.factor1,
                i.lifeTimeGradients.push($)
            }
        }
        var Ut = o.getLimitVelocityGradients();
        if (Ut) {
            i.limitVelocityGradients = [];
            for (var Gt = 0, Ht = Ut; Gt < Ht.length; Gt++) {
                var zt = Ht[Gt]
                  , $ = {
                    gradient: zt.gradient,
                    factor1: zt.factor1
                };
                zt.factor2 !== void 0 ? $.factor2 = zt.factor2 : $.factor2 = zt.factor1,
                i.limitVelocityGradients.push($)
            }
            i.limitVelocityDamping = o.limitVelocityDamping
        }
        o.noiseTexture && (i.noiseTexture = o.noiseTexture.serialize())
    }
    ,
    e._Parse = function(i, o, s, c) {
        var d, _, b, k;
        s instanceof ThinEngine ? k = null : k = s;
        var j = GetClass("BABYLON.Texture");
        if (j && k && (i.texture ? o.particleTexture = j.Parse(i.texture, k, c) : i.textureName && (o.particleTexture = new j(c + i.textureName,k,!1,i.invertY !== void 0 ? i.invertY : !0),
        o.particleTexture.name = i.textureName)),
        !i.emitterId && i.emitterId !== 0 && i.emitter === void 0 ? o.emitter = Vector3.Zero() : i.emitterId && k ? o.emitter = k.getLastMeshById(i.emitterId) : o.emitter = Vector3.FromArray(i.emitter),
        o.isLocal = !!i.isLocal,
        i.renderingGroupId !== void 0 && (o.renderingGroupId = i.renderingGroupId),
        i.isBillboardBased !== void 0 && (o.isBillboardBased = i.isBillboardBased),
        i.billboardMode !== void 0 && (o.billboardMode = i.billboardMode),
        i.animations) {
            for (var $ = 0; $ < i.animations.length; $++) {
                var _e = i.animations[$]
                  , et = GetClass("BABYLON.Animation");
                et && o.animations.push(et.Parse(_e))
            }
            o.beginAnimationOnStart = i.beginAnimationOnStart,
            o.beginAnimationFrom = i.beginAnimationFrom,
            o.beginAnimationTo = i.beginAnimationTo,
            o.beginAnimationLoop = i.beginAnimationLoop
        }
        if (i.autoAnimate && k && k.beginAnimation(o, i.autoAnimateFrom, i.autoAnimateTo, i.autoAnimateLoop, i.autoAnimateSpeed || 1),
        o.startDelay = i.startDelay | 0,
        o.minAngularSpeed = i.minAngularSpeed,
        o.maxAngularSpeed = i.maxAngularSpeed,
        o.minSize = i.minSize,
        o.maxSize = i.maxSize,
        i.minScaleX && (o.minScaleX = i.minScaleX,
        o.maxScaleX = i.maxScaleX,
        o.minScaleY = i.minScaleY,
        o.maxScaleY = i.maxScaleY),
        i.preWarmCycles !== void 0 && (o.preWarmCycles = i.preWarmCycles,
        o.preWarmStepOffset = i.preWarmStepOffset),
        i.minInitialRotation !== void 0 && (o.minInitialRotation = i.minInitialRotation,
        o.maxInitialRotation = i.maxInitialRotation),
        o.minLifeTime = i.minLifeTime,
        o.maxLifeTime = i.maxLifeTime,
        o.minEmitPower = i.minEmitPower,
        o.maxEmitPower = i.maxEmitPower,
        o.emitRate = i.emitRate,
        o.gravity = Vector3.FromArray(i.gravity),
        i.noiseStrength && (o.noiseStrength = Vector3.FromArray(i.noiseStrength)),
        o.color1 = Color4.FromArray(i.color1),
        o.color2 = Color4.FromArray(i.color2),
        o.colorDead = Color4.FromArray(i.colorDead),
        o.updateSpeed = i.updateSpeed,
        o.targetStopDuration = i.targetStopDuration,
        o.blendMode = i.blendMode,
        i.colorGradients)
            for (var tt = 0, rt = i.colorGradients; tt < rt.length; tt++) {
                var it = rt[tt];
                o.addColorGradient(it.gradient, Color4.FromArray(it.color1), it.color2 ? Color4.FromArray(it.color2) : void 0)
            }
        if (i.rampGradients) {
            for (var nt = 0, ot = i.rampGradients; nt < ot.length; nt++) {
                var at = ot[nt];
                o.addRampGradient(at.gradient, Color3.FromArray(at.color))
            }
            o.useRampGradients = i.useRampGradients
        }
        if (i.colorRemapGradients)
            for (var st = 0, ut = i.colorRemapGradients; st < ut.length; st++) {
                var ct = ut[st];
                o.addColorRemapGradient(ct.gradient, ct.factor1 !== void 0 ? ct.factor1 : ct.factor, ct.factor2)
            }
        if (i.alphaRemapGradients)
            for (var lt = 0, ft = i.alphaRemapGradients; lt < ft.length; lt++) {
                var ht = ft[lt];
                o.addAlphaRemapGradient(ht.gradient, ht.factor1 !== void 0 ? ht.factor1 : ht.factor, ht.factor2)
            }
        if (i.sizeGradients)
            for (var pt = 0, dt = i.sizeGradients; pt < dt.length; pt++) {
                var _t = dt[pt];
                o.addSizeGradient(_t.gradient, _t.factor1 !== void 0 ? _t.factor1 : _t.factor, _t.factor2)
            }
        if (i.angularSpeedGradients)
            for (var mt = 0, vt = i.angularSpeedGradients; mt < vt.length; mt++) {
                var yt = vt[mt];
                o.addAngularSpeedGradient(yt.gradient, yt.factor1 !== void 0 ? yt.factor1 : yt.factor, yt.factor2)
            }
        if (i.velocityGradients)
            for (var Et = 0, At = i.velocityGradients; Et < At.length; Et++) {
                var gt = At[Et];
                o.addVelocityGradient(gt.gradient, gt.factor1 !== void 0 ? gt.factor1 : gt.factor, gt.factor2)
            }
        if (i.dragGradients)
            for (var St = 0, xt = i.dragGradients; St < xt.length; St++) {
                var bt = xt[St];
                o.addDragGradient(bt.gradient, bt.factor1 !== void 0 ? bt.factor1 : bt.factor, bt.factor2)
            }
        if (i.emitRateGradients)
            for (var Rt = 0, Mt = i.emitRateGradients; Rt < Mt.length; Rt++) {
                var Pt = Mt[Rt];
                o.addEmitRateGradient(Pt.gradient, Pt.factor1 !== void 0 ? Pt.factor1 : Pt.factor, Pt.factor2)
            }
        if (i.startSizeGradients)
            for (var It = 0, Dt = i.startSizeGradients; It < Dt.length; It++) {
                var Ct = Dt[It];
                o.addStartSizeGradient(Ct.gradient, Ct.factor1 !== void 0 ? Ct.factor1 : Ct.factor, Ct.factor2)
            }
        if (i.lifeTimeGradients)
            for (var Ot = 0, wt = i.lifeTimeGradients; Ot < wt.length; Ot++) {
                var Nt = wt[Ot];
                o.addLifeTimeGradient(Nt.gradient, Nt.factor1 !== void 0 ? Nt.factor1 : Nt.factor, Nt.factor2)
            }
        if (i.limitVelocityGradients) {
            for (var Ft = 0, Vt = i.limitVelocityGradients; Ft < Vt.length; Ft++) {
                var Lt = Vt[Ft];
                o.addLimitVelocityGradient(Lt.gradient, Lt.factor1 !== void 0 ? Lt.factor1 : Lt.factor, Lt.factor2)
            }
            o.limitVelocityDamping = i.limitVelocityDamping
        }
        if (i.noiseTexture && k) {
            var kt = GetClass("BABYLON.ProceduralTexture");
            o.noiseTexture = kt.Parse(i.noiseTexture, k, c)
        }
        var Bt;
        if (i.particleEmitterType) {
            switch (i.particleEmitterType.type) {
            case "SphereParticleEmitter":
                Bt = new SphereParticleEmitter;
                break;
            case "SphereDirectedParticleEmitter":
                Bt = new SphereDirectedParticleEmitter;
                break;
            case "ConeEmitter":
            case "ConeParticleEmitter":
                Bt = new ConeParticleEmitter;
                break;
            case "CylinderParticleEmitter":
                Bt = new CylinderParticleEmitter;
                break;
            case "CylinderDirectedParticleEmitter":
                Bt = new CylinderDirectedParticleEmitter;
                break;
            case "HemisphericParticleEmitter":
                Bt = new HemisphericParticleEmitter;
                break;
            case "PointParticleEmitter":
                Bt = new PointParticleEmitter;
                break;
            case "MeshParticleEmitter":
                Bt = new MeshParticleEmitter;
                break;
            case "BoxEmitter":
            case "BoxParticleEmitter":
            default:
                Bt = new BoxParticleEmitter;
                break
            }
            Bt.parse(i.particleEmitterType, k)
        } else
            Bt = new BoxParticleEmitter,
            Bt.parse(i, k);
        o.particleEmitterType = Bt,
        o.startSpriteCellID = i.startSpriteCellID,
        o.endSpriteCellID = i.endSpriteCellID,
        o.spriteCellLoop = (d = i.spriteCellLoop) !== null && d !== void 0 ? d : !0,
        o.spriteCellWidth = i.spriteCellWidth,
        o.spriteCellHeight = i.spriteCellHeight,
        o.spriteCellChangeSpeed = i.spriteCellChangeSpeed,
        o.spriteRandomStartCell = i.spriteRandomStartCell,
        o.disposeOnStop = (_ = i.disposeOnStop) !== null && _ !== void 0 ? _ : !1,
        o.manualEmitCount = (b = i.manualEmitCount) !== null && b !== void 0 ? b : -1
    }
    ,
    e.Parse = function(i, o, s, c, d) {
        c === void 0 && (c = !1);
        var _ = i.name, b = null, k = null, j, $;
        if (o instanceof ThinEngine ? j = o : ($ = o,
        j = $.getEngine()),
        i.customShader && j.createEffectForParticles) {
            k = i.customShader;
            var _e = k.shaderOptions.defines.length > 0 ? k.shaderOptions.defines.join(`
`) : "";
            b = j.createEffectForParticles(k.shaderPath.fragmentElement, k.shaderOptions.uniforms, k.shaderOptions.samplers, _e)
        }
        var et = new e(_,d || i.capacity,o,b,i.isAnimationSheetEnabled);
        if (et.customShader = k,
        et._rootUrl = s,
        i.id && (et.id = i.id),
        i.subEmitters) {
            et.subEmitters = [];
            for (var tt = 0, rt = i.subEmitters; tt < rt.length; tt++) {
                for (var it = rt[tt], nt = [], ot = 0, at = it; ot < at.length; ot++) {
                    var st = at[ot];
                    nt.push(SubEmitter.Parse(st, o, s))
                }
                et.subEmitters.push(nt)
            }
        }
        return e._Parse(i, et, o, s),
        i.textureMask && (et.textureMask = Color4.FromArray(i.textureMask)),
        i.preventAutoStart && (et.preventAutoStart = i.preventAutoStart),
        !c && !et.preventAutoStart && et.start(),
        et
    }
    ,
    e.BILLBOARDMODE_Y = 2,
    e.BILLBOARDMODE_ALL = 7,
    e.BILLBOARDMODE_STRETCHED = 8,
    e
}(BaseParticleSystem);
SubEmitter._ParseParticleSystem = ParticleSystem.Parse;
var name$1k = "clipPlaneFragmentDeclaration2"
  , shader$1k = `#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$1k] = shader$1k;
var name$1j = "gpuRenderParticlesPixelShader"
  , shader$1j = `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$1j] = shader$1j;
var name$1i = "clipPlaneVertexDeclaration2"
  , shader$1i = `#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$1i] = shader$1i;
var name$1h = "gpuRenderParticlesVertexShader"
  , shader$1h = `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$1h] = shader$1h;
var GPUParticleSystem = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        c === void 0 && (c = null),
        d === void 0 && (d = !1);
        var _ = a.call(this, i) || this;
        if (_.layerMask = 268435455,
        _._accumulatedCount = 0,
        _._targetIndex = 0,
        _._currentRenderId = -1,
        _._currentRenderingCameraUniqueId = -1,
        _._started = !1,
        _._stopped = !1,
        _._timeDelta = 0,
        _._actualFrame = 0,
        _._rawTextureWidth = 256,
        _.onDisposeObservable = new Observable,
        _.onStoppedObservable = new Observable,
        _.forceDepthWrite = !1,
        _._preWarmDone = !1,
        _.isLocal = !1,
        _._onBeforeDrawParticlesObservable = null,
        !s || s.getClassName() === "Scene" ? (_._scene = s || EngineStore.LastCreatedScene,
        _._engine = _._scene.getEngine(),
        _.uniqueId = _._scene.getUniqueId(),
        _._scene.particleSystems.push(_)) : (_._engine = s,
        _.defaultProjectionMatrix = Matrix.PerspectiveFovLH(.8, 1, .1, 100, _._engine.isNDCHalfZRange)),
        _._engine.getCaps().supportComputeShaders) {
            if (!GetClass("BABYLON.ComputeShaderParticleSystem"))
                throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");
            _._platform = new (GetClass("BABYLON.ComputeShaderParticleSystem"))(_,_._engine)
        } else {
            if (!GetClass("BABYLON.WebGL2ParticleSystem"))
                throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");
            _._platform = new (GetClass("BABYLON.WebGL2ParticleSystem"))(_,_._engine)
        }
        _._customWrappers = {
            0: new DrawWrapper(_._engine)
        },
        _._customWrappers[0].effect = c,
        _._drawWrappers = {
            0: new DrawWrapper(_._engine)
        },
        _._drawWrappers[0].drawContext && (_._drawWrappers[0].drawContext.useInstancing = !0),
        _._attachImageProcessingConfiguration(null),
        o = o != null ? o : {},
        o.randomTextureSize || delete o.randomTextureSize;
        var b = __assign({
            capacity: 5e4,
            randomTextureSize: _._engine.getCaps().maxTextureSize
        }, o)
          , k = o;
        isFinite(k) && (b.capacity = k),
        _._capacity = b.capacity,
        _._activeCount = b.capacity,
        _._currentActiveCount = 0,
        _._isAnimationSheetEnabled = d,
        _.particleEmitterType = new BoxParticleEmitter;
        for (var j = Math.min(_._engine.getCaps().maxTextureSize, b.randomTextureSize), $ = [], _e = 0; _e < j; ++_e)
            $.push(Math.random()),
            $.push(Math.random()),
            $.push(Math.random()),
            $.push(Math.random());
        _._randomTexture = new RawTexture(new Float32Array($),j,1,5,s,!1,!1,1,1),
        _._randomTexture.name = "GPUParticleSystem_random1",
        _._randomTexture.wrapU = 1,
        _._randomTexture.wrapV = 1,
        $ = [];
        for (var _e = 0; _e < j; ++_e)
            $.push(Math.random()),
            $.push(Math.random()),
            $.push(Math.random()),
            $.push(Math.random());
        return _._randomTexture2 = new RawTexture(new Float32Array($),j,1,5,s,!1,!1,1,1),
        _._randomTexture2.name = "GPUParticleSystem_random2",
        _._randomTexture2.wrapU = 1,
        _._randomTexture2.wrapV = 1,
        _._randomTextureSize = j,
        _
    }
    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(i) {
            this._activeCount = Math.min(i, 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(i) {
        var o = this;
        if (i === void 0 && (i = this.startDelay),
        !this.targetStopDuration && this._hasTargetStopDurationDependantGradient())
            throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
        if (i) {
            setTimeout(function() {
                o.start(0)
            }, i);
            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(i) {
        var o, s;
        return i === void 0 && (i = 0),
        (s = (o = this._customWrappers[i]) === null || o === void 0 ? void 0 : o.effect) !== null && s !== void 0 ? s : this._customWrappers[0].effect
    }
    ,
    e.prototype._getCustomDrawWrapper = function(i) {
        var o;
        return i === void 0 && (i = 0),
        (o = this._customWrappers[i]) !== null && o !== void 0 ? o : this._customWrappers[0]
    }
    ,
    e.prototype.setCustomEffect = function(i, o) {
        o === void 0 && (o = 0),
        this._customWrappers[o] = new DrawWrapper(this._engine),
        this._customWrappers[o].effect = i
    }
    ,
    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(i, o, s) {
        return a.prototype._removeGradientAndTexture.call(this, i, o, s),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.addColorGradient = function(i, o, s) {
        this._colorGradients || (this._colorGradients = []);
        var c = new ColorGradient(i,o);
        return this._colorGradients.push(c),
        this._refreshColorGradient(!0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype._refreshColorGradient = function(i) {
        i === void 0 && (i = !1),
        this._colorGradients && (i && this._colorGradients.sort(function(o, s) {
            return o.gradient < s.gradient ? -1 : o.gradient > s.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(i) {
        return this._removeGradientAndTexture(i, this._colorGradients, this._colorGradientsTexture),
        this._colorGradientsTexture = null,
        this
    }
    ,
    e.prototype.resetDrawCache = function() {
        var i;
        for (var o in this._drawWrappers) {
            var s = this._drawWrappers[o];
            (i = s.drawContext) === null || i === void 0 || i.reset()
        }
    }
    ,
    e.prototype._addFactorGradient = function(i, o, s) {
        var c = new FactorGradient(o,s);
        i.push(c),
        this._releaseBuffers()
    }
    ,
    e.prototype.addSizeGradient = function(i, o) {
        return this._sizeGradients || (this._sizeGradients = []),
        this._addFactorGradient(this._sizeGradients, i, o),
        this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeSizeGradient = function(i) {
        return this._removeGradientAndTexture(i, this._sizeGradients, this._sizeGradientsTexture),
        this._sizeGradientsTexture = null,
        this
    }
    ,
    e.prototype._refreshFactorGradient = function(i, o, s) {
        if (s === void 0 && (s = !1),
        !!i) {
            s && i.sort(function(d, _) {
                return d.gradient < _.gradient ? -1 : d.gradient > _.gradient ? 1 : 0
            });
            var c = this;
            c[o] && (c[o].dispose(),
            c[o] = null)
        }
    }
    ,
    e.prototype.addAngularSpeedGradient = function(i, o) {
        return this._angularSpeedGradients || (this._angularSpeedGradients = []),
        this._addFactorGradient(this._angularSpeedGradients, i, o),
        this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeAngularSpeedGradient = function(i) {
        return this._removeGradientAndTexture(i, this._angularSpeedGradients, this._angularSpeedGradientsTexture),
        this._angularSpeedGradientsTexture = null,
        this
    }
    ,
    e.prototype.addVelocityGradient = function(i, o) {
        return this._velocityGradients || (this._velocityGradients = []),
        this._addFactorGradient(this._velocityGradients, i, o),
        this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeVelocityGradient = function(i) {
        return this._removeGradientAndTexture(i, this._velocityGradients, this._velocityGradientsTexture),
        this._velocityGradientsTexture = null,
        this
    }
    ,
    e.prototype.addLimitVelocityGradient = function(i, o) {
        return this._limitVelocityGradients || (this._limitVelocityGradients = []),
        this._addFactorGradient(this._limitVelocityGradients, i, o),
        this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeLimitVelocityGradient = function(i) {
        return this._removeGradientAndTexture(i, this._limitVelocityGradients, this._limitVelocityGradientsTexture),
        this._limitVelocityGradientsTexture = null,
        this
    }
    ,
    e.prototype.addDragGradient = function(i, o) {
        return this._dragGradients || (this._dragGradients = []),
        this._addFactorGradient(this._dragGradients, i, o),
        this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeDragGradient = function(i) {
        return this._removeGradientAndTexture(i, this._dragGradients, this._dragGradientsTexture),
        this._dragGradientsTexture = null,
        this
    }
    ,
    e.prototype.addEmitRateGradient = function(i, o, s) {
        return this
    }
    ,
    e.prototype.removeEmitRateGradient = function(i) {
        return this
    }
    ,
    e.prototype.addStartSizeGradient = function(i, o, s) {
        return this
    }
    ,
    e.prototype.removeStartSizeGradient = function(i) {
        return this
    }
    ,
    e.prototype.addColorRemapGradient = function(i, o, s) {
        return this
    }
    ,
    e.prototype.removeColorRemapGradient = function() {
        return this
    }
    ,
    e.prototype.addAlphaRemapGradient = function(i, o, s) {
        return this
    }
    ,
    e.prototype.removeAlphaRemapGradient = function() {
        return this
    }
    ,
    e.prototype.addRampGradient = function(i, o) {
        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(i) {},
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addLifeTimeGradient = function(i, o, s) {
        return this
    }
    ,
    e.prototype.removeLifeTimeGradient = function(i) {
        return this
    }
    ,
    e.prototype._reset = function() {
        this._releaseBuffers()
    }
    ,
    e.prototype._createVertexBuffers = function(i, o, s) {
        var c = {};
        c.position = o.createVertexBuffer("position", 0, 3, this._attributesStrideSize, !0);
        var d = 3;
        c.age = o.createVertexBuffer("age", d, 1, this._attributesStrideSize, !0),
        d += 1,
        c.size = o.createVertexBuffer("size", d, 3, this._attributesStrideSize, !0),
        d += 3,
        c.life = o.createVertexBuffer("life", d, 1, this._attributesStrideSize, !0),
        d += 1,
        d += 4,
        this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED && (c.direction = o.createVertexBuffer("direction", d, 3, this._attributesStrideSize, !0)),
        d += 3,
        this._platform.alignDataInBuffer && (d += 1),
        this.particleEmitterType instanceof CustomParticleEmitter && (d += 3,
        this._platform.alignDataInBuffer && (d += 1)),
        this._colorGradientsTexture || (c.color = o.createVertexBuffer("color", d, 4, this._attributesStrideSize, !0),
        d += 4),
        this._isBillboardBased || (c.initialDirection = o.createVertexBuffer("initialDirection", d, 3, this._attributesStrideSize, !0),
        d += 3,
        this._platform.alignDataInBuffer && (d += 1)),
        this.noiseTexture && (c.noiseCoordinates1 = o.createVertexBuffer("noiseCoordinates1", d, 3, this._attributesStrideSize, !0),
        d += 3,
        this._platform.alignDataInBuffer && (d += 1),
        c.noiseCoordinates2 = o.createVertexBuffer("noiseCoordinates2", d, 3, this._attributesStrideSize, !0),
        d += 3,
        this._platform.alignDataInBuffer && (d += 1)),
        c.angle = o.createVertexBuffer("angle", d, 1, this._attributesStrideSize, !0),
        this._angularSpeedGradientsTexture ? d++ : d += 2,
        this._isAnimationSheetEnabled && (c.cellIndex = o.createVertexBuffer("cellIndex", d, 1, this._attributesStrideSize, !0),
        d += 1,
        this.spriteRandomStartCell && (c.cellStartOffset = o.createVertexBuffer("cellStartOffset", d, 1, this._attributesStrideSize, !0),
        d += 1)),
        c.offset = s.createVertexBuffer("offset", 0, 2),
        c.uv = s.createVertexBuffer("uv", 2, 2),
        this._platform.createVertexBuffers(i, c),
        this.resetDrawCache()
    }
    ,
    e.prototype._initialize = function(i) {
        if (i === void 0 && (i = !1),
        !(this._buffer0 && !i)) {
            var o = this._engine
              , s = 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 c = this.particleEmitterType instanceof CustomParticleEmitter, d = TmpVectors.Vector3[0], _ = 0, b = 0; b < this._capacity; b++)
                if (s.push(0),
                s.push(0),
                s.push(0),
                s.push(0),
                s.push(0),
                s.push(0),
                s.push(0),
                s.push(0),
                s.push(Math.random()),
                s.push(Math.random()),
                s.push(Math.random()),
                s.push(Math.random()),
                c ? (this.particleEmitterType.particleDestinationGenerator(b, null, d),
                s.push(d.x),
                s.push(d.y),
                s.push(d.z)) : (s.push(0),
                s.push(0),
                s.push(0)),
                this._platform.alignDataInBuffer && s.push(0),
                _ += 16,
                c && (this.particleEmitterType.particlePositionGenerator(b, null, d),
                s.push(d.x),
                s.push(d.y),
                s.push(d.z),
                this._platform.alignDataInBuffer && s.push(0),
                _ += 4),
                this._colorGradientsTexture || (s.push(0),
                s.push(0),
                s.push(0),
                s.push(0),
                _ += 4),
                this.isBillboardBased || (s.push(0),
                s.push(0),
                s.push(0),
                this._platform.alignDataInBuffer && s.push(0),
                _ += 4),
                this.noiseTexture && (s.push(Math.random()),
                s.push(Math.random()),
                s.push(Math.random()),
                this._platform.alignDataInBuffer && s.push(0),
                s.push(Math.random()),
                s.push(Math.random()),
                s.push(Math.random()),
                this._platform.alignDataInBuffer && s.push(0),
                _ += 8),
                s.push(0),
                _ += 1,
                this._angularSpeedGradientsTexture || (s.push(0),
                _ += 1),
                this._isAnimationSheetEnabled && (s.push(0),
                _ += 1,
                this.spriteRandomStartCell && (s.push(0),
                _ += 1)),
                this._platform.alignDataInBuffer) {
                    var k = 3 - (_ + 3 & 3);
                    for (_ += k; k-- > 0; )
                        s.push(0)
                }
            var j = new Float32Array([.5, .5, 1, 1, -.5, .5, 0, 1, .5, -.5, 1, 0, -.5, -.5, 0, 0])
              , $ = this._platform.createParticleBuffer(s)
              , _e = this._platform.createParticleBuffer(s);
            this._buffer0 = new Buffer(o,$,!1,this._attributesStrideSize),
            this._buffer1 = new Buffer(o,_e,!1,this._attributesStrideSize),
            this._spriteBuffer = new Buffer(o,j,!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 i = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
        this._isBillboardBased && (i += `
#define BILLBOARD`),
        this._colorGradientsTexture && (i += `
#define COLORGRADIENTS`),
        this._sizeGradientsTexture && (i += `
#define SIZEGRADIENTS`),
        this._angularSpeedGradientsTexture && (i += `
#define ANGULARSPEEDGRADIENTS`),
        this._velocityGradientsTexture && (i += `
#define VELOCITYGRADIENTS`),
        this._limitVelocityGradientsTexture && (i += `
#define LIMITVELOCITYGRADIENTS`),
        this._dragGradientsTexture && (i += `
#define DRAGGRADIENTS`),
        this.isAnimationSheetEnabled && (i += `
#define ANIMATESHEET`,
        this.spriteRandomStartCell && (i += `
#define ANIMATESHEETRANDOMSTART`)),
        this.noiseTexture && (i += `
#define NOISE`),
        this.isLocal && (i += `
#define LOCAL`),
        !(this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === i) && (this._cachedUpdateDefines = i,
        this._updateBuffer = this._platform.createUpdateBuffer(i))
    }
    ,
    e.prototype._getWrapper = function(i) {
        var o = this._getCustomDrawWrapper(i);
        if (o != null && o.effect)
            return o;
        var s = [];
        this.fillDefines(s, i);
        var c = this._drawWrappers[i];
        c || (c = new DrawWrapper(this._engine),
        c.drawContext && (c.drawContext.useInstancing = !0),
        this._drawWrappers[i] = c);
        var d = s.join(`
`);
        if (c.defines !== d) {
            var _ = []
              , b = []
              , k = [];
            this.fillUniformsAttributesAndSamplerNames(b, _, k),
            c.setEffect(this._engine.createEffect("gpuRenderParticles", _, b, k, d), d)
        }
        return c
    }
    ,
    e._GetAttributeNamesOrOptions = function(i, o, s, c) {
        i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        s === void 0 && (s = !1),
        c === void 0 && (c = !1);
        var d = [VertexBuffer.PositionKind, "age", "life", "size", "angle"];
        return i || d.push(VertexBuffer.ColorKind),
        o && d.push("cellIndex"),
        s || d.push("initialDirection"),
        c || d.push("direction"),
        d.push("offset", VertexBuffer.UVKind),
        d
    }
    ,
    e._GetEffectCreationOptions = function(i) {
        i === void 0 && (i = !1);
        var o = ["emitterWM", "worldOffset", "view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "translationPivot", "eyePosition"];
        return i && o.push("sheetInfos"),
        o
    }
    ,
    e.prototype.fillDefines = function(i, o) {
        if (o === void 0 && (o = 0),
        this._scene && (this._scene.clipPlane && i.push("#define CLIPPLANE"),
        this._scene.clipPlane2 && i.push("#define CLIPPLANE2"),
        this._scene.clipPlane3 && i.push("#define CLIPPLANE3"),
        this._scene.clipPlane4 && i.push("#define CLIPPLANE4"),
        this._scene.clipPlane5 && i.push("#define CLIPPLANE5"),
        this._scene.clipPlane6 && i.push("#define CLIPPLANE6")),
        o === ParticleSystem.BLENDMODE_MULTIPLY && i.push("#define BLENDMULTIPLYMODE"),
        this.isLocal && i.push("#define LOCAL"),
        this._isBillboardBased)
            switch (i.push("#define BILLBOARD"),
            this.billboardMode) {
            case ParticleSystem.BILLBOARDMODE_Y:
                i.push("#define BILLBOARDY");
                break;
            case ParticleSystem.BILLBOARDMODE_STRETCHED:
                i.push("#define BILLBOARDSTRETCHED");
                break;
            case ParticleSystem.BILLBOARDMODE_ALL:
                i.push("#define BILLBOARDMODE_ALL");
                break
            }
        this._colorGradientsTexture && i.push("#define COLORGRADIENTS"),
        this.isAnimationSheetEnabled && i.push("#define ANIMATESHEET"),
        this._imageProcessingConfiguration && (this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),
        i.push("" + this._imageProcessingConfigurationDefines.toString()))
    }
    ,
    e.prototype.fillUniformsAttributesAndSamplerNames = function(i, o, s) {
        o.push.apply(o, e._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED)),
        i.push.apply(i, e._GetEffectCreationOptions(this._isAnimationSheetEnabled)),
        s.push("diffuseSampler", "colorGradientSampler"),
        this._imageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms(i, this._imageProcessingConfigurationDefines),
        ImageProcessingConfiguration.PrepareSamplers(s, this._imageProcessingConfigurationDefines))
    }
    ,
    e.prototype.animate = function(i) {
        var o;
        i === void 0 && (i = !1),
        this._timeDelta = this.updateSpeed * (i ? this.preWarmStepOffset : ((o = this._scene) === null || o === void 0 ? void 0 : o.getAnimationRatio()) || 1),
        this._actualFrame += this._timeDelta,
        this._stopped || this.targetStopDuration && this._actualFrame >= this.targetStopDuration && this.stop()
    }
    ,
    e.prototype._createFactorGradientTexture = function(i, o) {
        var s = this[o];
        if (!(!i || !i.length || s)) {
            for (var c = new Float32Array(this._rawTextureWidth), d = 0; d < this._rawTextureWidth; d++) {
                var _ = d / this._rawTextureWidth;
                GradientHelper.GetCurrentGradient(_, i, function(b, k, j) {
                    c[d] = Scalar.Lerp(b.factor1, k.factor1, j)
                })
            }
            this[o] = RawTexture.CreateRTexture(c, 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 i = new Uint8Array(this._rawTextureWidth * 4), o = TmpColors.Color4[0], s = 0; s < this._rawTextureWidth; s++) {
                var c = s / this._rawTextureWidth;
                GradientHelper.GetCurrentGradient(c, this._colorGradients, function(d, _, b) {
                    Color4.LerpToRef(d.color1, _.color1, b, o),
                    i[s * 4] = o.r * 255,
                    i[s * 4 + 1] = o.g * 255,
                    i[s * 4 + 2] = o.b * 255,
                    i[s * 4 + 3] = o.a * 255
                })
            }
            this._colorGradientsTexture = RawTexture.CreateRGBATexture(i, this._rawTextureWidth, 1, this._scene, !1, !1, 1)
        }
    }
    ,
    e.prototype._render = function(i, o) {
        var s, c, d = this._getWrapper(i), _ = d.effect;
        this._engine.enableEffect(d);
        var b = ((s = this._scene) === null || s === void 0 ? void 0 : s.getViewMatrix()) || Matrix.IdentityReadOnly;
        if (_.setMatrix("view", b),
        _.setMatrix("projection", (c = this.defaultProjectionMatrix) !== null && c !== void 0 ? c : this._scene.getProjectionMatrix()),
        _.setTexture("diffuseSampler", this.particleTexture),
        _.setVector2("translationPivot", this.translationPivot),
        _.setVector3("worldOffset", this.worldOffset),
        this.isLocal && _.setMatrix("emitterWM", o),
        this._colorGradientsTexture ? _.setTexture("colorGradientSampler", this._colorGradientsTexture) : _.setDirectColor4("colorDead", this.colorDead),
        this._isAnimationSheetEnabled && this.particleTexture) {
            var k = this.particleTexture.getBaseSize();
            _.setFloat3("sheetInfos", this.spriteCellWidth / k.width, this.spriteCellHeight / k.height, k.width / this.spriteCellWidth)
        }
        if (this._isBillboardBased && this._scene) {
            var j = this._scene.activeCamera;
            _.setVector3("eyePosition", j.globalPosition)
        }
        var $ = _.defines;
        if (this._scene && (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4 || this._scene.clipPlane5 || this._scene.clipPlane6) && MaterialHelper.BindClipPlane(_, this._scene),
        $.indexOf("#define BILLBOARDMODE_ALL") >= 0) {
            var _e = b.clone();
            _e.invert(),
            _.setMatrix("invView", _e)
        }
        switch (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess && this._imageProcessingConfiguration.bind(_),
        i) {
        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, _),
        this._onBeforeDrawParticlesObservable && this._onBeforeDrawParticlesObservable.notifyObservers(_),
        this._engine.drawArraysType(7, 0, 4, this._currentActiveCount),
        this._engine.setAlphaMode(0),
        this._currentActiveCount
    }
    ,
    e.prototype.render = function(i, o) {
        if (i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        !this._started || (this._createColorGradientTexture(),
        this._createSizeGradientTexture(),
        this._createAngularSpeedGradientTexture(),
        this._createVelocityGradientTexture(),
        this._createLimitVelocityGradientTexture(),
        this._createDragGradientTexture(),
        this._recreateUpdateEffect(),
        !this.isReady()))
            return 0;
        if (!i && this._scene) {
            if (!this._preWarmDone && this.preWarmCycles) {
                for (var s = 0; s < this.preWarmCycles; s++)
                    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 c = this._accumulatedCount | 0;
            this._accumulatedCount -= c,
            this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + c)
        }
        if (!this._currentActiveCount)
            return 0;
        var d;
        if (this.emitter.position) {
            var _ = this.emitter;
            d = _.getWorldMatrix()
        } else {
            var b = this.emitter;
            d = Matrix.Translation(b.x, b.y, b.z)
        }
        var k = 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", d),
        this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount);
        var j = 0;
        !i && !o && (k.setState(!1),
        this.forceDepthWrite && k.setDepthWrite(!0),
        this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD ? j = this._render(ParticleSystem.BLENDMODE_MULTIPLY, d) + this._render(ParticleSystem.BLENDMODE_ADD, d) : j = this._render(this.blendMode, d),
        this._engine.setAlphaMode(0)),
        this._targetIndex++,
        this._targetIndex === 2 && (this._targetIndex = 0);
        var $ = this._sourceBuffer;
        return this._sourceBuffer = this._targetBuffer,
        this._targetBuffer = $,
        j
    }
    ,
    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(i) {
        i === void 0 && (i = !0);
        for (var o in this._drawWrappers) {
            var s = this._drawWrappers[o];
            s.dispose()
        }
        if (this._drawWrappers = {},
        this._scene) {
            var c = this._scene.particleSystems.indexOf(this);
            c > -1 && this._scene.particleSystems.splice(c, 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),
        i && this.particleTexture && (this.particleTexture.dispose(),
        this.particleTexture = null),
        i && this.noiseTexture && (this.noiseTexture.dispose(),
        this.noiseTexture = null),
        this.onStoppedObservable.clear(),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear()
    }
    ,
    e.prototype.clone = function(i, o) {
        var s = __assign({}, this._customWrappers)
          , c = null
          , d = this._engine;
        if (d.createEffectForParticles && this.customShader != null) {
            c = this.customShader;
            var _ = c.shaderOptions.defines.length > 0 ? c.shaderOptions.defines.join(`
`) : "";
            s[0] = d.createEffectForParticles(c.shaderPath.fragmentElement, c.shaderOptions.uniforms, c.shaderOptions.samplers, _, void 0, void 0, void 0, this)
        }
        var b = this.serialize()
          , k = e.Parse(b, this._scene || this._engine, this._rootUrl);
        return k.name = i,
        k.customShader = c,
        k._customWrappers = s,
        o === void 0 && (o = this.emitter),
        this.noiseTexture && (k.noiseTexture = this.noiseTexture.clone()),
        k.emitter = o,
        k
    }
    ,
    e.prototype.serialize = function(i) {
        i === void 0 && (i = !1);
        var o = {};
        return ParticleSystem._Serialize(o, this, i),
        o.activeParticleCount = this.activeParticleCount,
        o.randomTextureSize = this._randomTextureSize,
        o.customShader = this.customShader,
        o
    }
    ,
    e.Parse = function(i, o, s, c, d) {
        c === void 0 && (c = !1);
        var _ = i.name, b, k;
        o instanceof ThinEngine ? b = o : (k = o,
        b = k.getEngine());
        var j = new e(_,{
            capacity: d || i.capacity,
            randomTextureSize: i.randomTextureSize
        },o,null,i.isAnimationSheetEnabled);
        if (j._rootUrl = s,
        i.customShader && b.createEffectForParticles) {
            var $ = i.customShader
              , _e = $.shaderOptions.defines.length > 0 ? $.shaderOptions.defines.join(`
`) : ""
              , et = b.createEffectForParticles($.shaderPath.fragmentElement, $.shaderOptions.uniforms, $.shaderOptions.samplers, _e, void 0, void 0, void 0, j);
            j.setCustomEffect(et, 0),
            j.customShader = $
        }
        return i.id && (j.id = i.id),
        i.activeParticleCount && (j.activeParticleCount = i.activeParticleCount),
        ParticleSystem._Parse(i, j, o, s),
        i.preventAutoStart && (j.preventAutoStart = i.preventAutoStart),
        !c && !j.preventAutoStart && j.start(),
        j
    }
    ,
    e
}(BaseParticleSystem)
  , ParticleSystemSet = function() {
    function a() {
        this._emitterNodeIsOwned = !0,
        this.systems = new Array
    }
    return Object.defineProperty(a.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 i = 0, o = this.systems; i < o.length; i++) {
                var s = o[i];
                s.emitter = e
            }
            this._emitterNode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setEmitterAsSphere = function(e, i, o) {
        this._emitterNodeIsOwned && this._emitterNode && this._emitterNode.dispose && this._emitterNode.dispose(),
        this._emitterNodeIsOwned = !0,
        this._emitterCreationOptions = {
            kind: "Sphere",
            options: e,
            renderingGroupId: i
        };
        var s = CreateSphere("emitterSphere", {
            diameter: e.diameter,
            segments: e.segments
        }, o);
        s.renderingGroupId = i;
        var c = new StandardMaterial("emitterSphereMaterial",o);
        c.emissiveColor = e.color,
        s.material = c;
        for (var d = 0, _ = this.systems; d < _.length; d++) {
            var b = _[d];
            b.emitter = s
        }
        this._emitterNode = s
    }
    ,
    a.prototype.start = function(e) {
        for (var i = 0, o = this.systems; i < o.length; i++) {
            var s = o[i];
            e && (s.emitter = e),
            s.start()
        }
    }
    ,
    a.prototype.dispose = function() {
        for (var e = 0, i = this.systems; e < i.length; e++) {
            var o = i[e];
            o.dispose()
        }
        this.systems = [],
        this._emitterNode && (this._emitterNode.dispose && this._emitterNode.dispose(),
        this._emitterNode = null)
    }
    ,
    a.prototype.serialize = function(e) {
        e === void 0 && (e = !1);
        var i = {};
        i.systems = [];
        for (var o = 0, s = this.systems; o < s.length; o++) {
            var c = s[o];
            i.systems.push(c.serialize(e))
        }
        return this._emitterNode && (i.emitter = this._emitterCreationOptions),
        i
    }
    ,
    a.Parse = function(e, i, o, s) {
        o === void 0 && (o = !1);
        var c = new a
          , d = this.BaseAssetsUrl + "/textures/";
        i = i || EngineStore.LastCreatedScene;
        for (var _ = 0, b = e.systems; _ < b.length; _++) {
            var k = b[_];
            c.systems.push(o ? GPUParticleSystem.Parse(k, i, d, !0, s) : ParticleSystem.Parse(k, i, d, !0, s))
        }
        if (e.emitter) {
            var j = e.emitter.options;
            switch (e.emitter.kind) {
            case "Sphere":
                c.setEmitterAsSphere({
                    diameter: j.diameter,
                    segments: j.segments,
                    color: Color3.FromArray(j.color)
                }, e.emitter.renderingGroupId, i);
                break
            }
        }
        return c
    }
    ,
    a.BaseAssetsUrl = "https://assets.babylonjs.com/particles",
    a
}()
  , ProceduralTextureSceneComponent = function() {
    function a(e) {
        this.name = SceneComponentConstants.NAME_PROCEDURALTEXTURE,
        this.scene = e,
        this.scene.proceduralTextures = new Array
    }
    return a.prototype.register = function() {
        this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear)
    }
    ,
    a.prototype.rebuild = function() {}
    ,
    a.prototype.dispose = function() {}
    ,
    a.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 i = this.scene.proceduralTextures[e];
                i._shouldRender() && i.render()
            }
            Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0)
        }
    }
    ,
    a
}()
  , name$1g = "proceduralVertexShader"
  , shader$1g = `
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$1g] = shader$1g;
var ProceduralTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        d === void 0 && (d = null),
        _ === void 0 && (_ = !0),
        b === void 0 && (b = !1),
        k === void 0 && (k = 0);
        var j = a.call(this, null, c, !_) || this;
        j.isEnabled = !0,
        j.autoClear = !0,
        j.onGeneratedObservable = new Observable,
        j.onBeforeGenerationObservable = new Observable,
        j.nodeMaterialSource = null,
        j._textures = {},
        j._currentRefreshId = -1,
        j._frameId = -1,
        j._refreshRate = 1,
        j._vertexBuffers = {},
        j._uniforms = new Array,
        j._samplers = new Array,
        j._floats = {},
        j._ints = {},
        j._floatsArrays = {},
        j._colors3 = {},
        j._colors4 = {},
        j._vectors2 = {},
        j._vectors3 = {},
        j._matrices = {},
        j._fallbackTextureUsed = !1,
        j._cachedDefines = null,
        j._contentUpdateId = -1,
        j._rtWrapper = null,
        c = j.getScene() || EngineStore.LastCreatedScene;
        var $ = c._getComponent(SceneComponentConstants.NAME_PROCEDURALTEXTURE);
        $ || ($ = new ProceduralTextureSceneComponent(c),
        c._addComponent($)),
        c.proceduralTextures.push(j),
        j._fullEngine = c.getEngine(),
        j.name = i,
        j.isRenderTarget = !0,
        j._size = o,
        j._textureType = k,
        j._generateMipMaps = _,
        j._drawWrapper = new DrawWrapper(j._fullEngine),
        j.setFragment(s),
        j._fallbackTexture = d,
        b ? (j._rtWrapper = j._fullEngine.createRenderTargetCubeTexture(o, {
            generateMipMaps: _,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1,
            type: k
        }),
        j.setFloat("face", 0)) : j._rtWrapper = j._fullEngine.createRenderTargetTexture(o, {
            generateMipMaps: _,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1,
            type: k
        }),
        j._texture = j._rtWrapper.texture;
        var _e = [];
        return _e.push(1, 1),
        _e.push(-1, 1),
        _e.push(-1, -1),
        _e.push(1, -1),
        j._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(j._fullEngine,_e,VertexBuffer.PositionKind,!1,!1,2),
        j._createIndexBuffer(),
        j
    }
    return e.prototype.getEffect = function() {
        return this._drawWrapper.effect
    }
    ,
    e.prototype._setEffect = function(i) {
        this._drawWrapper.effect = i
    }
    ,
    e.prototype.getContent = function() {
        var i = this;
        return this._contentData && this._frameId === this._contentUpdateId ? this._contentData : (this._contentData ? this._contentData.then(function(o) {
            i._contentData = i.readPixels(0, 0, o),
            i._contentUpdateId = i._frameId
        }) : (this._contentData = this.readPixels(0, 0),
        this._contentUpdateId = this._frameId),
        this._contentData)
    }
    ,
    e.prototype._createIndexBuffer = function() {
        var i = this._fullEngine
          , o = [];
        o.push(0),
        o.push(1),
        o.push(2),
        o.push(0),
        o.push(2),
        o.push(3),
        this._indexBuffer = i.createIndexBuffer(o)
    }
    ,
    e.prototype._rebuild = function() {
        var i = this._vertexBuffers[VertexBuffer.PositionKind];
        i && i._rebuild(),
        this._createIndexBuffer(),
        this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE && (this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE)
    }
    ,
    e.prototype.reset = function() {
        var i;
        (i = this._drawWrapper.effect) === null || i === void 0 || i.dispose()
    }
    ,
    e.prototype._getDefines = function() {
        return ""
    }
    ,
    e.prototype.isReady = function() {
        var i = this, o = this._fullEngine, s;
        if (this.nodeMaterialSource)
            return this._drawWrapper.effect.isReady();
        if (!this._fragment)
            return !1;
        if (this._fallbackTextureUsed)
            return !0;
        var c = this._getDefines();
        return this._drawWrapper.effect && c === this._cachedDefines && this._drawWrapper.effect.isReady() ? !0 : (this._fragment.fragmentElement !== void 0 ? s = {
            vertex: "procedural",
            fragmentElement: this._fragment.fragmentElement
        } : s = {
            vertex: "procedural",
            fragment: this._fragment
        },
        this._cachedDefines !== c && (this._cachedDefines = c,
        this._drawWrapper.effect = o.createEffect(s, [VertexBuffer.PositionKind], this._uniforms, this._samplers, c, void 0, void 0, function() {
            var d;
            (d = i._rtWrapper) === null || d === void 0 || d.dispose(),
            i._rtWrapper = i._texture = null,
            i._fallbackTexture && (i._texture = i._fallbackTexture._texture,
            i._texture && i._texture.incrementReferences()),
            i._fallbackTextureUsed = !0
        })),
        this._drawWrapper.effect.isReady())
    }
    ,
    e.prototype.resetRefreshCounter = function() {
        this._currentRefreshId = -1
    }
    ,
    e.prototype.setFragment = function(i) {
        this._fragment = i
    }
    ,
    Object.defineProperty(e.prototype, "refreshRate", {
        get: function() {
            return this._refreshRate
        },
        set: function(i) {
            this._refreshRate = i,
            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(i, o) {
        var s;
        this._fallbackTextureUsed || ((s = this._rtWrapper) === null || s === void 0 || s.dispose(),
        this._rtWrapper = this._fullEngine.createRenderTargetTexture(i, {
            generateMipMaps: o,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1,
            type: this._textureType
        }),
        this._texture = this._rtWrapper.texture,
        this._size = i,
        this._generateMipMaps = o)
    }
    ,
    e.prototype._checkUniform = function(i) {
        this._uniforms.indexOf(i) === -1 && this._uniforms.push(i)
    }
    ,
    e.prototype.setTexture = function(i, o) {
        return this._samplers.indexOf(i) === -1 && this._samplers.push(i),
        this._textures[i] = o,
        this
    }
    ,
    e.prototype.setFloat = function(i, o) {
        return this._checkUniform(i),
        this._floats[i] = o,
        this
    }
    ,
    e.prototype.setInt = function(i, o) {
        return this._checkUniform(i),
        this._ints[i] = o,
        this
    }
    ,
    e.prototype.setFloats = function(i, o) {
        return this._checkUniform(i),
        this._floatsArrays[i] = o,
        this
    }
    ,
    e.prototype.setColor3 = function(i, o) {
        return this._checkUniform(i),
        this._colors3[i] = o,
        this
    }
    ,
    e.prototype.setColor4 = function(i, o) {
        return this._checkUniform(i),
        this._colors4[i] = o,
        this
    }
    ,
    e.prototype.setVector2 = function(i, o) {
        return this._checkUniform(i),
        this._vectors2[i] = o,
        this
    }
    ,
    e.prototype.setVector3 = function(i, o) {
        return this._checkUniform(i),
        this._vectors3[i] = o,
        this
    }
    ,
    e.prototype.setMatrix = function(i, o) {
        return this._checkUniform(i),
        this._matrices[i] = o,
        this
    }
    ,
    e.prototype.render = function(i) {
        var o, s, c = this.getScene();
        if (!!c) {
            var d = this._fullEngine;
            if (d.enableEffect(this._drawWrapper),
            this.onBeforeGenerationObservable.notifyObservers(this),
            d.setState(!1),
            !this.nodeMaterialSource) {
                for (var _ in this._textures)
                    this._drawWrapper.effect.setTexture(_, this._textures[_]);
                for (_ in this._ints)
                    this._drawWrapper.effect.setInt(_, this._ints[_]);
                for (_ in this._floats)
                    this._drawWrapper.effect.setFloat(_, this._floats[_]);
                for (_ in this._floatsArrays)
                    this._drawWrapper.effect.setArray(_, this._floatsArrays[_]);
                for (_ in this._colors3)
                    this._drawWrapper.effect.setColor3(_, this._colors3[_]);
                for (_ in this._colors4) {
                    var b = this._colors4[_];
                    this._drawWrapper.effect.setFloat4(_, b.r, b.g, b.b, b.a)
                }
                for (_ in this._vectors2)
                    this._drawWrapper.effect.setVector2(_, this._vectors2[_]);
                for (_ in this._vectors3)
                    this._drawWrapper.effect.setVector3(_, this._vectors3[_]);
                for (_ in this._matrices)
                    this._drawWrapper.effect.setMatrix(_, this._matrices[_])
            }
            if (!(!this._texture || !this._rtWrapper)) {
                if ((o = d._debugPushGroup) === null || o === void 0 || o.call(d, "procedural texture generation for " + this.name, 1),
                this.isCube)
                    for (var k = 0; k < 6; k++)
                        d.bindFramebuffer(this._rtWrapper, k, void 0, void 0, !0),
                        d.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect),
                        this._drawWrapper.effect.setFloat("face", k),
                        this.autoClear && d.clear(c.clearColor, !0, !1, !1),
                        d.drawElementsType(Material.TriangleFillMode, 0, 6);
                else
                    d.bindFramebuffer(this._rtWrapper, 0, void 0, void 0, !0),
                    d.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect),
                    this.autoClear && d.clear(c.clearColor, !0, !1, !1),
                    d.drawElementsType(Material.TriangleFillMode, 0, 6);
                d.unBindFramebuffer(this._rtWrapper, this.isCube),
                this.isCube && d.generateMipMapsForCubemap(this._texture),
                (s = d._debugPopGroup) === null || s === void 0 || s.call(d, 1),
                this.onGenerated && this.onGenerated(),
                this.onGeneratedObservable.notifyObservers(this)
            }
        }
    }
    ,
    e.prototype.clone = function() {
        var i = this.getSize()
          , o = new e(this.name,i.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);
        return o.hasAlpha = this.hasAlpha,
        o.level = this.level,
        o.coordinatesMode = this.coordinatesMode,
        o
    }
    ,
    e.prototype.dispose = function() {
        var i = this.getScene();
        if (!!i) {
            var o = i.proceduralTextures.indexOf(this);
            o >= 0 && i.proceduralTextures.splice(o, 1);
            var s = this._vertexBuffers[VertexBuffer.PositionKind];
            s && (s.dispose(),
            this._vertexBuffers[VertexBuffer.PositionKind] = null),
            this._indexBuffer && this._fullEngine._releaseBuffer(this._indexBuffer) && (this._indexBuffer = null),
            this.onGeneratedObservable.clear(),
            this.onBeforeGenerationObservable.clear(),
            a.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$1f = "noisePixelShader"
  , shader$1f = `

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$1f] = shader$1f;
var NoiseProceduralTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        o === void 0 && (o = 256),
        s === void 0 && (s = EngineStore.LastCreatedScene);
        var _ = a.call(this, i, o, "noise", s, c, d) || this;
        return _.time = 0,
        _.brightness = .2,
        _.octaves = 3,
        _.persistence = .8,
        _.animationSpeedFactor = 1,
        _.autoClear = !1,
        _._updateShaderUniforms(),
        _
    }
    return e.prototype._updateShaderUniforms = function() {
        var i = this.getScene();
        !i || (this.time += i.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(i) {
        this._updateShaderUniforms(),
        a.prototype.render.call(this, i)
    }
    ,
    e.prototype.serialize = function() {
        var i = {};
        return i.customType = "BABYLON.NoiseProceduralTexture",
        i.brightness = this.brightness,
        i.octaves = this.octaves,
        i.persistence = this.persistence,
        i.animationSpeedFactor = this.animationSpeedFactor,
        i.size = this.getSize().width,
        i.generateMipMaps = this._generateMipMaps,
        i.time = this.time,
        i
    }
    ,
    e.prototype.clone = function() {
        var i = this.getSize()
          , o = new e(this.name,i.width,this.getScene(),this._fallbackTexture ? this._fallbackTexture : void 0,this._generateMipMaps);
        return o.hasAlpha = this.hasAlpha,
        o.level = this.level,
        o.coordinatesMode = this.coordinatesMode,
        o.brightness = this.brightness,
        o.octaves = this.octaves,
        o.persistence = this.persistence,
        o.animationSpeedFactor = this.animationSpeedFactor,
        o.time = this.time,
        o
    }
    ,
    e.Parse = function(i, o) {
        var s, c = new e(i.name,i.size,o,void 0,i.generateMipMaps);
        return c.brightness = i.brightness,
        c.octaves = i.octaves,
        c.persistence = i.persistence,
        c.animationSpeedFactor = i.animationSpeedFactor,
        c.time = (s = i.time) !== null && s !== void 0 ? s : 0,
        c
    }
    ,
    e
}(ProceduralTexture);
RegisterClass("BABYLON.NoiseProceduralTexture", NoiseProceduralTexture);
var NodeMaterialBlockTargets;
(function(a) {
    a[a.Vertex = 1] = "Vertex",
    a[a.Fragment = 2] = "Fragment",
    a[a.Neutral = 4] = "Neutral",
    a[a.VertexAndFragment = 3] = "VertexAndFragment"
}
)(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {}));
var NodeMaterialBlockConnectionPointTypes;
(function(a) {
    a[a.Float = 1] = "Float",
    a[a.Int = 2] = "Int",
    a[a.Vector2 = 4] = "Vector2",
    a[a.Vector3 = 8] = "Vector3",
    a[a.Vector4 = 16] = "Vector4",
    a[a.Color3 = 32] = "Color3",
    a[a.Color4 = 64] = "Color4",
    a[a.Matrix = 128] = "Matrix",
    a[a.Object = 256] = "Object",
    a[a.AutoDetect = 1024] = "AutoDetect",
    a[a.BasedOnInput = 2048] = "BasedOnInput"
}
)(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {}));
var NodeMaterialBlockConnectionPointMode;
(function(a) {
    a[a.Uniform = 0] = "Uniform",
    a[a.Attribute = 1] = "Attribute",
    a[a.Varying = 2] = "Varying",
    a[a.Undefined = 3] = "Undefined"
}
)(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {}));
var NodeMaterialSystemValues;
(function(a) {
    a[a.World = 1] = "World",
    a[a.View = 2] = "View",
    a[a.Projection = 3] = "Projection",
    a[a.ViewProjection = 4] = "ViewProjection",
    a[a.WorldView = 5] = "WorldView",
    a[a.WorldViewProjection = 6] = "WorldViewProjection",
    a[a.CameraPosition = 7] = "CameraPosition",
    a[a.FogColor = 8] = "FogColor",
    a[a.DeltaTime = 9] = "DeltaTime",
    a[a.CameraParameters = 10] = "CameraParameters"
}
)(NodeMaterialSystemValues || (NodeMaterialSystemValues = {}));
var NodeMaterialModes;
(function(a) {
    a[a.Material = 0] = "Material",
    a[a.PostProcess = 1] = "PostProcess",
    a[a.Particle = 2] = "Particle",
    a[a.ProceduralTexture = 3] = "ProceduralTexture"
}
)(NodeMaterialModes || (NodeMaterialModes = {}));
var NodeMaterialConnectionPointCompatibilityStates;
(function(a) {
    a[a.Compatible = 0] = "Compatible",
    a[a.TypeIncompatible = 1] = "TypeIncompatible",
    a[a.TargetIncompatible = 2] = "TargetIncompatible",
    a[a.HierarchyIssue = 3] = "HierarchyIssue"
}
)(NodeMaterialConnectionPointCompatibilityStates || (NodeMaterialConnectionPointCompatibilityStates = {}));
var NodeMaterialConnectionPointDirection;
(function(a) {
    a[a.Input = 0] = "Input",
    a[a.Output = 1] = "Output"
}
)(NodeMaterialConnectionPointDirection || (NodeMaterialConnectionPointDirection = {}));
var NodeMaterialConnectionPoint = function() {
    function a(e, i, o) {
        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 = i,
        this.name = e,
        this._direction = o
    }
    return a.AreEquivalentTypes = function(e, i) {
        switch (e) {
        case NodeMaterialBlockConnectionPointTypes.Vector3:
            {
                if (i === NodeMaterialBlockConnectionPointTypes.Color3)
                    return !0;
                break
            }
        case NodeMaterialBlockConnectionPointTypes.Vector4:
            {
                if (i === NodeMaterialBlockConnectionPointTypes.Color4)
                    return !0;
                break
            }
        case NodeMaterialBlockConnectionPointTypes.Color3:
            {
                if (i === NodeMaterialBlockConnectionPointTypes.Vector3)
                    return !0;
                break
            }
        case NodeMaterialBlockConnectionPointTypes.Color4:
            {
                if (i === NodeMaterialBlockConnectionPointTypes.Vector4)
                    return !0;
                break
            }
        }
        return !1
    }
    ,
    Object.defineProperty(a.prototype, "direction", {
        get: function() {
            return this._direction
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "innerType", {
        get: function() {
            return this._linkedConnectionSource && this._linkedConnectionSource.isConnected ? this.type : this._type
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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(a.prototype, "isConnected", {
        get: function() {
            return this.connectedPoint !== null || this.hasEndpoints
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isConnectedToInputBlock", {
        get: function() {
            return this.connectedPoint !== null && this.connectedPoint.ownerBlock.isInput
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "connectInputBlock", {
        get: function() {
            return this.isConnectedToInputBlock ? this.connectedPoint.ownerBlock : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "connectedPoint", {
        get: function() {
            return this._connectedPoint
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "ownerBlock", {
        get: function() {
            return this._ownerBlock
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "sourceBlock", {
        get: function() {
            return this._connectedPoint ? this._connectedPoint.ownerBlock : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "connectedBlocks", {
        get: function() {
            return this._endpoints.length === 0 ? [] : this._endpoints.map(function(e) {
                return e.ownerBlock
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "endpoints", {
        get: function() {
            return this._endpoints
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasEndpoints", {
        get: function() {
            return this._endpoints && this._endpoints.length > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isDirectlyConnectedToVertexOutput", {
        get: function() {
            if (!this.hasEndpoints)
                return !1;
            for (var e = 0, i = this._endpoints; e < i.length; e++) {
                var o = i[e];
                if (o.ownerBlock.target === NodeMaterialBlockTargets.Vertex || (o.ownerBlock.target === NodeMaterialBlockTargets.Neutral || o.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) && o.ownerBlock.outputs.some(function(s) {
                    return s.isDirectlyConnectedToVertexOutput
                }))
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isConnectedInVertexShader", {
        get: function() {
            if (this.target === NodeMaterialBlockTargets.Vertex)
                return !0;
            if (!this.hasEndpoints)
                return !1;
            for (var e = 0, i = this._endpoints; e < i.length; e++) {
                var o = i[e];
                if (o.ownerBlock.target === NodeMaterialBlockTargets.Vertex || o.target === NodeMaterialBlockTargets.Vertex || (o.ownerBlock.target === NodeMaterialBlockTargets.Neutral || o.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) && o.ownerBlock.outputs.some(function(s) {
                    return s.isConnectedInVertexShader
                }))
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isConnectedInFragmentShader", {
        get: function() {
            if (this.target === NodeMaterialBlockTargets.Fragment)
                return !0;
            if (!this.hasEndpoints)
                return !1;
            for (var e = 0, i = this._endpoints; e < i.length; e++) {
                var o = i[e];
                if (o.ownerBlock.target === NodeMaterialBlockTargets.Fragment || (o.ownerBlock.target === NodeMaterialBlockTargets.Neutral || o.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) && o.ownerBlock.outputs.some(function(s) {
                    return s.isConnectedInFragmentShader
                }))
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.createCustomInputBlock = function() {
        return null
    }
    ,
    a.prototype.getClassName = function() {
        return "NodeMaterialConnectionPoint"
    }
    ,
    a.prototype.canConnectTo = function(e) {
        return this.checkCompatibilityState(e) === NodeMaterialConnectionPointCompatibilityStates.Compatible
    }
    ,
    a.prototype.checkCompatibilityState = function(e) {
        var i = this._ownerBlock
          , o = e.ownerBlock;
        if (i.target === NodeMaterialBlockTargets.Fragment) {
            if (o.target === NodeMaterialBlockTargets.Vertex)
                return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;
            for (var s = 0, c = o.outputs; s < c.length; s++) {
                var d = c[s];
                if (d.ownerBlock.target != NodeMaterialBlockTargets.Neutral && d.isConnectedInVertexShader)
                    return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible
            }
        }
        if (this.type !== e.type && e.innerType !== NodeMaterialBlockConnectionPointTypes.AutoDetect)
            return a.AreEquivalentTypes(this.type, e.type) || e.acceptedConnectionPointTypes && e.acceptedConnectionPointTypes.indexOf(this.type) !== -1 || e._acceptedConnectionPointType && a.AreEquivalentTypes(e._acceptedConnectionPointType.type, this.type) ? NodeMaterialConnectionPointCompatibilityStates.Compatible : NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;
        if (e.excludedConnectionPointTypes && e.excludedConnectionPointTypes.indexOf(this.type) !== -1)
            return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;
        var _ = o
          , b = i;
        return this.direction === NodeMaterialConnectionPointDirection.Input && (_ = i,
        b = o),
        _.isAnAncestorOf(b) ? NodeMaterialConnectionPointCompatibilityStates.HierarchyIssue : NodeMaterialConnectionPointCompatibilityStates.Compatible
    }
    ,
    a.prototype.connectTo = function(e, i) {
        if (i === void 0 && (i = !1),
        !i && !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
    }
    ,
    a.prototype.disconnectFrom = function(e) {
        var i = this._endpoints.indexOf(e);
        return i === -1 ? this : (this._endpoints.splice(i, 1),
        e._connectedPoint = null,
        this._enforceAssociatedVariableName = !1,
        e._enforceAssociatedVariableName = !1,
        this)
    }
    ,
    a.prototype.serialize = function(e) {
        e === void 0 && (e = !0);
        var i = {};
        return i.name = this.name,
        i.displayName = this.displayName,
        e && this.connectedPoint && (i.inputName = this.name,
        i.targetBlockId = this.connectedPoint.ownerBlock.uniqueId,
        i.targetConnectionName = this.connectedPoint.name,
        i.isExposedOnFrame = !0,
        i.exposedPortPosition = this.exposedPortPosition),
        (this.isExposedOnFrame || this.exposedPortPosition >= 0) && (i.isExposedOnFrame = !0,
        i.exposedPortPosition = this.exposedPortPosition),
        i
    }
    ,
    a.prototype.dispose = function() {
        this.onConnectionObservable.clear()
    }
    ,
    a
}()
  , NodeMaterialBlock = function() {
    function a(e, i, o, s) {
        i === void 0 && (i = NodeMaterialBlockTargets.Vertex),
        o === void 0 && (o = !1),
        s === void 0 && (s = !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 = i,
        this._originalTargetIsNeutral = i === NodeMaterialBlockTargets.Neutral,
        this._isFinalMerger = o,
        this._isInput = s,
        this._name = e,
        this.uniqueId = UniqueIdGenerator.UniqueId
    }
    return Object.defineProperty(a.prototype, "name", {
        get: function() {
            return this._name
        },
        set: function(e) {
            !this.validateBlockName(e) || (this._name = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isUnique", {
        get: function() {
            return this._isUnique
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isFinalMerger", {
        get: function() {
            return this._isFinalMerger
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isInput", {
        get: function() {
            return this._isInput
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "buildId", {
        get: function() {
            return this._buildId
        },
        set: function(e) {
            this._buildId = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "target", {
        get: function() {
            return this._target
        },
        set: function(e) {
            (this._target & e) === 0 && (this._target = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "inputs", {
        get: function() {
            return this._inputs
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "outputs", {
        get: function() {
            return this._outputs
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getInputByName = function(e) {
        var i = this._inputs.filter(function(o) {
            return o.name === e
        });
        return i.length ? i[0] : null
    }
    ,
    a.prototype.getOutputByName = function(e) {
        var i = this._outputs.filter(function(o) {
            return o.name === e
        });
        return i.length ? i[0] : null
    }
    ,
    a.prototype.initialize = function(e) {}
    ,
    a.prototype.bind = function(e, i, o, s) {}
    ,
    a.prototype._declareOutput = function(e, i) {
        return i._getGLType(e.type) + " " + e.associatedVariableName
    }
    ,
    a.prototype._writeVariable = function(e) {
        var i = e.connectedPoint;
        return i ? "" + e.associatedVariableName : "0."
    }
    ,
    a.prototype._writeFloat = function(e) {
        var i = e.toString();
        return i.indexOf(".") === -1 && (i += ".0"),
        "" + i
    }
    ,
    a.prototype.getClassName = function() {
        return "NodeMaterialBlock"
    }
    ,
    a.prototype.registerInput = function(e, i, o, s, c) {
        return o === void 0 && (o = !1),
        c = c != null ? c : new NodeMaterialConnectionPoint(e,this,NodeMaterialConnectionPointDirection.Input),
        c.type = i,
        c.isOptional = o,
        s && (c.target = s),
        this._inputs.push(c),
        this
    }
    ,
    a.prototype.registerOutput = function(e, i, o, s) {
        return s = s != null ? s : new NodeMaterialConnectionPoint(e,this,NodeMaterialConnectionPointDirection.Output),
        s.type = i,
        o && (s.target = o),
        this._outputs.push(s),
        this
    }
    ,
    a.prototype.getFirstAvailableInput = function(e) {
        e === void 0 && (e = null);
        for (var i = 0, o = this._inputs; i < o.length; i++) {
            var s = o[i];
            if (!s.connectedPoint && (!e || e.type === s.type || s.type === NodeMaterialBlockConnectionPointTypes.AutoDetect))
                return s
        }
        return null
    }
    ,
    a.prototype.getFirstAvailableOutput = function(e) {
        e === void 0 && (e = null);
        for (var i = 0, o = this._outputs; i < o.length; i++) {
            var s = o[i];
            if (!e || !e.target || e.target === NodeMaterialBlockTargets.Neutral || (e.target & s.target) !== 0)
                return s
        }
        return null
    }
    ,
    a.prototype.getSiblingOutput = function(e) {
        var i = this._outputs.indexOf(e);
        return i === -1 || i >= this._outputs.length ? null : this._outputs[i + 1]
    }
    ,
    a.prototype.isAnAncestorOf = function(e) {
        for (var i = 0, o = this._outputs; i < o.length; i++) {
            var s = o[i];
            if (!!s.hasEndpoints)
                for (var c = 0, d = s.endpoints; c < d.length; c++) {
                    var _ = d[c];
                    if (_.ownerBlock === e || _.ownerBlock.isAnAncestorOf(e))
                        return !0
                }
        }
        return !1
    }
    ,
    a.prototype.connectTo = function(e, i) {
        if (this._outputs.length !== 0) {
            for (var o = i && i.output ? this.getOutputByName(i.output) : this.getFirstAvailableOutput(e), s = !0; s; ) {
                var c = i && i.input ? e.getInputByName(i.input) : e.getFirstAvailableInput(o);
                if (o && c && o.canConnectTo(c))
                    o.connectTo(c),
                    s = !1;
                else if (o)
                    o = this.getSiblingOutput(o);
                else
                    throw "Unable to find a compatible match"
            }
            return this
        }
    }
    ,
    a.prototype._buildBlock = function(e) {}
    ,
    a.prototype.updateUniformsAndSamples = function(e, i, o, s) {}
    ,
    a.prototype.provideFallbacks = function(e, i) {}
    ,
    a.prototype.initializeDefines = function(e, i, o, s) {}
    ,
    a.prototype.prepareDefines = function(e, i, o, s, c) {}
    ,
    a.prototype.autoConfigure = function(e) {}
    ,
    a.prototype.replaceRepeatableContent = function(e, i, o, s) {}
    ,
    Object.defineProperty(a.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
    }),
    a.prototype.isReady = function(e, i, o, s) {
        return !0
    }
    ,
    a.prototype._linkConnectionTypes = function(e, i, o) {
        o === void 0 && (o = !1),
        o ? this._inputs[i]._acceptedConnectionPointType = this._inputs[e] : this._inputs[e]._linkedConnectionSource = this._inputs[i],
        this._inputs[i]._linkedConnectionSource = this._inputs[e]
    }
    ,
    a.prototype._processBuild = function(e, i, o, s) {
        e.build(i, s);
        var c = i._vertexState != null
          , d = e._buildTarget === NodeMaterialBlockTargets.Vertex && e.target !== NodeMaterialBlockTargets.VertexAndFragment;
        if (c && ((e.target & e._buildTarget) === 0 || (e.target & o.target) === 0 || this.target !== NodeMaterialBlockTargets.VertexAndFragment && d) && (!e.isInput && i.target !== e._buildTarget || e.isInput && e.isAttribute && !e._noContextSwitch)) {
            var _ = o.connectedPoint;
            i._vertexState._emitVaryingFromString("v_" + _.associatedVariableName, i._getGLType(_.type)) && (i._vertexState.compilationString += "v_" + _.associatedVariableName + " = " + _.associatedVariableName + `;\r
`),
            o.associatedVariableName = "v_" + _.associatedVariableName,
            o._enforceAssociatedVariableName = !0
        }
    }
    ,
    a.prototype.validateBlockName = function(e) {
        for (var i = ["position", "normal", "tangent", "particle_positionw", "uv", "uv2", "uv3", "uv4", "uv5", "uv6", "position2d", "particle_uv", "matricesIndices", "matricesWeights", "world0", "world1", "world2", "world3", "particle_color", "particle_texturemask"], o = 0, s = i; o < s.length; o++) {
            var c = s[o];
            if (e === c)
                return !1
        }
        return !0
    }
    ,
    a.prototype.build = function(e, i) {
        if (this._buildId === e.sharedData.buildId)
            return !0;
        if (!this.isInput)
            for (var o = 0, s = this._outputs; o < s.length; o++) {
                var c = s[o];
                c.associatedVariableName || (c.associatedVariableName = e._getFreeVariableName(c.name))
            }
        for (var d = 0, _ = this._inputs; d < _.length; d++) {
            var b = _[d];
            if (!b.connectedPoint) {
                b.isOptional || e.sharedData.checks.notConnectedNonOptionalInputs.push(b);
                continue
            }
            if (!(this.target !== NodeMaterialBlockTargets.Neutral && ((b.target & this.target) === 0 || (b.target & e.target) === 0))) {
                var k = b.connectedPoint.ownerBlock;
                k && k !== this && this._processBuild(k, e, b, i)
            }
        }
        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 j = 0, $ = this._outputs; j < $.length; j++) {
            var c = $[j];
            if ((c.target & e.target) !== 0)
                for (var _e = 0, et = c.endpoints; _e < et.length; _e++) {
                    var tt = et[_e]
                      , k = tt.ownerBlock;
                    k && (k.target & e.target) !== 0 && i.indexOf(k) !== -1 && this._processBuild(k, e, tt, i)
                }
        }
        return !1
    }
    ,
    a.prototype._inputRename = function(e) {
        return e
    }
    ,
    a.prototype._outputRename = function(e) {
        return e
    }
    ,
    a.prototype._dumpPropertiesCode = function() {
        var e = this._codeVariableName;
        return e + ".visibleInInspector = " + this.visibleInInspector + `;\r
` + e + ".visibleOnFrame = " + this.visibleOnFrame + `;\r
` + e + ".target = " + this.target + `;\r
`
    }
    ,
    a.prototype._dumpCode = function(e, i) {
        i.push(this);
        var o, s = this.name.replace(/[^A-Za-z_]+/g, "");
        if (this._codeVariableName = s || this.getClassName() + "_" + this.uniqueId,
        e.indexOf(this._codeVariableName) !== -1) {
            var c = 0;
            do
                c++,
                this._codeVariableName = s + c;
            while (e.indexOf(this._codeVariableName) !== -1)
        }
        e.push(this._codeVariableName),
        o = `\r
// ` + this.getClassName() + `\r
`,
        this.comments && (o += "// " + this.comments + `\r
`),
        o += "var " + this._codeVariableName + " = new BABYLON." + this.getClassName() + '("' + this.name + `");\r
`,
        o += this._dumpPropertiesCode();
        for (var d = 0, _ = this.inputs; d < _.length; d++) {
            var b = _[d];
            if (!!b.isConnected) {
                var k = b.connectedPoint
                  , j = k.ownerBlock;
                i.indexOf(j) === -1 && (o += j._dumpCode(e, i))
            }
        }
        for (var $ = 0, _e = this.outputs; $ < _e.length; $++) {
            var et = _e[$];
            if (!!et.hasEndpoints)
                for (var tt = 0, rt = et.endpoints; tt < rt.length; tt++) {
                    var it = rt[tt]
                      , j = it.ownerBlock;
                    j && i.indexOf(j) === -1 && (o += j._dumpCode(e, i))
                }
        }
        return o
    }
    ,
    a.prototype._dumpCodeForOutputConnections = function(e) {
        var i = "";
        if (e.indexOf(this) !== -1)
            return i;
        e.push(this);
        for (var o = 0, s = this.inputs; o < s.length; o++) {
            var c = s[o];
            if (!!c.isConnected) {
                var d = c.connectedPoint
                  , _ = d.ownerBlock;
                i += _._dumpCodeForOutputConnections(e),
                i += _._codeVariableName + "." + _._outputRename(d.name) + ".connectTo(" + this._codeVariableName + "." + this._inputRename(c.name) + `);\r
`
            }
        }
        return i
    }
    ,
    a.prototype.clone = function(e, i) {
        i === void 0 && (i = "");
        var o = this.serialize()
          , s = GetClass(o.customType);
        if (s) {
            var c = new s;
            return c._deserialize(o, e, i),
            c
        }
        return null
    }
    ,
    a.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 i = 0, o = this.inputs; i < o.length; i++) {
            var s = o[i];
            e.inputs.push(s.serialize())
        }
        for (var c = 0, d = this.outputs; c < d.length; c++) {
            var _ = d[c];
            e.outputs.push(_.serialize(!1))
        }
        return e
    }
    ,
    a.prototype._deserialize = function(e, i, o) {
        var s;
        this.name = e.name,
        this.comments = e.comments,
        this.visibleInInspector = !!e.visibleInInspector,
        this.visibleOnFrame = !!e.visibleOnFrame,
        this._target = (s = e.target) !== null && s !== void 0 ? s : this.target,
        this._deserializePortDisplayNamesAndExposedOnFrame(e)
    }
    ,
    a.prototype._deserializePortDisplayNamesAndExposedOnFrame = function(e) {
        var i = this
          , o = e.inputs
          , s = e.outputs;
        o && o.forEach(function(c, d) {
            c.displayName && (i.inputs[d].displayName = c.displayName),
            c.isExposedOnFrame && (i.inputs[d].isExposedOnFrame = c.isExposedOnFrame,
            i.inputs[d].exposedPortPosition = c.exposedPortPosition)
        }),
        s && s.forEach(function(c, d) {
            c.displayName && (i.outputs[d].displayName = c.displayName),
            c.isExposedOnFrame && (i.outputs[d].isExposedOnFrame = c.isExposedOnFrame,
            i.outputs[d].exposedPortPosition = c.exposedPortPosition)
        })
    }
    ,
    a.prototype.dispose = function() {
        for (var e = 0, i = this.inputs; e < i.length; e++) {
            var o = i[e];
            o.dispose()
        }
        for (var s = 0, c = this.outputs; s < c.length; s++) {
            var d = c[s];
            d.dispose()
        }
    }
    ,
    a
}()
  , NodeMaterialBuildState = function() {
    function a() {
        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 a.prototype.finalize = function(e) {
        var i = e.sharedData.emitComments
          , o = this.target === NodeMaterialBlockTargets.Fragment;
        this.compilationString = `\r
` + (i ? `//Entry point\r
` : "") + `void main(void) {\r
` + this.compilationString,
        this._constantDeclaration && (this.compilationString = `\r
` + (i ? `//Constants\r
` : "") + this._constantDeclaration + `\r
` + this.compilationString);
        var s = "";
        for (var c in this.functions)
            s += this.functions[c] + `\r
`;
        this.compilationString = `\r
` + s + `\r
` + this.compilationString,
        !o && 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
` + (i ? `//Varyings\r
` : "") + this.sharedData.varyingDeclaration + `\r
` + this.compilationString),
        this._samplerDeclaration && (this.compilationString = `\r
` + (i ? `//Samplers\r
` : "") + this._samplerDeclaration + `\r
` + this.compilationString),
        this._uniformDeclaration && (this.compilationString = `\r
` + (i ? `//Uniforms\r
` : "") + this._uniformDeclaration + `\r
` + this.compilationString),
        this._attributeDeclaration && !o && (this.compilationString = `\r
` + (i ? `//Attributes\r
` : "") + this._attributeDeclaration + `\r
` + this.compilationString),
        this.compilationString = `precision highp float;\r
` + this.compilationString;
        for (var d in this.extensions) {
            var _ = this.extensions[d];
            this.compilationString = `\r
` + _ + `\r
` + this.compilationString
        }
        this._builtCompilationString = this.compilationString
    }
    ,
    Object.defineProperty(a.prototype, "_repeatableContentAnchor", {
        get: function() {
            return "###___ANCHOR" + this._repeatableContentAnchorIndex++ + "___###"
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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])
    }
    ,
    a.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]
    }
    ,
    a.prototype._excludeVariableName = function(e) {
        this.sharedData.variableNames[e] = 0
    }
    ,
    a.prototype._emit2DSampler = function(e) {
        this.samplers.indexOf(e) < 0 && (this._samplerDeclaration += "uniform sampler2D " + e + `;\r
`,
        this.samplers.push(e))
    }
    ,
    a.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 ""
    }
    ,
    a.prototype._emitExtension = function(e, i, o) {
        o === void 0 && (o = ""),
        !this.extensions[e] && (o && (i = "#if " + o + `\r
` + i + `\r
#endif`),
        this.extensions[e] = i)
    }
    ,
    a.prototype._emitFunction = function(e, i, o) {
        this.functions[e] || (this.sharedData.emitComments && (i = o + `\r
` + i),
        this.functions[e] = i)
    }
    ,
    a.prototype._emitCodeFromInclude = function(e, i, o) {
        if (o && o.repeatKey)
            return "#include<" + e + ">[0.." + o.repeatKey + `]\r
`;
        var s = Effect.IncludesShadersStore[e] + `\r
`;
        if (this.sharedData.emitComments && (s = i + `\r
` + s),
        !o)
            return s;
        if (o.replaceStrings)
            for (var c = 0; c < o.replaceStrings.length; c++) {
                var d = o.replaceStrings[c];
                s = s.replace(d.search, d.replace)
            }
        return s
    }
    ,
    a.prototype._emitFunctionFromInclude = function(e, i, o, s) {
        s === void 0 && (s = "");
        var c = e + s;
        if (!this.functions[c]) {
            if (!o || !o.removeAttributes && !o.removeUniforms && !o.removeVaryings && !o.removeIfDef && !o.replaceStrings) {
                o && o.repeatKey ? this.functions[c] = "#include<" + e + ">[0.." + o.repeatKey + `]\r
` : this.functions[c] = "#include<" + e + `>\r
`,
                this.sharedData.emitComments && (this.functions[c] = i + `\r
` + this.functions[c]);
                return
            }
            if (this.functions[c] = Effect.IncludesShadersStore[e],
            this.sharedData.emitComments && (this.functions[c] = i + `\r
` + this.functions[c]),
            o.removeIfDef && (this.functions[c] = this.functions[c].replace(/^\s*?#ifdef.+$/gm, ""),
            this.functions[c] = this.functions[c].replace(/^\s*?#endif.*$/gm, ""),
            this.functions[c] = this.functions[c].replace(/^\s*?#else.*$/gm, ""),
            this.functions[c] = this.functions[c].replace(/^\s*?#elif.*$/gm, "")),
            o.removeAttributes && (this.functions[c] = this.functions[c].replace(/^\s*?attribute.+$/gm, "")),
            o.removeUniforms && (this.functions[c] = this.functions[c].replace(/^\s*?uniform.+$/gm, "")),
            o.removeVaryings && (this.functions[c] = this.functions[c].replace(/^\s*?varying.+$/gm, "")),
            o.replaceStrings)
                for (var d = 0; d < o.replaceStrings.length; d++) {
                    var _ = o.replaceStrings[d];
                    this.functions[c] = this.functions[c].replace(_.search, _.replace)
                }
        }
    }
    ,
    a.prototype._registerTempVariable = function(e) {
        return this.sharedData.temps.indexOf(e) !== -1 ? !1 : (this.sharedData.temps.push(e),
        !0)
    }
    ,
    a.prototype._emitVaryingFromString = function(e, i, o, s) {
        return o === void 0 && (o = ""),
        s === void 0 && (s = !1),
        this.sharedData.varyings.indexOf(e) !== -1 ? !1 : (this.sharedData.varyings.push(e),
        o && (StartsWith(o, "defined(") ? this.sharedData.varyingDeclaration += "#if " + o + `\r
` : this.sharedData.varyingDeclaration += (s ? "#ifndef" : "#ifdef") + " " + o + `\r
`),
        this.sharedData.varyingDeclaration += "varying " + i + " " + e + `;\r
`,
        o && (this.sharedData.varyingDeclaration += `#endif\r
`),
        !0)
    }
    ,
    a.prototype._emitUniformFromString = function(e, i, o, s) {
        o === void 0 && (o = ""),
        s === void 0 && (s = !1),
        this.uniforms.indexOf(e) === -1 && (this.uniforms.push(e),
        o && (StartsWith(o, "defined(") ? this._uniformDeclaration += "#if " + o + `\r
` : this._uniformDeclaration += (s ? "#ifndef" : "#ifdef") + " " + o + `\r
`),
        this._uniformDeclaration += "uniform " + i + " " + e + `;\r
`,
        o && (this._uniformDeclaration += `#endif\r
`))
    }
    ,
    a.prototype._emitFloat = function(e) {
        return e.toString() === e.toFixed(0) ? e + ".0" : e.toString()
    }
    ,
    a
}()
  , NodeMaterialBuildStateSharedData = function() {
    function a() {
        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 a.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 i = 0, o = this.checks.notConnectedNonOptionalInputs; i < o.length; i++) {
            var s = o[i];
            e += "input " + s.name + " from block " + s.ownerBlock.name + "[" + s.ownerBlock.getClassName() + `] is not connected and is not optional.\r
`
        }
        if (e)
            throw `Build of NodeMaterial failed:\r
` + e
    }
    ,
    a
}()
  , TransformBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.complementW = 1,
        o.complementZ = 0,
        o.target = NodeMaterialBlockTargets.Vertex,
        o.registerInput("vector", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("transform", NodeMaterialBlockConnectionPointTypes.Matrix),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].onConnectionObservable.add(function(s) {
            if (s.ownerBlock.isInput) {
                var c = s.ownerBlock;
                (c.name === "normal" || c.name === "tangent") && (o.complementW = 0)
            }
        }),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this.vector
          , s = this.transform;
        if (o.connectedPoint) {
            if (this.complementW === 0) {
                var c = "//" + this.name;
                i._emitFunctionFromInclude("helperFunctions", c),
                i.sharedData.blocksWithDefines.push(this);
                var d = i._getFreeVariableName(s.associatedVariableName + "_NUS");
                switch (i.compilationString += "mat3 " + d + " = mat3(" + s.associatedVariableName + `);\r
`,
                i.compilationString += `#ifdef NONUNIFORMSCALING\r
`,
                i.compilationString += d + " = transposeMat3(inverseMat3(" + d + `));\r
`,
                i.compilationString += `#endif\r
`,
                o.connectedPoint.type) {
                case NodeMaterialBlockConnectionPointTypes.Vector2:
                    i.compilationString += this._declareOutput(this.output, i) + (" = vec4(" + d + " * vec3(" + o.associatedVariableName + ", " + this._writeFloat(this.complementZ) + "), " + this._writeFloat(this.complementW) + `);\r
`);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector3:
                case NodeMaterialBlockConnectionPointTypes.Color3:
                    i.compilationString += this._declareOutput(this.output, i) + (" = vec4(" + d + " * " + o.associatedVariableName + ", " + this._writeFloat(this.complementW) + `);\r
`);
                    break;
                default:
                    i.compilationString += this._declareOutput(this.output, i) + (" = vec4(" + d + " * " + o.associatedVariableName + ".xyz, " + this._writeFloat(this.complementW) + `);\r
`);
                    break
                }
            } else {
                var d = s.associatedVariableName;
                switch (o.connectedPoint.type) {
                case NodeMaterialBlockConnectionPointTypes.Vector2:
                    i.compilationString += this._declareOutput(this.output, i) + (" = " + d + " * vec4(" + o.associatedVariableName + ", " + this._writeFloat(this.complementZ) + ", " + this._writeFloat(this.complementW) + `);\r
`);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector3:
                case NodeMaterialBlockConnectionPointTypes.Color3:
                    i.compilationString += this._declareOutput(this.output, i) + (" = " + d + " * vec4(" + o.associatedVariableName + ", " + this._writeFloat(this.complementW) + `);\r
`);
                    break;
                default:
                    i.compilationString += this._declareOutput(this.output, i) + (" = " + d + " * " + o.associatedVariableName + `;\r
`);
                    break
                }
            }
            this.xyz.hasEndpoints && (i.compilationString += this._declareOutput(this.xyz, i) + (" = " + this.output.associatedVariableName + `.xyz;\r
`))
        }
        return this
    }
    ,
    e.prototype.prepareDefines = function(i, o, s, c, d) {
        i.nonUniformScaling && s.setValue("NONUNIFORMSCALING", !0)
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.complementZ = this.complementZ,
        i.complementW = this.complementW,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.complementZ = i.complementZ !== void 0 ? i.complementZ : 0,
        this.complementW = i.complementW !== void 0 ? i.complementW : 1
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".complementZ = " + this.complementZ + `;\r
`);
        return i += this._codeVariableName + ".complementW = " + this.complementW + `;\r
`,
        i
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.TransformBlock", TransformBlock);
var VertexOutputBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Vertex, !0) || this;
        return o.registerInput("vector", NodeMaterialBlockConnectionPointTypes.Vector4),
        o
    }
    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(i) {
        for (var o = 0, s = i; o < s.length; o++) {
            var c = s[o];
            if (c.useLogarithmicDepth)
                return !0
        }
        return !1
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this.vector;
        return i.compilationString += "gl_Position = " + o.associatedVariableName + `;\r
`,
        this._isLogarithmicDepthEnabled(i.sharedData.fragmentOutputNodes) && (i._emitUniformFromString("logarithmicDepthConstant", "float"),
        i._emitVaryingFromString("vFragmentDepth", "float"),
        i.compilationString += `vFragmentDepth = 1.0 + gl_Position.w;\r
`,
        i.compilationString += `gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.VertexOutputBlock", VertexOutputBlock);
var PropertyTypeForEdition;
(function(a) {
    a[a.Boolean = 0] = "Boolean",
    a[a.Float = 1] = "Float",
    a[a.Int = 2] = "Int",
    a[a.Vector2 = 3] = "Vector2",
    a[a.List = 4] = "List"
}
)(PropertyTypeForEdition || (PropertyTypeForEdition = {}));
function editableInPropertyPage(a, e, i, o) {
    return e === void 0 && (e = PropertyTypeForEdition.Boolean),
    i === void 0 && (i = "PROPERTIES"),
    function(s, c) {
        var d = s._propStore;
        d || (d = [],
        s._propStore = d),
        d.push({
            propertyName: c,
            displayName: a,
            type: e,
            groupName: i,
            options: o != null ? o : {}
        })
    }
}
var FragmentOutputBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment, !0) || this;
        return o.convertToGammaSpace = !1,
        o.convertToLinearSpace = !1,
        o.useLogarithmicDepth = !1,
        o.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, !0),
        o.registerInput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, !0),
        o.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.rgb.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    return e.prototype.getClassName = function() {
        return "FragmentOutputBlock"
    }
    ,
    e.prototype.initialize = function(i) {
        i._excludeVariableName("logarithmicDepthConstant"),
        i._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(i, o, s) {
        s.setValue(this._linearDefineName, this.convertToLinearSpace, !0),
        s.setValue(this._gammaDefineName, this.convertToGammaSpace, !0)
    }
    ,
    e.prototype.bind = function(i, o, s) {
        this.useLogarithmicDepth && s && MaterialHelper.BindLogDepth(void 0, i, s.getScene())
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this.rgba
          , s = this.rgb
          , c = this.a;
        i.sharedData.hints.needAlphaBlending = o.isConnected || c.isConnected,
        i.sharedData.blocksWithDefines.push(this),
        this.useLogarithmicDepth && (i._emitUniformFromString("logarithmicDepthConstant", "float"),
        i._emitVaryingFromString("vFragmentDepth", "float"),
        i.sharedData.bindableBlocks.push(this)),
        this._linearDefineName = i._getFreeDefineName("CONVERTTOLINEAR"),
        this._gammaDefineName = i._getFreeDefineName("CONVERTTOGAMMA");
        var d = "//" + this.name;
        if (i._emitFunctionFromInclude("helperFunctions", d),
        o.connectedPoint)
            c.isConnected ? i.compilationString += "gl_FragColor = vec4(" + o.associatedVariableName + ".rgb, " + c.associatedVariableName + `);\r
` : i.compilationString += "gl_FragColor = " + o.associatedVariableName + `;\r
`;
        else if (s.connectedPoint) {
            var _ = "1.0";
            c.connectedPoint && (_ = c.associatedVariableName),
            s.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float ? i.compilationString += "gl_FragColor = vec4(" + s.associatedVariableName + ", " + s.associatedVariableName + ", " + s.associatedVariableName + ", " + _ + `);\r
` : i.compilationString += "gl_FragColor = vec4(" + s.associatedVariableName + ", " + _ + `);\r
`
        } else
            i.sharedData.checks.notConnectedNonOptionalInputs.push(o);
        return i.compilationString += "#ifdef " + this._linearDefineName + `\r
`,
        i.compilationString += `gl_FragColor = toLinearSpace(gl_FragColor);\r
`,
        i.compilationString += `#endif\r
`,
        i.compilationString += "#ifdef " + this._gammaDefineName + `\r
`,
        i.compilationString += `gl_FragColor = toGammaSpace(gl_FragColor);\r
`,
        i.compilationString += `#endif\r
`,
        this.useLogarithmicDepth && (i.compilationString += `gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r
`),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return i += this._codeVariableName + ".convertToGammaSpace = " + this.convertToGammaSpace + `;\r
`,
        i += this._codeVariableName + ".convertToLinearSpace = " + this.convertToLinearSpace + `;\r
`,
        i += this._codeVariableName + ".useLogarithmicDepth = " + this.useLogarithmicDepth + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.convertToGammaSpace = this.convertToGammaSpace,
        i.convertToLinearSpace = this.convertToLinearSpace,
        i.useLogarithmicDepth = this.useLogarithmicDepth,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        var c;
        a.prototype._deserialize.call(this, i, o, s),
        this.convertToGammaSpace = i.convertToGammaSpace,
        this.convertToLinearSpace = i.convertToLinearSpace,
        this.useLogarithmicDepth = (c = i.useLogarithmicDepth) !== null && c !== void 0 ? c : !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(a) {
    a[a.None = 0] = "None",
    a[a.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(a) {
    __extends(e, a);
    function e(i, o, s) {
        o === void 0 && (o = NodeMaterialBlockTargets.Vertex),
        s === void 0 && (s = NodeMaterialBlockConnectionPointTypes.AutoDetect);
        var c = a.call(this, i, o, !1, !0) || this;
        return c._mode = NodeMaterialBlockConnectionPointMode.Undefined,
        c._animationType = AnimatedInputBlockTypes.None,
        c.min = 0,
        c.max = 0,
        c.isBoolean = !1,
        c.matrixMode = 0,
        c._systemValue = null,
        c.isConstant = !1,
        c.groupInInspector = "",
        c.onValueChangedObservable = new Observable,
        c.convertToGammaSpace = !1,
        c.convertToLinearSpace = !1,
        c._type = s,
        c.setDefaultValue(),
        c.registerOutput("output", s),
        c
    }
    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(i) {
        return this.isAttribute ? !0 : a.prototype.validateBlockName.call(this, i)
    }
    ,
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setAsAttribute = function(i) {
        return this._mode = NodeMaterialBlockConnectionPointMode.Attribute,
        i && (this.name = i),
        this
    }
    ,
    e.prototype.setAsSystemValue = function(i) {
        return this.systemValue = i,
        this
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._storedValue
        },
        set: function(i) {
            this.type === NodeMaterialBlockConnectionPointTypes.Float && (this.isBoolean ? i = i ? 1 : 0 : this.min !== this.max && (i = Math.max(this.min, i),
            i = Math.min(this.max, i))),
            this._storedValue = i,
            this._mode = NodeMaterialBlockConnectionPointMode.Uniform,
            this.onValueChangedObservable.notifyObservers(this)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "valueCallback", {
        get: function() {
            return this._valueCallback
        },
        set: function(i) {
            this._valueCallback = i,
            this._mode = NodeMaterialBlockConnectionPointMode.Uniform
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "associatedVariableName", {
        get: function() {
            return this._associatedVariableName
        },
        set: function(i) {
            this._associatedVariableName = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "animationType", {
        get: function() {
            return this._animationType
        },
        set: function(i) {
            this._animationType = i
        },
        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(i) {
            this._mode = i ? NodeMaterialBlockConnectionPointMode.Uniform : NodeMaterialBlockConnectionPointMode.Undefined,
            this.associatedVariableName = ""
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isAttribute", {
        get: function() {
            return this._mode === NodeMaterialBlockConnectionPointMode.Attribute
        },
        set: function(i) {
            this._mode = i ? NodeMaterialBlockConnectionPointMode.Attribute : NodeMaterialBlockConnectionPointMode.Undefined,
            this.associatedVariableName = ""
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isVarying", {
        get: function() {
            return this._mode === NodeMaterialBlockConnectionPointMode.Varying
        },
        set: function(i) {
            this._mode = i ? 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(i) {
            this._mode = NodeMaterialBlockConnectionPointMode.Uniform,
            this.associatedVariableName = "",
            this._systemValue = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "InputBlock"
    }
    ,
    e.prototype.animate = function(i) {
        switch (this._animationType) {
        case AnimatedInputBlockTypes.Time:
            {
                this.type === NodeMaterialBlockConnectionPointTypes.Float && (this.value += i.getAnimationRatio() * .01);
                break
            }
        }
    }
    ,
    e.prototype._emitDefine = function(i) {
        return i[0] === "!" ? "#ifndef " + i.substring(1) + `\r
` : "#ifdef " + i + `\r
`
    }
    ,
    e.prototype.initialize = function(i) {
        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(i) {
        switch (this.type) {
        case NodeMaterialBlockConnectionPointTypes.Float:
            return "" + i._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(i, o) {
        var s;
        if (this.isUniform) {
            if (this.associatedVariableName || (this.associatedVariableName = i._getFreeVariableName("u_" + this.name)),
            this.isConstant) {
                if (i.constants.indexOf(this.associatedVariableName) !== -1)
                    return;
                i.constants.push(this.associatedVariableName),
                i._constantDeclaration += this._declareOutput(this.output, i) + (" = " + this._emitConstant(i) + `;\r
`);
                return
            }
            if (i.uniforms.indexOf(this.associatedVariableName) !== -1)
                return;
            i.uniforms.push(this.associatedVariableName),
            o && (i._uniformDeclaration += this._emitDefine(o)),
            i._uniformDeclaration += "uniform " + i._getGLType(this.type) + " " + this.associatedVariableName + `;\r
`,
            o && (i._uniformDeclaration += `#endif\r
`);
            var c = i.sharedData.hints;
            if (this._systemValue !== null && this._systemValue !== void 0)
                switch (this._systemValue) {
                case NodeMaterialSystemValues.WorldView:
                    c.needWorldViewMatrix = !0;
                    break;
                case NodeMaterialSystemValues.WorldViewProjection:
                    c.needWorldViewProjectionMatrix = !0;
                    break
                }
            else
                this._animationType !== AnimatedInputBlockTypes.None && i.sharedData.animatedInputs.push(this);
            return
        }
        if (this.isAttribute) {
            if (this.associatedVariableName = (s = remapAttributeName[this.name]) !== null && s !== void 0 ? s : this.name,
            this.target === NodeMaterialBlockTargets.Vertex && i._vertexState) {
                attributeInFragmentOnly[this.name] ? attributeAsUniform[this.name] ? i._emitUniformFromString(this.associatedVariableName, i._getGLType(this.type), o) : i._emitVaryingFromString(this.associatedVariableName, i._getGLType(this.type), o) : this._emit(i._vertexState, o);
                return
            }
            if (i.attributes.indexOf(this.associatedVariableName) !== -1)
                return;
            i.attributes.push(this.associatedVariableName),
            attributeInFragmentOnly[this.name] ? attributeAsUniform[this.name] ? i._emitUniformFromString(this.associatedVariableName, i._getGLType(this.type), o) : i._emitVaryingFromString(this.associatedVariableName, i._getGLType(this.type), o) : (o && (i._attributeDeclaration += this._emitDefine(o)),
            i._attributeDeclaration += "attribute " + i._getGLType(this.type) + " " + this.associatedVariableName + `;\r
`,
            o && (i._attributeDeclaration += `#endif\r
`))
        }
    }
    ,
    e.prototype._transmitWorld = function(i, o, s, c) {
        if (!!this._systemValue) {
            var d = this.associatedVariableName;
            switch (this._systemValue) {
            case NodeMaterialSystemValues.World:
                i.setMatrix(d, o);
                break;
            case NodeMaterialSystemValues.WorldView:
                i.setMatrix(d, s);
                break;
            case NodeMaterialSystemValues.WorldViewProjection:
                i.setMatrix(d, c);
                break
            }
        }
    }
    ,
    e.prototype._transmit = function(i, o) {
        if (!this.isAttribute) {
            var s = this.associatedVariableName;
            if (this._systemValue) {
                switch (this._systemValue) {
                case NodeMaterialSystemValues.World:
                case NodeMaterialSystemValues.WorldView:
                case NodeMaterialSystemValues.WorldViewProjection:
                    return;
                case NodeMaterialSystemValues.View:
                    i.setMatrix(s, o.getViewMatrix());
                    break;
                case NodeMaterialSystemValues.Projection:
                    i.setMatrix(s, o.getProjectionMatrix());
                    break;
                case NodeMaterialSystemValues.ViewProjection:
                    i.setMatrix(s, o.getTransformMatrix());
                    break;
                case NodeMaterialSystemValues.CameraPosition:
                    o.bindEyePosition(i, s, !0);
                    break;
                case NodeMaterialSystemValues.FogColor:
                    i.setColor3(s, o.fogColor);
                    break;
                case NodeMaterialSystemValues.DeltaTime:
                    i.setFloat(s, o.deltaTime / 1e3);
                case NodeMaterialSystemValues.CameraParameters:
                    o.activeCamera && i.setFloat4(s, o.getEngine().hasOriginBottomLeft ? -1 : 1, o.activeCamera.minZ, o.activeCamera.maxZ, 1 / o.activeCamera.maxZ);
                    break
                }
                return
            }
            var c = this._valueCallback ? this._valueCallback() : this._storedValue;
            if (c !== null)
                switch (this.type) {
                case NodeMaterialBlockConnectionPointTypes.Float:
                    i.setFloat(s, c);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Int:
                    i.setInt(s, c);
                    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]),
                    i.setColor3(s, 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]),
                    i.setDirectColor4(s, TmpColors.Color4[0]);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector2:
                    i.setVector2(s, c);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector3:
                    i.setVector3(s, c);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector4:
                    i.setVector4(s, c);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Matrix:
                    i.setMatrix(s, c);
                    break
                }
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i),
        (this.isUniform || this.isSystemValue) && i.sharedData.inputBlocks.push(this),
        this._emit(i)
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = this._codeVariableName;
        if (this.isAttribute)
            return a.prototype._dumpPropertiesCode.call(this) + (i + '.setAsAttribute("' + this.name + `");\r
`);
        if (this.isSystemValue)
            return a.prototype._dumpPropertiesCode.call(this) + (i + ".setAsSystemValue(BABYLON.NodeMaterialSystemValues." + NodeMaterialSystemValues[this._systemValue] + `);\r
`);
        if (this.isUniform) {
            var o = []
              , s = "";
            switch (this.type) {
            case NodeMaterialBlockConnectionPointTypes.Float:
                s = "" + this.value;
                break;
            case NodeMaterialBlockConnectionPointTypes.Vector2:
                s = "new BABYLON.Vector2(" + this.value.x + ", " + this.value.y + ")";
                break;
            case NodeMaterialBlockConnectionPointTypes.Vector3:
                s = "new BABYLON.Vector3(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ")";
                break;
            case NodeMaterialBlockConnectionPointTypes.Vector4:
                s = "new BABYLON.Vector4(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ", " + this.value.w + ")";
                break;
            case NodeMaterialBlockConnectionPointTypes.Color3:
                s = "new BABYLON.Color3(" + this.value.r + ", " + this.value.g + ", " + this.value.b + ")",
                this.convertToGammaSpace && (s += ".toGammaSpace()"),
                this.convertToLinearSpace && (s += ".toLinearSpace()");
                break;
            case NodeMaterialBlockConnectionPointTypes.Color4:
                s = "new BABYLON.Color4(" + this.value.r + ", " + this.value.g + ", " + this.value.b + ", " + this.value.a + ")",
                this.convertToGammaSpace && (s += ".toGammaSpace()"),
                this.convertToLinearSpace && (s += ".toLinearSpace()");
                break;
            case NodeMaterialBlockConnectionPointTypes.Matrix:
                s = "BABYLON.Matrix.FromArray([" + this.value.m + "])";
                break
            }
            return o.push(i + ".value = " + s),
            this.type === NodeMaterialBlockConnectionPointTypes.Float && o.push(i + ".min = " + this.min, i + ".max = " + this.max, i + ".isBoolean = " + this.isBoolean, i + ".matrixMode = " + this.matrixMode, i + ".animationType = BABYLON.AnimatedInputBlockTypes." + AnimatedInputBlockTypes[this.animationType]),
            o.push(i + ".isConstant = " + this.isConstant),
            o.push(""),
            a.prototype._dumpPropertiesCode.call(this) + o.join(`;\r
`)
        }
        return a.prototype._dumpPropertiesCode.call(this)
    }
    ,
    e.prototype.dispose = function() {
        this.onValueChangedObservable.clear(),
        a.prototype.dispose.call(this)
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.type = this.type,
        i.mode = this._mode,
        i.systemValue = this._systemValue,
        i.animationType = this._animationType,
        i.min = this.min,
        i.max = this.max,
        i.isBoolean = this.isBoolean,
        i.matrixMode = this.matrixMode,
        i.isConstant = this.isConstant,
        i.groupInInspector = this.groupInInspector,
        i.convertToGammaSpace = this.convertToGammaSpace,
        i.convertToLinearSpace = this.convertToLinearSpace,
        this._storedValue != null && this._mode === NodeMaterialBlockConnectionPointMode.Uniform && (this._storedValue.asArray ? (i.valueType = "BABYLON." + this._storedValue.getClassName(),
        i.value = this._storedValue.asArray()) : (i.valueType = "number",
        i.value = this._storedValue)),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        if (this._mode = i.mode,
        a.prototype._deserialize.call(this, i, o, s),
        this._type = i.type,
        this._systemValue = i.systemValue || i.wellKnownValue,
        this._animationType = i.animationType,
        this.min = i.min || 0,
        this.max = i.max || 0,
        this.isBoolean = !!i.isBoolean,
        this.matrixMode = i.matrixMode || 0,
        this.isConstant = !!i.isConstant,
        this.groupInInspector = i.groupInInspector || "",
        this.convertToGammaSpace = !!i.convertToGammaSpace,
        this.convertToLinearSpace = !!i.convertToLinearSpace,
        !!i.valueType)
            if (i.valueType === "number")
                this._storedValue = i.value;
            else {
                var c = GetClass(i.valueType);
                c && (this._storedValue = c.FromArray(i.value))
            }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.InputBlock", InputBlock);
var CurrentScreenBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return o._samplerName = "textureSampler",
        o.convertToGammaSpace = !1,
        o.convertToLinearSpace = !1,
        o._isUnique = !1,
        o.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1, NodeMaterialBlockTargets.VertexAndFragment),
        o.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[0]._prioritizeVertex = !1,
        o
    }
    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(i) {
        i._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(i, o, s) {
        s.setValue(this._linearDefineName, this.convertToGammaSpace, !0),
        s.setValue(this._gammaDefineName, this.convertToLinearSpace, !0)
    }
    ,
    e.prototype.isReady = function() {
        return !(this.texture && !this.texture.isReadyOrNotBlocking())
    }
    ,
    e.prototype._injectVertexCode = function(i) {
        var o = this.uv;
        if (o.connectedPoint.ownerBlock.isInput) {
            var s = o.connectedPoint.ownerBlock;
            s.isAttribute || i._emitUniformFromString(o.associatedVariableName, "vec2")
        }
        if (this._mainUVName = "vMain" + o.associatedVariableName,
        i._emitVaryingFromString(this._mainUVName, "vec2"),
        i.compilationString += this._mainUVName + " = " + o.associatedVariableName + `.xy;\r
`,
        !!this._outputs.some(function(b) {
            return b.isConnectedInVertexShader
        })) {
            this._writeTextureRead(i, !0);
            for (var c = 0, d = this._outputs; c < d.length; c++) {
                var _ = d[c];
                _.hasEndpoints && this._writeOutput(i, _, _.name, !0)
            }
        }
    }
    ,
    e.prototype._writeTextureRead = function(i, o) {
        o === void 0 && (o = !1);
        var s = this.uv;
        if (o) {
            if (i.target === NodeMaterialBlockTargets.Fragment)
                return;
            i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + s.associatedVariableName + `);\r
`;
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + s.associatedVariableName + `);\r
`;
            return
        }
        i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this._mainUVName + `);\r
`
    }
    ,
    e.prototype._writeOutput = function(i, o, s, c) {
        if (c === void 0 && (c = !1),
        c) {
            if (i.target === NodeMaterialBlockTargets.Fragment)
                return;
            i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`;
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`;
            return
        }
        i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`,
        i.compilationString += "#ifdef " + this._linearDefineName + `\r
`,
        i.compilationString += o.associatedVariableName + " = toGammaSpace(" + o.associatedVariableName + `);\r
`,
        i.compilationString += `#endif\r
`,
        i.compilationString += "#ifdef " + this._gammaDefineName + `\r
`,
        i.compilationString += o.associatedVariableName + " = toLinearSpace(" + o.associatedVariableName + `);\r
`,
        i.compilationString += `#endif\r
`
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        this._tempTextureRead = i._getFreeVariableName("tempTextureRead"),
        i.sharedData.blockingBlocks.indexOf(this) < 0 && i.sharedData.blockingBlocks.push(this),
        i.sharedData.textureBlocks.indexOf(this) < 0 && i.sharedData.textureBlocks.push(this),
        i.sharedData.blocksWithDefines.indexOf(this) < 0 && i.sharedData.blocksWithDefines.push(this),
        i.target !== NodeMaterialBlockTargets.Fragment) {
            i._emit2DSampler(this._samplerName),
            this._injectVertexCode(i);
            return
        }
        if (!!this._outputs.some(function(_) {
            return _.isConnectedInFragmentShader
        })) {
            i._emit2DSampler(this._samplerName),
            this._linearDefineName = i._getFreeDefineName("ISLINEAR"),
            this._gammaDefineName = i._getFreeDefineName("ISGAMMA");
            var o = "//" + this.name;
            i._emitFunctionFromInclude("helperFunctions", o),
            this._writeTextureRead(i);
            for (var s = 0, c = this._outputs; s < c.length; s++) {
                var d = c[s];
                d.hasEndpoints && this._writeOutput(i, d, d.name)
            }
            return this
        }
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.convertToGammaSpace = this.convertToGammaSpace,
        i.convertToLinearSpace = this.convertToLinearSpace,
        this.texture && !this.texture.isRenderTarget && (i.texture = this.texture.serialize()),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.convertToGammaSpace = i.convertToGammaSpace,
        this.convertToLinearSpace = !!i.convertToLinearSpace,
        i.texture && (s = i.texture.url.indexOf("data:") === 0 ? "" : s,
        this.texture = Texture.Parse(i.texture, o, s))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.CurrentScreenBlock", CurrentScreenBlock);
var ParticleTextureBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o._samplerName = "diffuseSampler",
        o.convertToGammaSpace = !1,
        o.convertToLinearSpace = !1,
        o._isUnique = !1,
        o.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1, NodeMaterialBlockTargets.VertexAndFragment),
        o.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o
    }
    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(i) {
        i._excludeVariableName("diffuseSampler")
    }
    ,
    e.prototype.autoConfigure = function(i) {
        if (!this.uv.isConnected) {
            var o = i.getInputBlockByPredicate(function(s) {
                return s.isAttribute && s.name === "particle_uv"
            });
            o || (o = new InputBlock("uv"),
            o.setAsAttribute("particle_uv")),
            o.output.connectTo(this.uv)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        s.setValue(this._linearDefineName, this.convertToGammaSpace, !0),
        s.setValue(this._gammaDefineName, this.convertToLinearSpace, !0)
    }
    ,
    e.prototype.isReady = function() {
        return !(this.texture && !this.texture.isReadyOrNotBlocking())
    }
    ,
    e.prototype._writeOutput = function(i, o, s) {
        i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`,
        i.compilationString += "#ifdef " + this._linearDefineName + `\r
`,
        i.compilationString += o.associatedVariableName + " = toGammaSpace(" + o.associatedVariableName + `);\r
`,
        i.compilationString += `#endif\r
`,
        i.compilationString += "#ifdef " + this._gammaDefineName + `\r
`,
        i.compilationString += o.associatedVariableName + " = toLinearSpace(" + o.associatedVariableName + `);\r
`,
        i.compilationString += `#endif\r
`
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        i.target !== NodeMaterialBlockTargets.Vertex) {
            this._tempTextureRead = i._getFreeVariableName("tempTextureRead"),
            i._emit2DSampler(this._samplerName),
            i.sharedData.blockingBlocks.push(this),
            i.sharedData.textureBlocks.push(this),
            i.sharedData.blocksWithDefines.push(this),
            this._linearDefineName = i._getFreeDefineName("ISLINEAR"),
            this._gammaDefineName = i._getFreeDefineName("ISGAMMA");
            var o = "//" + this.name;
            i._emitFunctionFromInclude("helperFunctions", o),
            i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this.uv.associatedVariableName + `);\r
`;
            for (var s = 0, c = this._outputs; s < c.length; s++) {
                var d = c[s];
                d.hasEndpoints && this._writeOutput(i, d, d.name)
            }
            return this
        }
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.convertToGammaSpace = this.convertToGammaSpace,
        i.convertToLinearSpace = this.convertToLinearSpace,
        this.texture && !this.texture.isRenderTarget && (i.texture = this.texture.serialize()),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.convertToGammaSpace = i.convertToGammaSpace,
        this.convertToLinearSpace = !!i.convertToLinearSpace,
        i.texture && (s = i.texture.url.indexOf("data:") === 0 ? "" : s,
        this.texture = Texture.Parse(i.texture, o, s))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ParticleTextureBlock", ParticleTextureBlock);
var ParticleRampGradientBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o._isUnique = !0,
        o.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, !1, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("rampColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment),
        o
    }
    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(i) {
        i._excludeVariableName("remapRanges"),
        i._excludeVariableName("rampSampler"),
        i._excludeVariableName("baseColor"),
        i._excludeVariableName("alpha"),
        i._excludeVariableName("remappedColorIndex"),
        i._excludeVariableName("rampColor"),
        i._excludeVariableName("finalAlpha")
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        i.target !== NodeMaterialBlockTargets.Vertex)
            return i._emit2DSampler("rampSampler"),
            i._emitVaryingFromString("remapRanges", "vec4", "RAMPGRADIENT"),
            i.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, i) + ` = baseColor;
            #else
                ` + this._declareOutput(this.rampColor, i) + " = " + this.color.associatedVariableName + `;
            #endif
        `,
            this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ParticleRampGradientBlock", ParticleRampGradientBlock);
var ParticleBlendMultiplyBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o._isUnique = !0,
        o.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("alphaTexture", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("alphaColor", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("blendColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment),
        o
    }
    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(i) {
        i._excludeVariableName("sourceAlpha")
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        i.target !== NodeMaterialBlockTargets.Vertex)
            return i.compilationString += `
            #ifdef BLENDMULTIPLYMODE
                ` + this._declareOutput(this.blendColor, i) + `;
                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, i) + " = " + this.color.associatedVariableName + `;
            #endif
        `,
            this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ParticleBlendMultiplyBlock", ParticleBlendMultiplyBlock);
var VectorMergerBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.xSwizzle = "x",
        o.ySwizzle = "y",
        o.zSwizzle = "z",
        o.wSwizzle = "w",
        o.registerInput("xyzw ", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        o.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, !0),
        o.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, !0),
        o.registerInput("zw ", NodeMaterialBlockConnectionPointTypes.Vector2, !0),
        o.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("z", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("w", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2),
        o
    }
    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(i) {
        return i === "xyzw " ? "xyzwIn" : i === "xyz " ? "xyzIn" : i === "xy " ? "xyIn" : i === "zw " ? "zwIn" : i
    }
    ,
    e.prototype._buildSwizzle = function(i) {
        var o = this.xSwizzle + this.ySwizzle + this.zSwizzle + this.wSwizzle;
        return "." + o.substr(0, i)
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this.x
          , s = this.y
          , c = this.z
          , d = this.w
          , _ = this.xyIn
          , b = this.zwIn
          , k = this.xyzIn
          , j = this.xyzwIn
          , $ = this._outputs[0]
          , _e = this._outputs[1]
          , et = this._outputs[2]
          , tt = this._outputs[3];
        return j.isConnected ? ($.hasEndpoints && (i.compilationString += this._declareOutput($, i) + (" = " + j.associatedVariableName + this._buildSwizzle(4) + `;\r
`)),
        _e.hasEndpoints && (i.compilationString += this._declareOutput(_e, i) + (" = " + j.associatedVariableName + this._buildSwizzle(3) + `;\r
`)),
        et.hasEndpoints && (i.compilationString += this._declareOutput(et, i) + (" = " + j.associatedVariableName + this._buildSwizzle(2) + `;\r
`))) : k.isConnected ? ($.hasEndpoints && (i.compilationString += this._declareOutput($, i) + (" = vec4(" + k.associatedVariableName + ", " + (d.isConnected ? this._writeVariable(d) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        _e.hasEndpoints && (i.compilationString += this._declareOutput(_e, i) + (" = " + k.associatedVariableName + this._buildSwizzle(3) + `;\r
`)),
        et.hasEndpoints && (i.compilationString += this._declareOutput(et, i) + (" = " + k.associatedVariableName + this._buildSwizzle(2) + `;\r
`))) : _.isConnected ? ($.hasEndpoints && (b.isConnected ? i.compilationString += this._declareOutput($, i) + (" = vec4(" + _.associatedVariableName + ", " + b.associatedVariableName + ")" + this._buildSwizzle(4) + `;\r
`) : i.compilationString += this._declareOutput($, i) + (" = vec4(" + _.associatedVariableName + ", " + (c.isConnected ? this._writeVariable(c) : "0.0") + ", " + (d.isConnected ? this._writeVariable(d) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        _e.hasEndpoints && (i.compilationString += this._declareOutput(_e, i) + (" = vec3(" + _.associatedVariableName + ", " + (c.isConnected ? this._writeVariable(c) : "0.0") + ")" + this._buildSwizzle(3) + `;\r
`)),
        et.hasEndpoints && (i.compilationString += this._declareOutput(et, i) + (" = " + _.associatedVariableName + this._buildSwizzle(2) + `;\r
`)),
        tt.hasEndpoints && (b.isConnected ? i.compilationString += this._declareOutput(tt, i) + (" = " + b.associatedVariableName + this._buildSwizzle(2) + `;\r
`) : i.compilationString += this._declareOutput(tt, i) + (" = vec2(" + (c.isConnected ? this._writeVariable(c) : "0.0") + ", " + (d.isConnected ? this._writeVariable(d) : "0.0") + ")" + this._buildSwizzle(2) + `;\r
`))) : ($.hasEndpoints && (b.isConnected ? i.compilationString += this._declareOutput($, i) + (" = vec4(" + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (s.isConnected ? this._writeVariable(s) : "0.0") + ", " + b.associatedVariableName + ")" + this._buildSwizzle(4) + `;\r
`) : i.compilationString += this._declareOutput($, i) + (" = vec4(" + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (s.isConnected ? this._writeVariable(s) : "0.0") + ", " + (c.isConnected ? this._writeVariable(c) : "0.0") + ", " + (d.isConnected ? this._writeVariable(d) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        _e.hasEndpoints && (i.compilationString += this._declareOutput(_e, i) + (" = vec3(" + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (s.isConnected ? this._writeVariable(s) : "0.0") + ", " + (c.isConnected ? this._writeVariable(c) : "0.0") + ")" + this._buildSwizzle(3) + `;\r
`)),
        et.hasEndpoints && (i.compilationString += this._declareOutput(et, i) + (" = vec2(" + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (s.isConnected ? this._writeVariable(s) : "0.0") + ")" + this._buildSwizzle(2) + `;\r
`)),
        tt.hasEndpoints && (b.isConnected ? i.compilationString += this._declareOutput(tt, i) + (" = " + b.associatedVariableName + this._buildSwizzle(2) + `;\r
`) : i.compilationString += this._declareOutput(tt, i) + (" = vec2(" + (c.isConnected ? this._writeVariable(c) : "0.0") + ", " + (d.isConnected ? this._writeVariable(d) : "0.0") + ")" + this._buildSwizzle(2) + `;\r
`))),
        this
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.xSwizzle = this.xSwizzle,
        i.ySwizzle = this.ySwizzle,
        i.zSwizzle = this.zSwizzle,
        i.wSwizzle = this.wSwizzle,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        var c, d, _, b;
        a.prototype._deserialize.call(this, i, o, s),
        this.xSwizzle = (c = i.xSwizzle) !== null && c !== void 0 ? c : "x",
        this.ySwizzle = (d = i.ySwizzle) !== null && d !== void 0 ? d : "y",
        this.zSwizzle = (_ = i.zSwizzle) !== null && _ !== void 0 ? _ : "z",
        this.wSwizzle = (b = i.wSwizzle) !== null && b !== void 0 ? b : "w"
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return i += this._codeVariableName + '.xSwizzle = "' + this.xSwizzle + `";\r
`,
        i += this._codeVariableName + '.ySwizzle = "' + this.ySwizzle + `";\r
`,
        i += this._codeVariableName + '.zSwizzle = "' + this.zSwizzle + `";\r
`,
        i += this._codeVariableName + '.wSwizzle = "' + this.wSwizzle + `";\r
`,
        i
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.VectorMergerBlock", VectorMergerBlock);
var RemapBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.sourceRange = new Vector2(-1,1),
        o.targetRange = new Vector2(0,1),
        o.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("sourceMin", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("sourceMax", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("targetMin", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("targetMax", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = this.sourceMin.isConnected ? this.sourceMin.associatedVariableName : this._writeFloat(this.sourceRange.x)
          , c = this.sourceMax.isConnected ? this.sourceMax.associatedVariableName : this._writeFloat(this.sourceRange.y)
          , d = this.targetMin.isConnected ? this.targetMin.associatedVariableName : this._writeFloat(this.targetRange.x)
          , _ = this.targetMax.isConnected ? this.targetMax.associatedVariableName : this._writeFloat(this.targetRange.y);
        return i.compilationString += this._declareOutput(o, i) + (" = " + d + " + (" + this._inputs[0].associatedVariableName + " - " + s + ") * (" + _ + " - " + d + ") / (" + c + " - " + s + `);\r
`),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".sourceRange = new BABYLON.Vector2(" + this.sourceRange.x + ", " + this.sourceRange.y + `);\r
`);
        return i += this._codeVariableName + ".targetRange = new BABYLON.Vector2(" + this.targetRange.x + ", " + this.targetRange.y + `);\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.sourceRange = this.sourceRange.asArray(),
        i.targetRange = this.targetRange.asArray(),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.sourceRange = Vector2.FromArray(i.sourceRange),
        this.targetRange = Vector2.FromArray(i.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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = " + this.left.associatedVariableName + " * " + this.right.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MultiplyBlock", MultiplyBlock);
var ColorSplitterBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, !0),
        o.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, !0),
        o.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3),
        o.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float),
        o.inputsAreExclusive = !0,
        o
    }
    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(i) {
        return i === "rgb " ? "rgbIn" : i
    }
    ,
    e.prototype._outputRename = function(i) {
        return i === "rgb" ? "rgbOut" : i
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this.rgba.isConnected ? this.rgba : this.rgbIn;
        if (!!o.isConnected) {
            var s = this._outputs[0]
              , c = this._outputs[1]
              , d = this._outputs[2]
              , _ = this._outputs[3]
              , b = this._outputs[4];
            return s.hasEndpoints && (i.compilationString += this._declareOutput(s, i) + (" = " + o.associatedVariableName + `.rgb;\r
`)),
            c.hasEndpoints && (i.compilationString += this._declareOutput(c, i) + (" = " + o.associatedVariableName + `.r;\r
`)),
            d.hasEndpoints && (i.compilationString += this._declareOutput(d, i) + (" = " + o.associatedVariableName + `.g;\r
`)),
            _.hasEndpoints && (i.compilationString += this._declareOutput(_, i) + (" = " + o.associatedVariableName + `.b;\r
`)),
            b.hasEndpoints && (i.compilationString += this._declareOutput(b, i) + (" = " + o.associatedVariableName + `.a;\r
`)),
            this
        }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ColorSplitterBlock", ColorSplitterBlock);
var TrigonometryBlockOperations;
(function(a) {
    a[a.Cos = 0] = "Cos",
    a[a.Sin = 1] = "Sin",
    a[a.Abs = 2] = "Abs",
    a[a.Exp = 3] = "Exp",
    a[a.Exp2 = 4] = "Exp2",
    a[a.Round = 5] = "Round",
    a[a.Floor = 6] = "Floor",
    a[a.Ceiling = 7] = "Ceiling",
    a[a.Sqrt = 8] = "Sqrt",
    a[a.Log = 9] = "Log",
    a[a.Tan = 10] = "Tan",
    a[a.ArcTan = 11] = "ArcTan",
    a[a.ArcCos = 12] = "ArcCos",
    a[a.ArcSin = 13] = "ArcSin",
    a[a.Fract = 14] = "Fract",
    a[a.Sign = 15] = "Sign",
    a[a.Radians = 16] = "Radians",
    a[a.Degrees = 17] = "Degrees"
}
)(TrigonometryBlockOperations || (TrigonometryBlockOperations = {}));
var TrigonometryBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.operation = TrigonometryBlockOperations.Cos,
        o.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = "";
        switch (this.operation) {
        case TrigonometryBlockOperations.Cos:
            {
                s = "cos";
                break
            }
        case TrigonometryBlockOperations.Sin:
            {
                s = "sin";
                break
            }
        case TrigonometryBlockOperations.Abs:
            {
                s = "abs";
                break
            }
        case TrigonometryBlockOperations.Exp:
            {
                s = "exp";
                break
            }
        case TrigonometryBlockOperations.Exp2:
            {
                s = "exp2";
                break
            }
        case TrigonometryBlockOperations.Round:
            {
                s = "round";
                break
            }
        case TrigonometryBlockOperations.Floor:
            {
                s = "floor";
                break
            }
        case TrigonometryBlockOperations.Ceiling:
            {
                s = "ceil";
                break
            }
        case TrigonometryBlockOperations.Sqrt:
            {
                s = "sqrt";
                break
            }
        case TrigonometryBlockOperations.Log:
            {
                s = "log";
                break
            }
        case TrigonometryBlockOperations.Tan:
            {
                s = "tan";
                break
            }
        case TrigonometryBlockOperations.ArcTan:
            {
                s = "atan";
                break
            }
        case TrigonometryBlockOperations.ArcCos:
            {
                s = "acos";
                break
            }
        case TrigonometryBlockOperations.ArcSin:
            {
                s = "asin";
                break
            }
        case TrigonometryBlockOperations.Fract:
            {
                s = "fract";
                break
            }
        case TrigonometryBlockOperations.Sign:
            {
                s = "sign";
                break
            }
        case TrigonometryBlockOperations.Radians:
            {
                s = "radians";
                break
            }
        case TrigonometryBlockOperations.Degrees:
            {
                s = "degrees";
                break
            }
        }
        return i.compilationString += this._declareOutput(o, i) + (" = " + s + "(" + this.input.associatedVariableName + `);\r
`),
        this
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.operation = this.operation,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.operation = i.operation
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".operation = BABYLON.TrigonometryBlockOperations." + TrigonometryBlockOperations[this.operation] + `;\r
`);
        return i
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.TrigonometryBlock", TrigonometryBlock);
var onCreatedEffectParameters$1 = {
    effect: null,
    subMesh: null
}
  , NodeMaterialDefines = function(a) {
    __extends(e, a);
    function e() {
        var i = a.call(this) || this;
        return i.NORMAL = !1,
        i.TANGENT = !1,
        i.UV1 = !1,
        i.UV2 = !1,
        i.UV3 = !1,
        i.UV4 = !1,
        i.UV5 = !1,
        i.UV6 = !1,
        i.NUM_BONE_INFLUENCERS = 0,
        i.BonesPerMesh = 0,
        i.BONETEXTURE = !1,
        i.MORPHTARGETS = !1,
        i.MORPHTARGETS_NORMAL = !1,
        i.MORPHTARGETS_TANGENT = !1,
        i.MORPHTARGETS_UV = !1,
        i.NUM_MORPH_INFLUENCERS = 0,
        i.MORPHTARGETS_TEXTURE = !1,
        i.IMAGEPROCESSING = !1,
        i.VIGNETTE = !1,
        i.VIGNETTEBLENDMODEMULTIPLY = !1,
        i.VIGNETTEBLENDMODEOPAQUE = !1,
        i.TONEMAPPING = !1,
        i.TONEMAPPING_ACES = !1,
        i.CONTRAST = !1,
        i.EXPOSURE = !1,
        i.COLORCURVES = !1,
        i.COLORGRADING = !1,
        i.COLORGRADING3D = !1,
        i.SAMPLER3DGREENDEPTH = !1,
        i.SAMPLER3DBGRMAP = !1,
        i.IMAGEPROCESSINGPOSTPROCESS = !1,
        i.SKIPFINALCOLORCLAMP = !1,
        i.BUMPDIRECTUV = 0,
        i.rebuild(),
        i
    }
    return e.prototype.setValue = function(i, o, s) {
        s === void 0 && (s = !1),
        this[i] === void 0 && this._keys.push(i),
        s && this[i] !== o && this.markAsUnprocessed(),
        this[i] = o
    }
    ,
    e
}(MaterialDefines)
  , NodeMaterial = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        s === void 0 && (s = {});
        var c = a.call(this, i, o || Engine.LastCreatedScene) || this;
        return c._buildId = e._BuildIdGenerator++,
        c._buildWasSuccessful = !1,
        c._cachedWorldViewMatrix = new Matrix,
        c._cachedWorldViewProjectionMatrix = new Matrix,
        c._optimizers = new Array,
        c._animationFrame = -1,
        c.BJSNODEMATERIALEDITOR = c._getGlobalNodeMaterialEditor(),
        c.editorData = null,
        c.ignoreAlpha = !1,
        c.maxSimultaneousLights = 4,
        c.onBuildObservable = new Observable,
        c._vertexOutputNodes = new Array,
        c._fragmentOutputNodes = new Array,
        c.attachedBlocks = new Array,
        c._mode = NodeMaterialModes.Material,
        c._options = __assign({
            emitComments: !1
        }, s),
        c._attachImageProcessingConfiguration(null),
        c
    }
    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(i) {
            this._options = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(i) {
            this._attachImageProcessingConfiguration(i),
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "mode", {
        get: function() {
            return this._mode
        },
        set: function(i) {
            this._mode = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buildId", {
        get: function() {
            return this._buildId
        },
        set: function(i) {
            this._buildId = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "NodeMaterial"
    }
    ,
    e.prototype._attachImageProcessingConfiguration = function(i) {
        var o = this;
        i !== this._imageProcessingConfiguration && (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        i ? this._imageProcessingConfiguration = i : this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration,
        this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
            o._markAllSubMeshesAsImageProcessingDirty()
        })))
    }
    ,
    e.prototype.getBlockByName = function(i) {
        for (var o = null, s = 0, c = this.attachedBlocks; s < c.length; s++) {
            var d = c[s];
            if (d.name === i)
                if (!o)
                    o = d;
                else
                    return Tools.Warn("More than one block was found with the name `" + i + "`"),
                    o
        }
        return o
    }
    ,
    e.prototype.getBlockByPredicate = function(i) {
        for (var o = 0, s = this.attachedBlocks; o < s.length; o++) {
            var c = s[o];
            if (i(c))
                return c
        }
        return null
    }
    ,
    e.prototype.getInputBlockByPredicate = function(i) {
        for (var o = 0, s = this.attachedBlocks; o < s.length; o++) {
            var c = s[o];
            if (c.isInput && i(c))
                return c
        }
        return null
    }
    ,
    e.prototype.getInputBlocks = function() {
        for (var i = [], o = 0, s = this.attachedBlocks; o < s.length; o++) {
            var c = s[o];
            c.isInput && i.push(c)
        }
        return i
    }
    ,
    e.prototype.registerOptimizer = function(i) {
        var o = this._optimizers.indexOf(i);
        if (!(o > -1))
            return this._optimizers.push(i),
            this
    }
    ,
    e.prototype.unregisterOptimizer = function(i) {
        var o = this._optimizers.indexOf(i);
        if (o !== -1)
            return this._optimizers.splice(o, 1),
            this
    }
    ,
    e.prototype.addOutputNode = function(i) {
        if (i.target === null)
            throw "This node is not meant to be an output node. You may want to explicitly set its target value.";
        return (i.target & NodeMaterialBlockTargets.Vertex) !== 0 && this._addVertexOutputNode(i),
        (i.target & NodeMaterialBlockTargets.Fragment) !== 0 && this._addFragmentOutputNode(i),
        this
    }
    ,
    e.prototype.removeOutputNode = function(i) {
        return i.target === null ? this : ((i.target & NodeMaterialBlockTargets.Vertex) !== 0 && this._removeVertexOutputNode(i),
        (i.target & NodeMaterialBlockTargets.Fragment) !== 0 && this._removeFragmentOutputNode(i),
        this)
    }
    ,
    e.prototype._addVertexOutputNode = function(i) {
        if (this._vertexOutputNodes.indexOf(i) === -1)
            return i.target = NodeMaterialBlockTargets.Vertex,
            this._vertexOutputNodes.push(i),
            this
    }
    ,
    e.prototype._removeVertexOutputNode = function(i) {
        var o = this._vertexOutputNodes.indexOf(i);
        if (o !== -1)
            return this._vertexOutputNodes.splice(o, 1),
            this
    }
    ,
    e.prototype._addFragmentOutputNode = function(i) {
        if (this._fragmentOutputNodes.indexOf(i) === -1)
            return i.target = NodeMaterialBlockTargets.Fragment,
            this._fragmentOutputNodes.push(i),
            this
    }
    ,
    e.prototype._removeFragmentOutputNode = function(i) {
        var o = this._fragmentOutputNodes.indexOf(i);
        if (o !== -1)
            return this._fragmentOutputNodes.splice(o, 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(i, o, s, c) {
        if (c === void 0 && (c = !0),
        i.initialize(o),
        c && i.autoConfigure(this),
        i._preparationId = this._buildId,
        this.attachedBlocks.indexOf(i) === -1) {
            if (i.isUnique)
                for (var d = i.getClassName(), _ = 0, b = this.attachedBlocks; _ < b.length; _++) {
                    var k = b[_];
                    if (k.getClassName() === d)
                        throw "Cannot have multiple blocks of type " + d + " in the same NodeMaterial"
                }
            this.attachedBlocks.push(i)
        }
        for (var j = 0, $ = i.inputs; j < $.length; j++) {
            var _e = $[j];
            _e.associatedVariableName = "";
            var et = _e.connectedPoint;
            if (et) {
                var tt = et.ownerBlock;
                tt !== i && ((tt.target === NodeMaterialBlockTargets.VertexAndFragment || o.target === NodeMaterialBlockTargets.Fragment && tt.target === NodeMaterialBlockTargets.Vertex && tt._preparationId !== this._buildId) && s.push(tt),
                this._initializeBlock(tt, o, s, c))
            }
        }
        for (var rt = 0, it = i.outputs; rt < it.length; rt++) {
            var nt = it[rt];
            nt.associatedVariableName = ""
        }
    }
    ,
    e.prototype._resetDualBlocks = function(i, o) {
        i.target === NodeMaterialBlockTargets.VertexAndFragment && (i.buildId = o);
        for (var s = 0, c = i.inputs; s < c.length; s++) {
            var d = c[s]
              , _ = d.connectedPoint;
            if (_) {
                var b = _.ownerBlock;
                b !== i && this._resetDualBlocks(b, o)
            }
        }
    }
    ,
    e.prototype.removeBlock = function(i) {
        var o = this.attachedBlocks.indexOf(i);
        o > -1 && this.attachedBlocks.splice(o, 1),
        i.isFinalMerger && this.removeOutputNode(i)
    }
    ,
    e.prototype.build = function(i, o, s) {
        i === void 0 && (i = !1),
        o === void 0 && (o = !0),
        s === void 0 && (s = !0),
        this._buildWasSuccessful = !1;
        var c = this.getScene().getEngine()
          , d = this._mode === NodeMaterialModes.Particle;
        if (this._vertexOutputNodes.length === 0 && !d)
            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 = c.supportsUniformBuffers,
        this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex,
        this._fragmentCompilationState = new NodeMaterialBuildState,
        this._fragmentCompilationState.supportUniformBuffers = c.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 = i,
        this._sharedData.scene = this.getScene(),
        this._sharedData.allowEmptyVertexProgram = d;
        for (var _ = [], b = [], k = 0, j = this._vertexOutputNodes; k < j.length; k++) {
            var $ = j[k];
            _.push($),
            this._initializeBlock($, this._vertexCompilationState, b, s)
        }
        for (var _e = 0, et = this._fragmentOutputNodes; _e < et.length; _e++) {
            var tt = et[_e];
            b.push(tt),
            this._initializeBlock(tt, this._fragmentCompilationState, _, s)
        }
        this.optimize();
        for (var rt = 0, it = _; rt < it.length; rt++) {
            var $ = it[rt];
            $.build(this._vertexCompilationState, _)
        }
        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 nt = 0, ot = b; nt < ot.length; nt++) {
            var tt = ot[nt];
            this._resetDualBlocks(tt, this._buildId - 1)
        }
        for (var at = 0, st = b; at < st.length; at++) {
            var tt = st[at];
            tt.build(this._fragmentCompilationState, b)
        }
        this._vertexCompilationState.finalize(this._vertexCompilationState),
        this._fragmentCompilationState.finalize(this._fragmentCompilationState),
        o && (this._buildId = e._BuildIdGenerator++),
        this._sharedData.emitErrors(),
        i && (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 ut = this.getScene().meshes, ct = 0, lt = ut; ct < lt.length; ct++) {
            var ft = lt[ct];
            if (!!ft.subMeshes)
                for (var ht = 0, pt = ft.subMeshes; ht < pt.length; ht++) {
                    var dt = pt[ht];
                    if (dt.getMaterial() === this && !!dt.materialDefines) {
                        var _t = dt.materialDefines;
                        _t.markAllAsDirty(),
                        _t.reset()
                    }
                }
        }
    }
    ,
    e.prototype.optimize = function() {
        for (var i = 0, o = this._optimizers; i < o.length; i++) {
            var s = o[i];
            s.optimize(this._vertexOutputNodes, this._fragmentOutputNodes)
        }
    }
    ,
    e.prototype._prepareDefinesForAttributes = function(i, o) {
        var s = o.NORMAL
          , c = o.TANGENT;
        o.NORMAL = i.isVerticesDataPresent(VertexBuffer.NormalKind),
        o.TANGENT = i.isVerticesDataPresent(VertexBuffer.TangentKind);
        for (var d = !1, _ = 1; _ <= 6; ++_) {
            var b = o["UV" + _];
            o["UV" + _] = i.isVerticesDataPresent("uv" + (_ === 1 ? "" : _)),
            d = d || o["UV" + _] !== b
        }
        (s !== o.NORMAL || c !== o.TANGENT || d) && o.markAsAttributesDirty()
    }
    ,
    e.prototype.createPostProcess = function(i, o, s, c, d, _, b) {
        return o === void 0 && (o = 1),
        s === void 0 && (s = 1),
        _ === void 0 && (_ = 0),
        b === void 0 && (b = 5),
        this.mode !== NodeMaterialModes.PostProcess ? (console.log("Incompatible material mode"),
        null) : this._createEffectForPostProcess(null, i, o, s, c, d, _, b)
    }
    ,
    e.prototype.createEffectForPostProcess = function(i) {
        this._createEffectForPostProcess(i)
    }
    ,
    e.prototype._createEffectForPostProcess = function(i, o, s, c, d, _, b, k) {
        var j = this;
        s === void 0 && (s = 1),
        c === void 0 && (c = 1),
        b === void 0 && (b = 0),
        k === void 0 && (k = 5);
        var $ = this.name + this._buildId
          , _e = new NodeMaterialDefines
          , et = new AbstractMesh($ + "PostProcess",this.getScene())
          , tt = this._buildId;
        return this._processDefines(et, _e),
        Effect.RegisterShader($, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString),
        i ? i.updateEffect(_e.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, {
            maxSimultaneousLights: this.maxSimultaneousLights
        }, void 0, void 0, $, $) : i = new PostProcess(this.name + "PostProcess",$,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,s,o,c,d,_,_e.toString(),b,$,{
            maxSimultaneousLights: this.maxSimultaneousLights
        },!1,k),
        i.nodeMaterialSource = this,
        i.onApplyObservable.add(function(rt) {
            tt !== j._buildId && (delete Effect.ShadersStore[$ + "VertexShader"],
            delete Effect.ShadersStore[$ + "PixelShader"],
            $ = j.name + j._buildId,
            _e.markAllAsDirty(),
            tt = j._buildId);
            var it = j._processDefines(et, _e);
            it && (Effect.RegisterShader($, j._fragmentCompilationState._builtCompilationString, j._vertexCompilationState._builtCompilationString),
            TimingTools.SetImmediate(function() {
                return i.updateEffect(_e.toString(), j._fragmentCompilationState.uniforms, j._fragmentCompilationState.samplers, {
                    maxSimultaneousLights: j.maxSimultaneousLights
                }, void 0, void 0, $, $)
            })),
            j._checkInternals(rt)
        }),
        i
    }
    ,
    e.prototype.createProceduralTexture = function(i, o) {
        var s = this;
        if (this.mode !== NodeMaterialModes.ProceduralTexture)
            return console.log("Incompatible material mode"),
            null;
        var c = this.name + this._buildId
          , d = new ProceduralTexture(c,i,null,o)
          , _ = new AbstractMesh(c + "Procedural",this.getScene());
        _.reservedDataStore = {
            hidden: !0
        };
        var b = new NodeMaterialDefines
          , k = this._processDefines(_, b);
        Effect.RegisterShader(c, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);
        var j = this.getScene().getEngine().createEffect({
            vertexElement: c,
            fragmentElement: c
        }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, b.toString(), k == null ? void 0 : k.fallbacks, void 0);
        d.nodeMaterialSource = this,
        d._setEffect(j);
        var $ = this._buildId;
        return d.onBeforeGenerationObservable.add(function() {
            $ !== s._buildId && (delete Effect.ShadersStore[c + "VertexShader"],
            delete Effect.ShadersStore[c + "PixelShader"],
            c = s.name + s._buildId,
            b.markAllAsDirty(),
            $ = s._buildId);
            var _e = s._processDefines(_, b);
            _e && (Effect.RegisterShader(c, s._fragmentCompilationState._builtCompilationString, s._vertexCompilationState._builtCompilationString),
            TimingTools.SetImmediate(function() {
                j = s.getScene().getEngine().createEffect({
                    vertexElement: c,
                    fragmentElement: c
                }, [VertexBuffer.PositionKind], s._fragmentCompilationState.uniforms, s._fragmentCompilationState.samplers, b.toString(), _e == null ? void 0 : _e.fallbacks, void 0),
                d._setEffect(j)
            })),
            s._checkInternals(j)
        }),
        d
    }
    ,
    e.prototype._createEffectForParticles = function(i, o, s, c, d, _, b, k) {
        var j = this;
        k === void 0 && (k = "");
        var $ = this.name + this._buildId + "_" + o;
        _ || (_ = new NodeMaterialDefines),
        b || (b = this.getScene().getMeshByName(this.name + "Particle"),
        b || (b = new AbstractMesh(this.name + "Particle",this.getScene()),
        b.reservedDataStore = {
            hidden: !0
        }));
        var _e = this._buildId
          , et = []
          , tt = k;
        if (!d) {
            var rt = this._processDefines(b, _);
            Effect.RegisterShader($, this._fragmentCompilationState._builtCompilationString),
            i.fillDefines(et, o),
            tt = et.join(`
`),
            d = this.getScene().getEngine().createEffectForParticles($, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, _.toString() + `
` + tt, rt == null ? void 0 : rt.fallbacks, s, c, i),
            i.setCustomEffect(d, o)
        }
        d.onBindObservable.add(function(it) {
            _e !== j._buildId && (delete Effect.ShadersStore[$ + "PixelShader"],
            $ = j.name + j._buildId + "_" + o,
            _.markAllAsDirty(),
            _e = j._buildId),
            et.length = 0,
            i.fillDefines(et, o);
            var nt = et.join(`
`);
            nt !== tt && (_.markAllAsDirty(),
            tt = nt);
            var ot = j._processDefines(b, _);
            if (ot) {
                Effect.RegisterShader($, j._fragmentCompilationState._builtCompilationString),
                it = j.getScene().getEngine().createEffectForParticles($, j._fragmentCompilationState.uniforms, j._fragmentCompilationState.samplers, _.toString() + `
` + tt, ot == null ? void 0 : ot.fallbacks, s, c, i),
                i.setCustomEffect(it, o),
                j._createEffectForParticles(i, o, s, c, it, _, b, tt);
                return
            }
            j._checkInternals(it)
        })
    }
    ,
    e.prototype._checkInternals = function(i) {
        if (this._sharedData.animatedInputs) {
            var o = this.getScene()
              , s = o.getFrameId();
            if (this._animationFrame !== s) {
                for (var c = 0, d = this._sharedData.animatedInputs; c < d.length; c++) {
                    var _ = d[c];
                    _.animate(o)
                }
                this._animationFrame = s
            }
        }
        for (var b = 0, k = this._sharedData.bindableBlocks; b < k.length; b++) {
            var j = k[b];
            j.bind(i, this)
        }
        for (var $ = 0, _e = this._sharedData.inputBlocks; $ < _e.length; $++) {
            var et = _e[$];
            et._transmit(i, this.getScene())
        }
    }
    ,
    e.prototype.createEffectForParticles = function(i, o, s) {
        if (this.mode !== NodeMaterialModes.Particle) {
            console.log("Incompatible material mode");
            return
        }
        this._createEffectForParticles(i, BaseParticleSystem.BLENDMODE_ONEONE, o, s),
        this._createEffectForParticles(i, BaseParticleSystem.BLENDMODE_MULTIPLY, o, s)
    }
    ,
    e.prototype._processDefines = function(i, o, s, c) {
        var d = this;
        s === void 0 && (s = !1);
        var _ = null;
        if (this._sharedData.blocksWithDefines.forEach(function(et) {
            et.initializeDefines(i, d, o, s)
        }),
        this._sharedData.blocksWithDefines.forEach(function(et) {
            et.prepareDefines(i, d, o, s, c)
        }),
        o.isDirty) {
            var b = o._areLightsDisposed;
            o.markAsProcessed(),
            this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString,
            this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString,
            this._sharedData.repeatableContentBlocks.forEach(function(et) {
                et.replaceRepeatableContent(d._vertexCompilationState, d._fragmentCompilationState, i, o)
            });
            var k = [];
            this._sharedData.dynamicUniformBlocks.forEach(function(et) {
                et.updateUniformsAndSamples(d._vertexCompilationState, d, o, k)
            });
            var j = this._vertexCompilationState.uniforms;
            this._fragmentCompilationState.uniforms.forEach(function(et) {
                var tt = j.indexOf(et);
                tt === -1 && j.push(et)
            });
            var $ = this._vertexCompilationState.samplers;
            this._fragmentCompilationState.samplers.forEach(function(et) {
                var tt = $.indexOf(et);
                tt === -1 && $.push(et)
            });
            var _e = new EffectFallbacks;
            this._sharedData.blocksWithFallbacks.forEach(function(et) {
                et.provideFallbacks(i, _e)
            }),
            _ = {
                lightDisposed: b,
                uniformBuffers: k,
                mergedUniforms: j,
                mergedSamplers: $,
                fallbacks: _e
            }
        }
        return _
    }
    ,
    e.prototype.isReadyForSubMesh = function(i, o, s) {
        var c = this;
        if (s === void 0 && (s = !1),
        !this._buildWasSuccessful)
            return !1;
        var d = this.getScene();
        if (this._sharedData.animatedInputs) {
            var _ = d.getFrameId();
            if (this._animationFrame !== _) {
                for (var b = 0, k = this._sharedData.animatedInputs; b < k.length; b++) {
                    var j = k[b];
                    j.animate(d)
                }
                this._animationFrame = _
            }
        }
        if (o.effect && this.isFrozen && o.effect._wasPreviouslyReady)
            return !0;
        o.materialDefines || (o.materialDefines = new NodeMaterialDefines);
        var $ = o.materialDefines;
        if (this._isReadyForSubMesh(o))
            return !0;
        var _e = d.getEngine();
        if (this._prepareDefinesForAttributes(i, $),
        this._sharedData.blockingBlocks.some(function(nt) {
            return !nt.isReady(i, c, $, s)
        }))
            return !1;
        var et = this._processDefines(i, $, s, o);
        if (et) {
            var tt = o.effect
              , rt = $.toString()
              , it = _e.createEffect({
                vertex: "nodeMaterial" + this._buildId,
                fragment: "nodeMaterial" + this._buildId,
                vertexSource: this._vertexCompilationState.compilationString,
                fragmentSource: this._fragmentCompilationState.compilationString
            }, {
                attributes: this._vertexCompilationState.attributes,
                uniformsNames: et.mergedUniforms,
                uniformBuffersNames: et.uniformBuffers,
                samplers: et.mergedSamplers,
                defines: rt,
                fallbacks: et.fallbacks,
                onCompiled: this.onCompiled,
                onError: this.onError,
                indexParameters: {
                    maxSimultaneousLights: this.maxSimultaneousLights,
                    maxSimultaneousMorphTargets: $.NUM_MORPH_INFLUENCERS
                }
            }, _e);
            if (it)
                if (this._onEffectCreatedObservable && (onCreatedEffectParameters$1.effect = it,
                onCreatedEffectParameters$1.subMesh = o,
                this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$1)),
                this.allowShaderHotSwapping && tt && !it.isReady()) {
                    if (it = tt,
                    $.markAsUnprocessed(),
                    et.lightDisposed)
                        return $._areLightsDisposed = !0,
                        !1
                } else
                    d.resetCachedMaterial(),
                    o.setEffect(it, $, this._materialContext)
        }
        return !o.effect || !o.effect.isReady() ? !1 : ($._renderId = d.getRenderId(),
        o.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(i) {
        var o = this.getScene();
        if (!!this._activeEffect) {
            var s = this._sharedData.hints;
            s.needWorldViewMatrix && i.multiplyToRef(o.getViewMatrix(), this._cachedWorldViewMatrix),
            s.needWorldViewProjectionMatrix && i.multiplyToRef(o.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
            for (var c = 0, d = this._sharedData.inputBlocks; c < d.length; c++) {
                var _ = d[c];
                _._transmitWorld(this._activeEffect, i, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix)
            }
        }
    }
    ,
    e.prototype.bindForSubMesh = function(i, o, s) {
        var c = this.getScene()
          , d = s.effect;
        if (!!d) {
            this._activeEffect = d,
            this.bindOnlyWorldMatrix(i);
            var _ = this._mustRebind(c, d, o.visibility)
              , b = this._sharedData;
            if (_) {
                if (d) {
                    for (var k = 0, j = b.bindableBlocks; k < j.length; k++) {
                        var $ = j[k];
                        $.bind(d, this, o, s)
                    }
                    for (var _e = 0, et = b.forcedBindableBlocks; _e < et.length; _e++) {
                        var $ = et[_e];
                        $.bind(d, this, o, s)
                    }
                    for (var tt = 0, rt = b.inputBlocks; tt < rt.length; tt++) {
                        var it = rt[tt];
                        it._transmit(d, c)
                    }
                }
            } else if (!this.isFrozen)
                for (var nt = 0, ot = b.forcedBindableBlocks; nt < ot.length; nt++) {
                    var $ = ot[nt];
                    $.bind(d, this, o, s)
                }
            this._afterBind(o, this._activeEffect)
        }
    }
    ,
    e.prototype.getActiveTextures = function() {
        var i = a.prototype.getActiveTextures.call(this);
        return this._sharedData && i.push.apply(i, this._sharedData.textureBlocks.filter(function(o) {
            return o.texture
        }).map(function(o) {
            return o.texture
        })),
        i
    }
    ,
    e.prototype.getTextureBlocks = function() {
        return this._sharedData ? this._sharedData.textureBlocks : []
    }
    ,
    e.prototype.hasTexture = function(i) {
        if (a.prototype.hasTexture.call(this, i))
            return !0;
        if (!this._sharedData)
            return !1;
        for (var o = 0, s = this._sharedData.textureBlocks; o < s.length; o++) {
            var c = s[o];
            if (c.texture === i)
                return !0
        }
        return !1
    }
    ,
    e.prototype.dispose = function(i, o, s) {
        if (o && this._sharedData)
            for (var c = 0, d = this._sharedData.textureBlocks.filter(function($) {
                return $.texture
            }).map(function($) {
                return $.texture
            }); c < d.length; c++) {
                var _ = d[c];
                _.dispose()
            }
        for (var b = 0, k = this.attachedBlocks; b < k.length; b++) {
            var j = k[b];
            j.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),
        a.prototype.dispose.call(this, i, o, s)
    }
    ,
    e.prototype._createNodeEditor = function() {
        this.BJSNODEMATERIALEDITOR.NodeEditor.Show({
            nodeMaterial: this
        })
    }
    ,
    e.prototype.edit = function(i) {
        var o = this;
        return new Promise(function(s, c) {
            if (o.BJSNODEMATERIALEDITOR = o.BJSNODEMATERIALEDITOR || o._getGlobalNodeMaterialEditor(),
            typeof o.BJSNODEMATERIALEDITOR == "undefined") {
                var d = i && i.editorURL ? i.editorURL : e.EditorURL;
                Tools.LoadScript(d, function() {
                    o.BJSNODEMATERIALEDITOR = o.BJSNODEMATERIALEDITOR || o._getGlobalNodeMaterialEditor(),
                    o._createNodeEditor(),
                    s()
                })
            } else
                o._createNodeEditor(),
                s()
        }
        )
    }
    ,
    e.prototype.clear = function() {
        this._vertexOutputNodes = [],
        this._fragmentOutputNodes = [],
        this.attachedBlocks = []
    }
    ,
    e.prototype.setToDefault = function() {
        this.clear(),
        this.editorData = null;
        var i = new InputBlock("Position");
        i.setAsAttribute("position");
        var o = new InputBlock("World");
        o.setAsSystemValue(NodeMaterialSystemValues.World);
        var s = new TransformBlock("WorldPos");
        i.connectTo(s),
        o.connectTo(s);
        var c = new InputBlock("ViewProjection");
        c.setAsSystemValue(NodeMaterialSystemValues.ViewProjection);
        var d = new TransformBlock("WorldPos * ViewProjectionTransform");
        s.connectTo(d),
        c.connectTo(d);
        var _ = new VertexOutputBlock("VertexOutput");
        d.connectTo(_);
        var b = new InputBlock("color");
        b.value = new Color4(.8,.8,.8,1);
        var k = new FragmentOutputBlock("FragmentOutput");
        b.connectTo(k),
        this.addOutputNode(_),
        this.addOutputNode(k),
        this._mode = NodeMaterialModes.Material
    }
    ,
    e.prototype.setToDefaultPostProcess = function() {
        this.clear(),
        this.editorData = null;
        var i = new InputBlock("Position");
        i.setAsAttribute("position2d");
        var o = new InputBlock("Constant1");
        o.isConstant = !0,
        o.value = 1;
        var s = new VectorMergerBlock("Position3D");
        i.connectTo(s),
        o.connectTo(s, {
            input: "w"
        });
        var c = new VertexOutputBlock("VertexOutput");
        s.connectTo(c);
        var d = new InputBlock("Scale");
        d.visibleInInspector = !0,
        d.value = new Vector2(1,1);
        var _ = new RemapBlock("uv0");
        i.connectTo(_);
        var b = new MultiplyBlock("UV scale");
        _.connectTo(b),
        d.connectTo(b);
        var k = new CurrentScreenBlock("CurrentScreen");
        b.connectTo(k),
        k.texture = new Texture("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());
        var j = new FragmentOutputBlock("FragmentOutput");
        k.connectTo(j, {
            output: "rgba"
        }),
        this.addOutputNode(c),
        this.addOutputNode(j),
        this._mode = NodeMaterialModes.PostProcess
    }
    ,
    e.prototype.setToDefaultProceduralTexture = function() {
        this.clear(),
        this.editorData = null;
        var i = new InputBlock("Position");
        i.setAsAttribute("position2d");
        var o = new InputBlock("Constant1");
        o.isConstant = !0,
        o.value = 1;
        var s = new VectorMergerBlock("Position3D");
        i.connectTo(s),
        o.connectTo(s, {
            input: "w"
        });
        var c = new VertexOutputBlock("VertexOutput");
        s.connectTo(c);
        var d = new InputBlock("Time");
        d.value = 0,
        d.min = 0,
        d.max = 0,
        d.isBoolean = !1,
        d.matrixMode = 0,
        d.animationType = AnimatedInputBlockTypes.Time,
        d.isConstant = !1;
        var _ = new InputBlock("Color3");
        _.value = new Color3(1,1,1),
        _.isConstant = !1;
        var b = new FragmentOutputBlock("FragmentOutput")
          , k = new VectorMergerBlock("VectorMerger");
        k.visibleInInspector = !1;
        var j = new TrigonometryBlock("Cos");
        j.operation = TrigonometryBlockOperations.Cos,
        i.connectTo(k),
        d.output.connectTo(j.input),
        j.output.connectTo(k.z),
        k.xyzOut.connectTo(b.rgb),
        this.addOutputNode(c),
        this.addOutputNode(b),
        this._mode = NodeMaterialModes.ProceduralTexture
    }
    ,
    e.prototype.setToDefaultParticle = function() {
        this.clear(),
        this.editorData = null;
        var i = new InputBlock("uv");
        i.setAsAttribute("particle_uv");
        var o = new ParticleTextureBlock("ParticleTexture");
        i.connectTo(o);
        var s = new InputBlock("Color");
        s.setAsAttribute("particle_color");
        var c = new MultiplyBlock("Texture * Color");
        o.connectTo(c),
        s.connectTo(c);
        var d = new ParticleRampGradientBlock("ParticleRampGradient");
        c.connectTo(d);
        var _ = new ColorSplitterBlock("ColorSplitter");
        s.connectTo(_);
        var b = new ParticleBlendMultiplyBlock("ParticleBlendMultiply");
        d.connectTo(b),
        o.connectTo(b, {
            output: "a"
        }),
        _.connectTo(b, {
            output: "a"
        });
        var k = new FragmentOutputBlock("FragmentOutput");
        b.connectTo(k),
        this.addOutputNode(k),
        this._mode = NodeMaterialModes.Particle
    }
    ,
    e.prototype.loadAsync = function(i) {
        var o = this;
        return this.getScene()._loadFileAsync(i).then(function(s) {
            var c = JSON.parse(s);
            o.loadFromSerialization(c, "")
        })
    }
    ,
    e.prototype._gatherBlocks = function(i, o) {
        if (o.indexOf(i) === -1) {
            o.push(i);
            for (var s = 0, c = i.inputs; s < c.length; s++) {
                var d = c[s]
                  , _ = d.connectedPoint;
                if (_) {
                    var b = _.ownerBlock;
                    b !== i && this._gatherBlocks(b, o)
                }
            }
        }
    }
    ,
    e.prototype.generateCode = function() {
        for (var i = [], o = [], s = ["const", "var", "let"], c = 0, d = this._vertexOutputNodes; c < d.length; c++) {
            var _ = d[c];
            this._gatherBlocks(_, o)
        }
        for (var b = [], k = 0, j = this._fragmentOutputNodes; k < j.length; k++) {
            var _ = j[k];
            this._gatherBlocks(_, b)
        }
        for (var $ = 'var nodeMaterial = new BABYLON.NodeMaterial("' + (this.name || "node material") + `");\r
`, _e = 0, et = o; _e < et.length; _e++) {
            var tt = et[_e];
            tt.isInput && i.indexOf(tt) === -1 && ($ += tt._dumpCode(s, i))
        }
        for (var rt = 0, it = b; rt < it.length; rt++) {
            var tt = it[rt];
            tt.isInput && i.indexOf(tt) === -1 && ($ += tt._dumpCode(s, i))
        }
        i = [],
        $ += `\r
// Connections\r
`;
        for (var nt = 0, ot = this._vertexOutputNodes; nt < ot.length; nt++) {
            var tt = ot[nt];
            $ += tt._dumpCodeForOutputConnections(i)
        }
        for (var at = 0, st = this._fragmentOutputNodes; at < st.length; at++) {
            var tt = st[at];
            $ += tt._dumpCodeForOutputConnections(i)
        }
        $ += `\r
// Output nodes\r
`;
        for (var ut = 0, ct = this._vertexOutputNodes; ut < ct.length; ut++) {
            var tt = ct[ut];
            $ += "nodeMaterial.addOutputNode(" + tt._codeVariableName + `);\r
`
        }
        for (var lt = 0, ft = this._fragmentOutputNodes; lt < ft.length; lt++) {
            var tt = ft[lt];
            $ += "nodeMaterial.addOutputNode(" + tt._codeVariableName + `);\r
`
        }
        return $ += `nodeMaterial.build();\r
`,
        $
    }
    ,
    e.prototype.serialize = function(i) {
        var o = i ? {} : SerializationHelper.Serialize(this);
        o.editorData = JSON.parse(JSON.stringify(this.editorData));
        var s = [];
        if (i)
            s = i;
        else {
            o.customType = "BABYLON.NodeMaterial",
            o.outputNodes = [];
            for (var c = 0, d = this._vertexOutputNodes; c < d.length; c++) {
                var _ = d[c];
                this._gatherBlocks(_, s),
                o.outputNodes.push(_.uniqueId)
            }
            for (var b = 0, k = this._fragmentOutputNodes; b < k.length; b++) {
                var _ = k[b];
                this._gatherBlocks(_, s),
                o.outputNodes.indexOf(_.uniqueId) === -1 && o.outputNodes.push(_.uniqueId)
            }
        }
        o.blocks = [];
        for (var j = 0, $ = s; j < $.length; j++) {
            var _e = $[j];
            o.blocks.push(_e.serialize())
        }
        if (!i)
            for (var et = 0, tt = this.attachedBlocks; et < tt.length; et++) {
                var _e = tt[et];
                s.indexOf(_e) === -1 && o.blocks.push(_e.serialize())
            }
        return o
    }
    ,
    e.prototype._restoreConnections = function(i, o, s) {
        for (var c = 0, d = i.outputs; c < d.length; c++)
            for (var _ = d[c], b = 0, k = o.blocks; b < k.length; b++) {
                var j = k[b]
                  , $ = s[j.id];
                if (!!$)
                    for (var _e = 0, et = j.inputs; _e < et.length; _e++) {
                        var tt = et[_e];
                        if (s[tt.targetBlockId] === i && tt.targetConnectionName === _.name) {
                            var rt = $.getInputByName(tt.inputName);
                            if (!rt || rt.isConnected)
                                continue;
                            _.connectTo(rt, !0),
                            this._restoreConnections($, o, s);
                            continue
                        }
                    }
            }
    }
    ,
    e.prototype.loadFromSerialization = function(i, o, s) {
        var c;
        o === void 0 && (o = ""),
        s === void 0 && (s = !1),
        s || this.clear();
        for (var d = {}, _ = 0, b = i.blocks; _ < b.length; _++) {
            var k = b[_]
              , j = GetClass(k.customType);
            if (j) {
                var $ = new j;
                $._deserialize(k, this.getScene(), o),
                d[k.id] = $,
                this.attachedBlocks.push($)
            }
        }
        for (var _e = 0; _e < i.blocks.length; _e++) {
            var et = i.blocks[_e]
              , $ = d[et.id];
            !$ || $.inputs.length && !s || this._restoreConnections($, i, d)
        }
        if (i.outputNodes)
            for (var tt = 0, rt = i.outputNodes; tt < rt.length; tt++) {
                var it = rt[tt];
                this.addOutputNode(d[it])
            }
        if (i.locations || i.editorData && i.editorData.locations) {
            for (var nt = i.locations || i.editorData.locations, ot = 0, at = nt; ot < at.length; ot++) {
                var st = at[ot];
                d[st.blockId] && (st.blockId = d[st.blockId].uniqueId)
            }
            s && this.editorData && this.editorData.locations && nt.concat(this.editorData.locations),
            i.locations ? this.editorData = {
                locations: nt
            } : (this.editorData = i.editorData,
            this.editorData.locations = nt);
            var ut = [];
            for (var ct in d)
                ut[ct] = d[ct].uniqueId;
            this.editorData.map = ut
        }
        this.comment = i.comment,
        s || (this._mode = (c = i.mode) !== null && c !== void 0 ? c : NodeMaterialModes.Material)
    }
    ,
    e.prototype.clone = function(i, o) {
        var s = this;
        o === void 0 && (o = !1);
        var c = this.serialize()
          , d = SerializationHelper.Clone(function() {
            return new e(i,s.getScene(),s.options)
        }, this);
        return d.id = i,
        d.name = i,
        d.loadFromSerialization(c),
        d._buildId = this._buildId,
        d.build(!1, !o),
        d
    }
    ,
    e.Parse = function(i, o, s) {
        s === void 0 && (s = "");
        var c = SerializationHelper.Parse(function() {
            return new e(i.name,o)
        }, i, o, s);
        return c.loadFromSerialization(i, s),
        c.build(),
        c
    }
    ,
    e.ParseFromFileAsync = function(i, o, s) {
        var c = new e(i,s);
        return new Promise(function(d, _) {
            return c.loadAsync(o).then(function() {
                c.build(),
                d(c)
            }).catch(_)
        }
        )
    }
    ,
    e.ParseFromSnippetAsync = function(i, o, s, c) {
        var d = this;
        return s === void 0 && (s = ""),
        i === "_BLANK" ? Promise.resolve(this.CreateDefault("blank", o)) : new Promise(function(_, b) {
            var k = new WebRequest;
            k.addEventListener("readystatechange", function() {
                if (k.readyState == 4)
                    if (k.status == 200) {
                        var j = JSON.parse(JSON.parse(k.responseText).jsonPayload)
                          , $ = JSON.parse(j.nodeMaterial);
                        c || (c = SerializationHelper.Parse(function() {
                            return new e(i,o)
                        }, $, o, s),
                        c.uniqueId = o.getUniqueId()),
                        c.loadFromSerialization($),
                        c.snippetId = i;
                        try {
                            c.build(),
                            _(c)
                        } catch (_e) {
                            b(_e)
                        }
                    } else
                        b("Unable to load the snippet " + i)
            }),
            k.open("GET", d.SnippetUrl + "/" + i.replace(/#/g, "/")),
            k.send()
        }
        )
    }
    ,
    e.CreateDefault = function(i, o) {
        var s = new e(i,o);
        return s.setToDefault(),
        s.build(),
        s
    }
    ,
    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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Vertex) || this;
        return o.registerInput("matricesIndices", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("matricesWeights", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("matricesIndicesExtra", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        o.registerInput("matricesWeightsExtra", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        o.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    return e.prototype.initialize = function(i) {
        i._excludeVariableName("boneSampler"),
        i._excludeVariableName("boneTextureWidth"),
        i._excludeVariableName("mBones"),
        i._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(i) {
        if (!this.matricesIndices.isConnected) {
            var o = i.getInputBlockByPredicate(function(d) {
                return d.isAttribute && d.name === "matricesIndices"
            });
            o || (o = new InputBlock("matricesIndices"),
            o.setAsAttribute("matricesIndices")),
            o.output.connectTo(this.matricesIndices)
        }
        if (!this.matricesWeights.isConnected) {
            var s = i.getInputBlockByPredicate(function(d) {
                return d.isAttribute && d.name === "matricesWeights"
            });
            s || (s = new InputBlock("matricesWeights"),
            s.setAsAttribute("matricesWeights")),
            s.output.connectTo(this.matricesWeights)
        }
        if (!this.world.isConnected) {
            var c = i.getInputBlockByPredicate(function(d) {
                return d.systemValue === NodeMaterialSystemValues.World
            });
            c || (c = new InputBlock("world"),
            c.setAsSystemValue(NodeMaterialSystemValues.World)),
            c.output.connectTo(this.world)
        }
    }
    ,
    e.prototype.provideFallbacks = function(i, o) {
        i && i.useBones && i.computeBonesUsingShaders && i.skeleton && o.addCPUSkinningFallback(0, i)
    }
    ,
    e.prototype.bind = function(i, o, s) {
        MaterialHelper.BindBonesParameters(s, i)
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        !s._areAttributesDirty || MaterialHelper.PrepareDefinesForBones(i, s)
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i),
        i.sharedData.blocksWithFallbacks.push(this),
        i.sharedData.bindableBlocks.push(this),
        i.sharedData.blocksWithDefines.push(this),
        i.uniforms.push("boneTextureWidth"),
        i.uniforms.push("mBones"),
        i.samplers.push("boneSampler");
        var o = "//" + this.name;
        i._emitFunctionFromInclude("bonesDeclaration", o, {
            removeAttributes: !0,
            removeUniforms: !1,
            removeVaryings: !0,
            removeIfDef: !1
        });
        var s = i._getFreeVariableName("influence");
        i.compilationString += i._emitCodeFromInclude("bonesVertex", o, {
            replaceStrings: [{
                search: /finalWorld=finalWorld\*influence;/,
                replace: ""
            }, {
                search: /influence/gm,
                replace: s
            }]
        });
        var c = this._outputs[0]
          , d = this.world;
        return i.compilationString += `#if NUM_BONE_INFLUENCERS>0\r
`,
        i.compilationString += this._declareOutput(c, i) + (" = " + d.associatedVariableName + " * " + s + `;\r
`),
        i.compilationString += `#else\r
`,
        i.compilationString += this._declareOutput(c, i) + (" = " + d.associatedVariableName + `;\r
`),
        i.compilationString += `#endif\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.BonesBlock", BonesBlock);
var InstancesBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Vertex) || this;
        return o.registerInput("world0", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("world1", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("world2", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("world3", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, !0),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix),
        o.registerOutput("instanceID", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        if (!this.world0.connectedPoint) {
            var o = i.getInputBlockByPredicate(function(b) {
                return b.isAttribute && b.name === "world0"
            });
            o || (o = new InputBlock("world0"),
            o.setAsAttribute("world0")),
            o.output.connectTo(this.world0)
        }
        if (!this.world1.connectedPoint) {
            var s = i.getInputBlockByPredicate(function(b) {
                return b.isAttribute && b.name === "world1"
            });
            s || (s = new InputBlock("world1"),
            s.setAsAttribute("world1")),
            s.output.connectTo(this.world1)
        }
        if (!this.world2.connectedPoint) {
            var c = i.getInputBlockByPredicate(function(b) {
                return b.isAttribute && b.name === "world2"
            });
            c || (c = new InputBlock("world2"),
            c.setAsAttribute("world2")),
            c.output.connectTo(this.world2)
        }
        if (!this.world3.connectedPoint) {
            var d = i.getInputBlockByPredicate(function(b) {
                return b.isAttribute && b.name === "world3"
            });
            d || (d = new InputBlock("world3"),
            d.setAsAttribute("world3")),
            d.output.connectTo(this.world3)
        }
        if (!this.world.connectedPoint) {
            var _ = i.getInputBlockByPredicate(function(b) {
                return b.isAttribute && b.name === "world"
            });
            _ || (_ = new InputBlock("world"),
            _.setAsSystemValue(NodeMaterialSystemValues.World)),
            _.output.connectTo(this.world)
        }
        this.world.define = "!INSTANCES || THIN_INSTANCES"
    }
    ,
    e.prototype.prepareDefines = function(i, o, s, c, d) {
        c === void 0 && (c = !1);
        var _ = !1;
        s.INSTANCES !== c && (s.setValue("INSTANCES", c),
        _ = !0),
        d && s.THIN_INSTANCES !== !!(d != null && d.getRenderingMesh().hasThinInstances) && (s.setValue("THIN_INSTANCES", !!(d != null && d.getRenderingMesh().hasThinInstances)),
        _ = !0),
        _ && s.markAsUnprocessed()
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = i.sharedData.scene.getEngine();
        i.sharedData.blocksWithDefines.push(this);
        var s = this._outputs[0]
          , c = this._outputs[1]
          , d = this.world0
          , _ = this.world1
          , b = this.world2
          , k = this.world3;
        return i.compilationString += `#ifdef INSTANCES\r
`,
        i.compilationString += this._declareOutput(s, i) + (" = mat4(" + d.associatedVariableName + ", " + _.associatedVariableName + ", " + b.associatedVariableName + ", " + k.associatedVariableName + `);\r
`),
        i.compilationString += `#ifdef THIN_INSTANCES\r
`,
        i.compilationString += s.associatedVariableName + " = " + this.world.associatedVariableName + " * " + s.associatedVariableName + `;\r
`,
        i.compilationString += `#endif\r
`,
        o._caps.canUseGLInstanceID ? i.compilationString += this._declareOutput(c, i) + ` = float(gl_InstanceID);\r
` : i.compilationString += this._declareOutput(c, i) + ` = 0.0;\r
`,
        i.compilationString += `#else\r
`,
        i.compilationString += this._declareOutput(s, i) + (" = " + this.world.associatedVariableName + `;\r
`),
        i.compilationString += this._declareOutput(c, i) + ` = 0.0;\r
`,
        i.compilationString += `#endif\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.InstancesBlock", InstancesBlock);
var MorphTargetsBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Vertex) || this;
        return o.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("tangent", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("positionOutput", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("normalOutput", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("tangentOutput", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("uvOutput", NodeMaterialBlockConnectionPointTypes.Vector2),
        o
    }
    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(i) {
        i._excludeVariableName("morphTargetInfluences")
    }
    ,
    e.prototype.autoConfigure = function(i) {
        if (!this.position.isConnected) {
            var o = i.getInputBlockByPredicate(function(_) {
                return _.isAttribute && _.name === "position"
            });
            o || (o = new InputBlock("position"),
            o.setAsAttribute()),
            o.output.connectTo(this.position)
        }
        if (!this.normal.isConnected) {
            var s = i.getInputBlockByPredicate(function(_) {
                return _.isAttribute && _.name === "normal"
            });
            s || (s = new InputBlock("normal"),
            s.setAsAttribute("normal")),
            s.output.connectTo(this.normal)
        }
        if (!this.tangent.isConnected) {
            var c = i.getInputBlockByPredicate(function(_) {
                return _.isAttribute && _.name === "tangent"
            });
            c || (c = new InputBlock("tangent"),
            c.setAsAttribute("tangent")),
            c.output.connectTo(this.tangent)
        }
        if (!this.uv.isConnected) {
            var d = i.getInputBlockByPredicate(function(_) {
                return _.isAttribute && _.name === "uv"
            });
            d || (d = new InputBlock("uv"),
            d.setAsAttribute("uv")),
            d.output.connectTo(this.uv)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        if (i.morphTargetManager) {
            var c = i.morphTargetManager;
            (c == null ? void 0 : c.isUsingTextureForTargets) && c.numInfluencers !== s.NUM_MORPH_INFLUENCERS && s.markAsAttributesDirty()
        }
        !s._areAttributesDirty || MaterialHelper.PrepareDefinesForMorphTargets(i, s)
    }
    ,
    e.prototype.bind = function(i, o, s) {
        s && s.morphTargetManager && s.morphTargetManager.numInfluencers > 0 && (MaterialHelper.BindMorphTargetParameters(s, i),
        s.morphTargetManager.isUsingTextureForTargets && s.morphTargetManager._bind(i))
    }
    ,
    e.prototype.replaceRepeatableContent = function(i, o, s, c) {
        var d = this.position
          , _ = this.normal
          , b = this.tangent
          , k = this.uv
          , j = this.positionOutput
          , $ = this.normalOutput
          , _e = this.tangentOutput
          , et = this.uvOutput
          , tt = i
          , rt = c.NUM_MORPH_INFLUENCERS
          , it = s.morphTargetManager
          , nt = it && it.supportsNormals && c.NORMAL
          , ot = it && it.supportsTangents && c.TANGENT
          , at = it && it.supportsUVs && c.UV1
          , st = "";
        (it == null ? void 0 : it.isUsingTextureForTargets) && rt > 0 && (st += `float vertexID;\r
`);
        for (var ut = 0; ut < rt; ut++)
            st += `#ifdef MORPHTARGETS\r
`,
            it != null && it.isUsingTextureForTargets ? (st += `vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\r
`,
            st += j.associatedVariableName + " += (readVector3FromRawSampler(" + ut + ", vertexID) - " + d.associatedVariableName + ") * morphTargetInfluences[" + ut + `];\r
`,
            st += `vertexID += 1.0;\r
`) : st += j.associatedVariableName + " += (position" + ut + " - " + d.associatedVariableName + ") * morphTargetInfluences[" + ut + `];\r
`,
            nt && (st += `#ifdef MORPHTARGETS_NORMAL\r
`,
            it != null && it.isUsingTextureForTargets ? (st += $.associatedVariableName + " += (readVector3FromRawSampler(" + ut + ", vertexID) - " + _.associatedVariableName + ") * morphTargetInfluences[" + ut + `];\r
`,
            st += `vertexID += 1.0;\r
`) : st += $.associatedVariableName + " += (normal" + ut + " - " + _.associatedVariableName + ") * morphTargetInfluences[" + ut + `];\r
`,
            st += `#endif\r
`),
            at && (st += `#ifdef MORPHTARGETS_UV\r
`,
            it != null && it.isUsingTextureForTargets ? (st += et.associatedVariableName + " += (readVector3FromRawSampler(" + ut + ", vertexID).xy - " + k.associatedVariableName + ") * morphTargetInfluences[" + ut + `];\r
`,
            st += `vertexID += 1.0;\r
`) : st += et.associatedVariableName + ".xy += (uv_" + ut + " - " + k.associatedVariableName + ".xy) * morphTargetInfluences[" + ut + `];\r
`,
            st += `#endif\r
`),
            ot && (st += `#ifdef MORPHTARGETS_TANGENT\r
`,
            it != null && it.isUsingTextureForTargets ? st += _e.associatedVariableName + " += (readVector3FromRawSampler(" + ut + ", vertexID) - " + b.associatedVariableName + ") * morphTargetInfluences[" + ut + `];\r
` : st += _e.associatedVariableName + ".xyz += (tangent" + ut + " - " + b.associatedVariableName + ".xyz) * morphTargetInfluences[" + ut + `];\r
`,
            st += `#endif\r
`),
            st += `#endif\r
`;
        if (tt.compilationString = tt.compilationString.replace(this._repeatableContentAnchor, st),
        rt > 0)
            for (var ut = 0; ut < rt; ut++)
                tt.attributes.push(VertexBuffer.PositionKind + ut),
                nt && tt.attributes.push(VertexBuffer.NormalKind + ut),
                ot && tt.attributes.push(VertexBuffer.TangentKind + ut),
                at && tt.attributes.push(VertexBuffer.UVKind + "_" + ut)
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i),
        i.sharedData.blocksWithDefines.push(this),
        i.sharedData.bindableBlocks.push(this),
        i.sharedData.repeatableContentBlocks.push(this);
        var o = this.position
          , s = this.normal
          , c = this.tangent
          , d = this.uv
          , _ = this.positionOutput
          , b = this.normalOutput
          , k = this.tangentOutput
          , j = this.uvOutput
          , $ = "//" + this.name;
        return i.uniforms.push("morphTargetInfluences"),
        i.uniforms.push("morphTargetTextureInfo"),
        i.uniforms.push("morphTargetTextureIndices"),
        i.samplers.push("morphTargets"),
        i._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration", $),
        i._emitFunctionFromInclude("morphTargetsVertexDeclaration", $, {
            repeatKey: "maxSimultaneousMorphTargets"
        }),
        i.compilationString += this._declareOutput(_, i) + " = " + o.associatedVariableName + `;\r
`,
        i.compilationString += `#ifdef NORMAL\r
`,
        i.compilationString += this._declareOutput(b, i) + " = " + s.associatedVariableName + `;\r
`,
        i.compilationString += `#else\r
`,
        i.compilationString += this._declareOutput(b, i) + ` = vec3(0., 0., 0.);\r
`,
        i.compilationString += `#endif\r
`,
        i.compilationString += `#ifdef TANGENT\r
`,
        i.compilationString += this._declareOutput(k, i) + " = " + c.associatedVariableName + `;\r
`,
        i.compilationString += `#else\r
`,
        i.compilationString += this._declareOutput(k, i) + ` = vec3(0., 0., 0.);\r
`,
        i.compilationString += `#endif\r
`,
        i.compilationString += `#ifdef UV1\r
`,
        i.compilationString += this._declareOutput(j, i) + " = " + d.associatedVariableName + `;\r
`,
        i.compilationString += `#else\r
`,
        i.compilationString += this._declareOutput(j, i) + ` = vec2(0., 0.);\r
`,
        i.compilationString += `#endif\r
`,
        this._repeatableContentAnchor = i._repeatableContentAnchor,
        i.compilationString += this._repeatableContentAnchor,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MorphTargetsBlock", MorphTargetsBlock);
var LightInformationBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Vertex) || this;
        return o.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        o.registerOutput("direction", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("color", NodeMaterialBlockConnectionPointTypes.Color3),
        o.registerOutput("intensity", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i, o, s) {
        if (!!s) {
            this.light && this.light.isDisposed && (this.light = null);
            var c = this.light
              , d = o.getScene();
            if (!c && d.lights.length && (c = this.light = d.lights[0],
            this._forcePrepareDefines = !0),
            !c || !c.isEnabled) {
                i.setFloat3(this._lightDataUniformName, 0, 0, 0),
                i.setFloat4(this._lightColorUniformName, 0, 0, 0, 0);
                return
            }
            c.transferToNodeMaterialEffect(i, this._lightDataUniformName),
            i.setColor4(this._lightColorUniformName, c.diffuse, c.intensity)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        if (!(!s._areLightsDirty && !this._forcePrepareDefines)) {
            this._forcePrepareDefines = !1;
            var c = this.light;
            s.setValue(this._lightTypeDefineName, !!(c && c instanceof PointLight), !0)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i),
        i.sharedData.bindableBlocks.push(this),
        i.sharedData.blocksWithDefines.push(this);
        var o = this.direction
          , s = this.color
          , c = this.intensity;
        return this._lightDataUniformName = i._getFreeVariableName("lightData"),
        this._lightColorUniformName = i._getFreeVariableName("lightColor"),
        this._lightTypeDefineName = i._getFreeDefineName("LIGHTPOINTTYPE"),
        i._emitUniformFromString(this._lightDataUniformName, "vec3"),
        i._emitUniformFromString(this._lightColorUniformName, "vec4"),
        i.compilationString += "#ifdef " + this._lightTypeDefineName + `\r
`,
        i.compilationString += this._declareOutput(o, i) + (" = normalize(" + this.worldPosition.associatedVariableName + ".xyz - " + this._lightDataUniformName + `);\r
`),
        i.compilationString += `#else\r
`,
        i.compilationString += this._declareOutput(o, i) + (" = " + this._lightDataUniformName + `;\r
`),
        i.compilationString += `#endif\r
`,
        i.compilationString += this._declareOutput(s, i) + (" = " + this._lightColorUniformName + `.rgb;\r
`),
        i.compilationString += this._declareOutput(c, i) + (" = " + this._lightColorUniformName + `.a;\r
`),
        this
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return this.light && (i.lightId = this.light.id),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        i.lightId && (this.light = o.getLightById(i.lightId))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.LightInformationBlock", LightInformationBlock);
var ImageProcessingBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.convertInputToLinearSpace = !0,
        o.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color4),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o
    }
    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(i) {
        i._excludeVariableName("exposureLinear"),
        i._excludeVariableName("contrast"),
        i._excludeVariableName("vInverseScreenSize"),
        i._excludeVariableName("vignetteSettings1"),
        i._excludeVariableName("vignetteSettings2"),
        i._excludeVariableName("vCameraColorCurveNegative"),
        i._excludeVariableName("vCameraColorCurveNeutral"),
        i._excludeVariableName("vCameraColorCurvePositive"),
        i._excludeVariableName("txColorTransform"),
        i._excludeVariableName("colorTransformSettings")
    }
    ,
    e.prototype.isReady = function(i, o, s) {
        return !(s._areImageProcessingDirty && o.imageProcessingConfiguration && !o.imageProcessingConfiguration.isReady())
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        s._areImageProcessingDirty && o.imageProcessingConfiguration && o.imageProcessingConfiguration.prepareDefines(s)
    }
    ,
    e.prototype.bind = function(i, o, s) {
        !s || !o.imageProcessingConfiguration || o.imageProcessingConfiguration.bind(i)
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i),
        i.sharedData.blocksWithDefines.push(this),
        i.sharedData.blockingBlocks.push(this),
        i.sharedData.bindableBlocks.push(this),
        i.uniforms.push("exposureLinear"),
        i.uniforms.push("contrast"),
        i.uniforms.push("vInverseScreenSize"),
        i.uniforms.push("vignetteSettings1"),
        i.uniforms.push("vignetteSettings2"),
        i.uniforms.push("vCameraColorCurveNegative"),
        i.uniforms.push("vCameraColorCurveNeutral"),
        i.uniforms.push("vCameraColorCurvePositive"),
        i.uniforms.push("txColorTransform"),
        i.uniforms.push("colorTransformSettings");
        var o = this.color
          , s = this._outputs[0]
          , c = "//" + this.name;
        return i._emitFunctionFromInclude("helperFunctions", c),
        i._emitFunctionFromInclude("imageProcessingDeclaration", c),
        i._emitFunctionFromInclude("imageProcessingFunctions", c),
        o.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color4 || o.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? i.compilationString += this._declareOutput(s, i) + " = " + o.associatedVariableName + `;\r
` : i.compilationString += this._declareOutput(s, i) + " = vec4(" + o.associatedVariableName + `, 1.0);\r
`,
        i.compilationString += `#ifdef IMAGEPROCESSINGPOSTPROCESS\r
`,
        this.convertInputToLinearSpace && (i.compilationString += s.associatedVariableName + ".rgb = toLinearSpace(" + o.associatedVariableName + `.rgb);\r
`),
        i.compilationString += `#else\r
`,
        i.compilationString += `#ifdef IMAGEPROCESSING\r
`,
        this.convertInputToLinearSpace && (i.compilationString += s.associatedVariableName + ".rgb = toLinearSpace(" + o.associatedVariableName + `.rgb);\r
`),
        i.compilationString += s.associatedVariableName + " = applyImageProcessing(" + s.associatedVariableName + `);\r
`,
        i.compilationString += `#endif\r
`,
        i.compilationString += `#endif\r
`,
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return i += this._codeVariableName + ".convertInputToLinearSpace = " + this.convertInputToLinearSpace + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.convertInputToLinearSpace = this.convertInputToLinearSpace,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        var c;
        a.prototype._deserialize.call(this, i, o, s),
        this.convertInputToLinearSpace = (c = i.convertInputToLinearSpace) !== null && c !== void 0 ? c : !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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o._tangentSpaceParameterName = "",
        o.invertX = !1,
        o.invertY = !1,
        o.useParallaxOcclusion = !1,
        o._isUnique = !0,
        o.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1),
        o.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, !1),
        o.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        o.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1),
        o.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, !1),
        o.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float, !1),
        o.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3, !0),
        o.registerInput("parallaxScale", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("parallaxHeight", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerOutput("uvOffset", NodeMaterialBlockConnectionPointTypes.Vector2),
        o
    }
    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(i, o, s) {
        var c = this.normalMapColor.connectedPoint._ownerBlock.samplerName
          , d = this.viewDirection.isConnected && (this.useParallaxOcclusion && c || !this.useParallaxOcclusion && this.parallaxHeight.isConnected);
        s.setValue("BUMP", !0),
        s.setValue("PARALLAX", d, !0),
        s.setValue("PARALLAXOCCLUSION", this.useParallaxOcclusion, !0)
    }
    ,
    e.prototype.bind = function(i, o, s) {
        o.getScene()._mirroredCameraPosition ? i.setFloat2(this._tangentSpaceParameterName, this.invertX ? 1 : -1, this.invertY ? 1 : -1) : i.setFloat2(this._tangentSpaceParameterName, this.invertX ? -1 : 1, this.invertY ? -1 : 1)
    }
    ,
    e.prototype.autoConfigure = function(i) {
        if (!this.uv.isConnected) {
            var o = i.getInputBlockByPredicate(function(c) {
                return c.isAttribute && c.name === "uv"
            });
            o || (o = new InputBlock("uv"),
            o.setAsAttribute()),
            o.output.connectTo(this.uv)
        }
        if (!this.strength.isConnected) {
            var s = new InputBlock("strength");
            s.value = 1,
            s.output.connectTo(this.strength)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = "//" + this.name
          , s = this.uv
          , c = this.worldPosition
          , d = this.worldNormal
          , _ = this.worldTangent;
        i.sharedData.blocksWithDefines.push(this),
        i.sharedData.bindableBlocks.push(this),
        this._tangentSpaceParameterName = i._getFreeDefineName("tangentSpaceParameter"),
        i._emitUniformFromString(this._tangentSpaceParameterName, "vec2");
        var b = this.normalMapColor.connectedPoint._ownerBlock.samplerName
          , k = this.viewDirection.isConnected && (this.useParallaxOcclusion && b || !this.useParallaxOcclusion && this.parallaxHeight.isConnected)
          , j = this.parallaxScale.isConnectedToInputBlock ? this.parallaxScale.connectInputBlock.isConstant ? i._emitFloat(this.parallaxScale.connectInputBlock.value) : this.parallaxScale.associatedVariableName : "0.05"
          , $ = this.strength.isConnectedToInputBlock && this.strength.connectInputBlock.isConstant ? `\r
#if !defined(NORMALXYSCALE)\r
1.0/\r
#endif\r
` + i._emitFloat(this.strength.connectInputBlock.value) : `\r
#if !defined(NORMALXYSCALE)\r
1.0/\r
#endif\r
` + this.strength.associatedVariableName;
        i._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
        var _e = {
            search: /defined\(TANGENT\)/g,
            replace: _.isConnected ? "defined(TANGENT)" : "defined(IGNORE)"
        };
        _.isConnected && (i.compilationString += "vec3 tbnNormal = normalize(" + d.associatedVariableName + `.xyz);\r
`,
        i.compilationString += "vec3 tbnTangent = normalize(" + _.associatedVariableName + `.xyz);\r
`,
        i.compilationString += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r
`,
        i.compilationString += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r
`),
        i._emitFunctionFromInclude("bumpFragmentMainFunctions", o, {
            replaceStrings: [_e]
        }),
        i._emitFunctionFromInclude("bumpFragmentFunctions", o, {
            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 et = !k || !b ? this.normalMapColor.associatedVariableName : "texture2D(" + b + ", " + s.associatedVariableName + " + uvOffset).xyz";
        return i.compilationString += this._declareOutput(this.output, i) + ` = vec4(0.);\r
`,
        i.compilationString += i._emitCodeFromInclude("bumpFragment", o, {
            replaceStrings: [{
                search: /perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,
                replace: "perturbNormal(TBN, " + et + ", vBumpInfos.y)"
            }, {
                search: /parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,
                replace: "parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, " + (k && this.useParallaxOcclusion ? b : "bumpSampler") + ")"
            }, {
                search: /parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,
                replace: "parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, " + (k ? this.parallaxHeight.associatedVariableName : "0.") + ")"
            }, {
                search: /vTangentSpaceParams/g,
                replace: this._tangentSpaceParameterName
            }, {
                search: /vBumpInfos.y/g,
                replace: $
            }, {
                search: /vBumpInfos.z/g,
                replace: j
            }, {
                search: /vBumpUV/g,
                replace: s.associatedVariableName
            }, {
                search: /vPositionW/g,
                replace: c.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: d.associatedVariableName + ".xyz"
            }, {
                search: /viewDirectionW/g,
                replace: k ? this.viewDirection.associatedVariableName : "vec3(0.)"
            }, _e]
        }),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".invertX = " + this.invertX + `;\r
`);
        return i += this._codeVariableName + ".invertY = " + this.invertY + `;\r
`,
        i += this._codeVariableName + ".useParallaxOcclusion = " + this.useParallaxOcclusion + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.invertX = this.invertX,
        i.invertY = this.invertY,
        i.useParallaxOcclusion = this.useParallaxOcclusion,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.invertX = i.invertX,
        this.invertY = i.invertY,
        this.useParallaxOcclusion = !!i.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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment, !0) || this;
        return o.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("cutoff", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o
    }
    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(i) {
        if (a.prototype._buildBlock.call(this, i),
        i.sharedData.hints.needAlphaTesting = !0,
        !(!this.cutoff.isConnected || !this.value.isConnected))
            return i.compilationString += "if (" + this.value.associatedVariableName + " < " + this.cutoff.associatedVariableName + `) discard;\r
`,
            this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DiscardBlock", DiscardBlock);
var FrontFacingBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o
    }
    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(i) {
        if (a.prototype._buildBlock.call(this, i),
        i.target === NodeMaterialBlockTargets.Vertex)
            throw "FrontFacingBlock must only be used in a fragment shader";
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + ` = gl_FrontFacing ? 1.0 : 0.0;\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.FrontFacingBlock", FrontFacingBlock);
var DerivativeBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect, !1),
        o.registerOutput("dx", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o.registerOutput("dy", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._outputs[1]._typeConnectionSource = o._inputs[0],
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = this._outputs[1];
        return i._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"),
        o.hasEndpoints && (i.compilationString += this._declareOutput(o, i) + (" = dFdx(" + this.input.associatedVariableName + `);\r
`)),
        s.hasEndpoints && (i.compilationString += this._declareOutput(s, i) + (" = dFdy(" + this.input.associatedVariableName + `);\r
`)),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DerivativeBlock", DerivativeBlock);
var FragCoordBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o
    }
    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(i) {
        for (var o = "", s = 0, c = this._outputs; s < c.length; s++) {
            var d = c[s];
            d.hasEndpoints && (o += this._declareOutput(d, i) + " = gl_FragCoord." + d.name + `;\r
`)
        }
        return o
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        i.target === NodeMaterialBlockTargets.Vertex)
            throw "FragCoordBlock must only be used in a fragment shader";
        return i.compilationString += this.writeOutputs(i),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.FragCoordBlock", FragCoordBlock);
var ScreenSizeBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o
    }
    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(i, o, s) {
        var c = this._scene.getEngine();
        i.setFloat2(this._varName, c.getRenderWidth(), c.getRenderHeight())
    }
    ,
    e.prototype.writeOutputs = function(i, o) {
        for (var s = "", c = 0, d = this._outputs; c < d.length; c++) {
            var _ = d[c];
            _.hasEndpoints && (s += this._declareOutput(_, i) + " = " + o + "." + _.name + `;\r
`)
        }
        return s
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        this._scene = i.sharedData.scene,
        i.target === NodeMaterialBlockTargets.Vertex)
            throw "ScreenSizeBlock must only be used in a fragment shader";
        return i.sharedData.bindableBlocks.push(this),
        this._varName = i._getFreeVariableName("screenSize"),
        i._emitUniformFromString(this._varName, "vec2"),
        i.compilationString += this.writeOutputs(i, this._varName),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ScreenSizeBlock", ScreenSizeBlock);
var ScreenSpaceBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.registerInput("vector", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("worldViewProjection", NodeMaterialBlockConnectionPointTypes.Matrix),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float),
        o.inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o
    }
    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(i) {
        if (!this.worldViewProjection.isConnected) {
            var o = i.getInputBlockByPredicate(function(s) {
                return s.systemValue === NodeMaterialSystemValues.WorldViewProjection
            });
            o || (o = new InputBlock("worldViewProjection"),
            o.setAsSystemValue(NodeMaterialSystemValues.WorldViewProjection)),
            o.output.connectTo(this.worldViewProjection)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this.vector
          , s = this.worldViewProjection;
        if (!!o.connectedPoint) {
            var c = s.associatedVariableName
              , d = i._getFreeVariableName("screenSpaceTemp");
            switch (o.connectedPoint.type) {
            case NodeMaterialBlockConnectionPointTypes.Vector3:
                i.compilationString += "vec4 " + d + " = " + c + " * vec4(" + o.associatedVariableName + `, 1.0);\r
`;
                break;
            case NodeMaterialBlockConnectionPointTypes.Vector4:
                i.compilationString += "vec4 " + d + " = " + c + " * " + o.associatedVariableName + `;\r
`;
                break
            }
            return i.compilationString += d + ".xy /= " + d + ".w;",
            i.compilationString += d + ".xy = " + d + ".xy * 0.5 + vec2(0.5, 0.5);",
            this.output.hasEndpoints && (i.compilationString += this._declareOutput(this.output, i) + (" = " + d + `.xy;\r
`)),
            this.x.hasEndpoints && (i.compilationString += this._declareOutput(this.x, i) + (" = " + d + `.x;\r
`)),
            this.y.hasEndpoints && (i.compilationString += this._declareOutput(this.y, i) + (" = " + d + `.y;\r
`)),
            this
        }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ScreenSpaceBlock", ScreenSpaceBlock);
var TwirlBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("center", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        if (!this.center.isConnected) {
            var o = new InputBlock("center");
            o.value = new Vector2(.5,.5),
            o.output.connectTo(this.center)
        }
        if (!this.strength.isConnected) {
            var s = new InputBlock("strength");
            s.value = 1,
            s.output.connectTo(this.strength)
        }
        if (!this.offset.isConnected) {
            var c = new InputBlock("offset");
            c.value = new Vector2(0,0),
            c.output.connectTo(this.offset)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = i._getFreeVariableName("delta")
          , s = i._getFreeVariableName("angle")
          , c = i._getFreeVariableName("x")
          , d = i._getFreeVariableName("y")
          , _ = i._getFreeVariableName("result");
        return i.compilationString += `
            vec2 ` + o + " = " + this.input.associatedVariableName + " - " + this.center.associatedVariableName + `;
            float ` + s + " = " + this.strength.associatedVariableName + " * length(" + o + `);
            float ` + c + " = cos(" + s + ") * " + o + ".x - sin(" + s + ") * " + o + `.y;
            float ` + d + " = sin(" + s + ") * " + o + ".x + cos(" + s + ") * " + o + `.y;
            vec2 ` + _ + " = vec2(" + c + " + " + this.center.associatedVariableName + ".x + " + this.offset.associatedVariableName + ".x, " + d + " + " + this.center.associatedVariableName + ".y + " + this.offset.associatedVariableName + `.y);
        `,
        this.output.hasEndpoints && (i.compilationString += this._declareOutput(this.output, i) + (" = " + _ + `;\r
`)),
        this.x.hasEndpoints && (i.compilationString += this._declareOutput(this.x, i) + (" = " + _ + `.x;\r
`)),
        this.y.hasEndpoints && (i.compilationString += this._declareOutput(this.y, i) + (" = " + _ + `.y;\r
`)),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.TwirlBlock", TwirlBlock);
var FogBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.VertexAndFragment, !1) || this;
        return o.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        o.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, !1, NodeMaterialBlockTargets.Vertex),
        o.registerInput("input", NodeMaterialBlockConnectionPointTypes.Color3, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("fogColor", NodeMaterialBlockConnectionPointTypes.Color3, !1, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        o.input.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o.fogColor.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o
    }
    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(i) {
        if (!this.view.isConnected) {
            var o = i.getInputBlockByPredicate(function(c) {
                return c.systemValue === NodeMaterialSystemValues.View
            });
            o || (o = new InputBlock("view"),
            o.setAsSystemValue(NodeMaterialSystemValues.View)),
            o.output.connectTo(this.view)
        }
        if (!this.fogColor.isConnected) {
            var s = i.getInputBlockByPredicate(function(c) {
                return c.systemValue === NodeMaterialSystemValues.FogColor
            });
            s || (s = new InputBlock("fogColor",void 0,NodeMaterialBlockConnectionPointTypes.Color3),
            s.setAsSystemValue(NodeMaterialSystemValues.FogColor)),
            s.output.connectTo(this.fogColor)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        var c = i.getScene();
        s.setValue("FOG", o.fogEnabled && MaterialHelper.GetFogState(i, c))
    }
    ,
    e.prototype.bind = function(i, o, s) {
        if (!!s) {
            var c = s.getScene();
            i.setFloat4(this._fogParameters, c.fogMode, c.fogStart, c.fogEnd, c.fogDensity)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        i.target === NodeMaterialBlockTargets.Fragment) {
            i.sharedData.blocksWithDefines.push(this),
            i.sharedData.bindableBlocks.push(this),
            i._emitFunctionFromInclude("fogFragmentDeclaration", "//" + this.name, {
                removeUniforms: !0,
                removeVaryings: !0,
                removeIfDef: !1,
                replaceStrings: [{
                    search: /float CalcFogFactor\(\)/,
                    replace: "float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"
                }]
            });
            var o = i._getFreeVariableName("fog")
              , s = this.input
              , c = this.fogColor;
            this._fogParameters = i._getFreeVariableName("fogParameters");
            var d = this._outputs[0];
            i._emitUniformFromString(this._fogParameters, "vec4"),
            i.compilationString += `#ifdef FOG\r
`,
            i.compilationString += "float " + o + " = CalcFogFactor(" + this._fogDistanceName + ", " + this._fogParameters + `);\r
`,
            i.compilationString += this._declareOutput(d, i) + (" = " + o + " * " + s.associatedVariableName + ".rgb + (1.0 - " + o + ") * " + c.associatedVariableName + `.rgb;\r
`),
            i.compilationString += `#else\r
` + this._declareOutput(d, i) + " =  " + s.associatedVariableName + `.rgb;\r
`,
            i.compilationString += `#endif\r
`
        } else {
            var _ = this.worldPosition
              , b = this.view;
            this._fogDistanceName = i._getFreeVariableName("vFogDistance"),
            i._emitVaryingFromString(this._fogDistanceName, "vec3"),
            i.compilationString += this._fogDistanceName + " = (" + b.associatedVariableName + " * " + _.associatedVariableName + `).xyz;\r
`
        }
        return this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.FogBlock", FogBlock);
var LightBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return o._isUnique = !0,
        o.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        o.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("glossiness", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("glossPower", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("specularColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, !0),
        o.registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o
    }
    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(i) {
        if (!this.cameraPosition.isConnected) {
            var o = i.getInputBlockByPredicate(function(s) {
                return s.systemValue === NodeMaterialSystemValues.CameraPosition
            });
            o || (o = new InputBlock("cameraPosition"),
            o.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),
            o.output.connectTo(this.cameraPosition)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        if (!!s._areLightsDirty) {
            var c = i.getScene();
            if (!this.light)
                MaterialHelper.PrepareDefinesForLights(c, i, s, !0, o.maxSimultaneousLights);
            else {
                var d = {
                    needNormals: !1,
                    needRebuild: !1,
                    lightmapMode: !1,
                    shadowEnabled: !1,
                    specularEnabled: !1
                };
                MaterialHelper.PrepareDefinesForLight(c, i, this.light, this._lightId, s, !0, d),
                d.needRebuild && s.rebuild()
            }
        }
    }
    ,
    e.prototype.updateUniformsAndSamples = function(i, o, s, c) {
        for (var d = 0; d < o.maxSimultaneousLights && s["LIGHT" + d]; d++) {
            var _ = i.uniforms.indexOf("vLightData" + d) >= 0;
            MaterialHelper.PrepareUniformsAndSamplersForLight(d, i.uniforms, i.samplers, s["PROJECTEDLIGHTTEXTURE" + d], c, _)
        }
    }
    ,
    e.prototype.bind = function(i, o, s) {
        if (!!s) {
            var c = s.getScene();
            this.light ? MaterialHelper.BindLight(this.light, this._lightId, c, i, !0) : MaterialHelper.BindLights(c, s, i, !0, o.maxSimultaneousLights)
        }
    }
    ,
    e.prototype._injectVertexCode = function(i) {
        var o = this.worldPosition
          , s = "//" + this.name;
        this.light ? (this._lightId = (i.counters.lightCounter !== void 0 ? i.counters.lightCounter : -1) + 1,
        i.counters.lightCounter = this._lightId,
        i._emitFunctionFromInclude(i.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", s, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }, this._lightId.toString())) : (i._emitFunctionFromInclude(i.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", s, {
            repeatKey: "maxSimultaneousLights"
        }),
        this._lightId = 0,
        i.sharedData.dynamicUniformBlocks.push(this));
        var c = "v_" + o.associatedVariableName;
        i._emitVaryingFromString(c, "vec4") && (i.compilationString += c + " = " + o.associatedVariableName + `;\r
`),
        this.light ? i.compilationString += i._emitCodeFromInclude("shadowsVertex", s, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }, {
                search: /worldPos/g,
                replace: o.associatedVariableName
            }]
        }) : (i.compilationString += "vec4 worldPos = " + o.associatedVariableName + `;\r
`,
        this.view.isConnected && (i.compilationString += "mat4 view = " + this.view.associatedVariableName + `;\r
`),
        i.compilationString += i._emitCodeFromInclude("shadowsVertex", s, {
            repeatKey: "maxSimultaneousLights"
        }))
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        i.target !== NodeMaterialBlockTargets.Fragment) {
            this._injectVertexCode(i);
            return
        }
        i.sharedData.forcedBindableBlocks.push(this),
        i.sharedData.blocksWithDefines.push(this);
        var o = "//" + this.name
          , s = this.worldPosition;
        i._emitFunctionFromInclude("helperFunctions", o),
        i._emitFunctionFromInclude("lightsFragmentFunctions", o, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: "v_" + s.associatedVariableName + ".xyz"
            }]
        }),
        i._emitFunctionFromInclude("shadowsFragmentFunctions", o, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: "v_" + s.associatedVariableName + ".xyz"
            }]
        }),
        this.light ? i._emitFunctionFromInclude(i.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", o, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }, this._lightId.toString()) : i._emitFunctionFromInclude(i.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", o, {
            repeatKey: "maxSimultaneousLights"
        }),
        this._lightId === 0 && (i._registerTempVariable("viewDirectionW") && (i.compilationString += "vec3 viewDirectionW = normalize(" + this.cameraPosition.associatedVariableName + " - " + ("v_" + s.associatedVariableName) + `.xyz);\r
`),
        i.compilationString += `lightingInfo info;\r
`,
        i.compilationString += `float shadow = 1.;\r
`,
        i.compilationString += "float glossiness = " + (this.glossiness.isConnected ? this.glossiness.associatedVariableName : "1.0") + " * " + (this.glossPower.isConnected ? this.glossPower.associatedVariableName : "1024.0") + `;\r
`,
        i.compilationString += `vec3 diffuseBase = vec3(0., 0., 0.);\r
`,
        i.compilationString += `vec3 specularBase = vec3(0., 0., 0.);\r
`,
        i.compilationString += "vec3 normalW = " + this.worldNormal.associatedVariableName + `.xyz;\r
`),
        this.light ? i.compilationString += i._emitCodeFromInclude("lightFragment", o, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }) : i.compilationString += i._emitCodeFromInclude("lightFragment", o, {
            repeatKey: "maxSimultaneousLights"
        });
        var c = this.diffuseOutput
          , d = this.specularOutput;
        return i.compilationString += this._declareOutput(c, i) + (" = diffuseBase" + (this.diffuseColor.isConnected ? " * " + this.diffuseColor.associatedVariableName : "") + `;\r
`),
        d.hasEndpoints && (i.compilationString += this._declareOutput(d, i) + (" = specularBase" + (this.specularColor.isConnected ? " * " + this.specularColor.associatedVariableName : "") + `;\r
`)),
        this.shadow.hasEndpoints && (i.compilationString += this._declareOutput(this.shadow, i) + ` = shadow;\r
`),
        this
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return this.light && (i.lightId = this.light.id),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        i.lightId && (this.light = o.getLightById(i.lightId))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.LightBlock", LightBlock);
var NodeMaterialConnectionPointCustomObject = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _) {
        var b = a.call(this, i, o, s) || this;
        return b._blockType = c,
        b._blockName = d,
        b._nameForCheking = _,
        b._nameForCheking || (b._nameForCheking = i),
        b.needDualDirectionValidation = !0,
        b
    }
    return e.prototype.checkCompatibilityState = function(i) {
        return i instanceof e && i.name === this._nameForCheking ? NodeMaterialConnectionPointCompatibilityStates.Compatible : NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible
    }
    ,
    e.prototype.createCustomInputBlock = function() {
        return [new this._blockType(this._blockName), this.name]
    }
    ,
    e
}(NodeMaterialConnectionPoint)
  , ImageSourceBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return o.registerOutput("source", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source",o,NodeMaterialConnectionPointDirection.Output,e,"ImageSourceBlock")),
        o
    }
    return Object.defineProperty(e.prototype, "texture", {
        get: function() {
            return this._texture
        },
        set: function(i) {
            var o = this, s;
            if (this._texture !== i) {
                var c = (s = i == null ? void 0 : i.getScene()) !== null && s !== void 0 ? s : Engine.LastCreatedScene;
                !i && c && c.markAllMaterialsAsDirty(1, function(d) {
                    return d.hasTexture(o._texture)
                }),
                this._texture = i,
                i && c && c.markAllMaterialsAsDirty(1, function(d) {
                    return d.hasTexture(i)
                })
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "samplerName", {
        get: function() {
            return this._samplerName
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.bind = function(i, o, s) {
        !this.texture || i.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(i) {
        return a.prototype._buildBlock.call(this, i),
        i.target === NodeMaterialBlockTargets.Vertex && (this._samplerName = i._getFreeVariableName(this.name + "Sampler"),
        i.sharedData.blockingBlocks.push(this),
        i.sharedData.textureBlocks.push(this),
        i.sharedData.bindableBlocks.push(this)),
        i._emit2DSampler(this._samplerName),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return this.texture && (i += this._codeVariableName + '.texture = new BABYLON.Texture("' + this.texture.name + '", null, ' + this.texture.noMipmap + ", " + this.texture.invertY + ", " + this.texture.samplingMode + `);\r
`,
        i += this._codeVariableName + ".texture.wrapU = " + this.texture.wrapU + `;\r
`,
        i += this._codeVariableName + ".texture.wrapV = " + this.texture.wrapV + `;\r
`,
        i += this._codeVariableName + ".texture.uAng = " + this.texture.uAng + `;\r
`,
        i += this._codeVariableName + ".texture.vAng = " + this.texture.vAng + `;\r
`,
        i += this._codeVariableName + ".texture.wAng = " + this.texture.wAng + `;\r
`,
        i += this._codeVariableName + ".texture.uOffset = " + this.texture.uOffset + `;\r
`,
        i += this._codeVariableName + ".texture.vOffset = " + this.texture.vOffset + `;\r
`,
        i += this._codeVariableName + ".texture.uScale = " + this.texture.uScale + `;\r
`,
        i += this._codeVariableName + ".texture.vScale = " + this.texture.vScale + `;\r
`,
        i += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + `;\r
`),
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture" && (i.texture = this.texture.serialize()),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        i.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && i.texture.url !== void 0 && (s = i.texture.url.indexOf("data:") === 0 ? "" : s,
        this.texture = Texture.Parse(i.texture, o, s))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ImageSourceBlock", ImageSourceBlock);
var TextureBlock = function(a) {
    __extends(e, a);
    function e(i, o) {
        o === void 0 && (o = !1);
        var s = a.call(this, i, o ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment) || this;
        return s.convertToGammaSpace = !1,
        s.convertToLinearSpace = !1,
        s.disableLevelMultiplication = !1,
        s._fragmentOnly = o,
        s.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1, NodeMaterialBlockTargets.VertexAndFragment),
        s.registerInput("source", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source",s,NodeMaterialConnectionPointDirection.Input,ImageSourceBlock,"ImageSourceBlock")),
        s.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral),
        s.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral),
        s.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        s.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        s.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        s.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        s.registerOutput("level", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        s._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        s._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        s._inputs[0]._prioritizeVertex = !o,
        s
    }
    return Object.defineProperty(e.prototype, "texture", {
        get: function() {
            var i;
            return this.source.isConnected ? ((i = this.source.connectedPoint) === null || i === void 0 ? void 0 : i.ownerBlock).texture : this._texture
        },
        set: function(i) {
            var o = this, s;
            if (this._texture !== i) {
                var c = (s = i == null ? void 0 : i.getScene()) !== null && s !== void 0 ? s : Engine.LastCreatedScene;
                !i && c && c.markAllMaterialsAsDirty(1, function(d) {
                    return d.hasTexture(o._texture)
                }),
                this._texture = i,
                i && c && c.markAllMaterialsAsDirty(1, function(d) {
                    return d.hasTexture(i)
                })
            }
        },
        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 i = this.uv.connectedPoint; i; ) {
                if (i.target === NodeMaterialBlockTargets.Fragment)
                    return NodeMaterialBlockTargets.Fragment;
                if (i.target === NodeMaterialBlockTargets.Vertex)
                    return NodeMaterialBlockTargets.VertexAndFragment;
                if (i.target === NodeMaterialBlockTargets.Neutral || i.target === NodeMaterialBlockTargets.VertexAndFragment) {
                    var o = i.ownerBlock;
                    if (o.target === NodeMaterialBlockTargets.Fragment)
                        return NodeMaterialBlockTargets.Fragment;
                    i = null;
                    for (var s = 0, c = o.inputs; s < c.length; s++) {
                        var d = c[s];
                        if (d.connectedPoint) {
                            i = d.connectedPoint;
                            break
                        }
                    }
                }
            }
            return NodeMaterialBlockTargets.VertexAndFragment
        },
        set: function(i) {},
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(i) {
        if (!this.uv.isConnected)
            if (i.mode === NodeMaterialModes.PostProcess) {
                var o = i.getBlockByPredicate(function(c) {
                    return c.name === "uv"
                });
                o && o.connectTo(this)
            } else {
                var s = i.mode === NodeMaterialModes.Particle ? "particle_uv" : "uv"
                  , o = i.getInputBlockByPredicate(function(d) {
                    return d.isAttribute && d.name === s
                });
                o || (o = new InputBlock("uv"),
                o.setAsAttribute(s)),
                o.output.connectTo(this.uv)
            }
    }
    ,
    e.prototype.initializeDefines = function(i, o, s, c) {
        !s._areTexturesDirty || this._mainUVDefineName !== void 0 && s.setValue(this._mainUVDefineName, !1, !0)
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        if (!!s._areTexturesDirty) {
            if (!this.texture || !this.texture.getTextureMatrix) {
                this._isMixed && (s.setValue(this._defineName, !1, !0),
                s.setValue(this._mainUVDefineName, !0, !0));
                return
            }
            s.setValue(this._linearDefineName, this.convertToGammaSpace, !0),
            s.setValue(this._gammaDefineName, this.convertToLinearSpace, !0),
            this._isMixed && (this.texture.getTextureMatrix().isIdentityAs3x2() ? (s.setValue(this._defineName, !1, !0),
            s.setValue(this._mainUVDefineName, !0, !0)) : (s.setValue(this._defineName, !0),
            s[this._mainUVDefineName] == null && s.setValue(this._mainUVDefineName, !1, !0)))
        }
    }
    ,
    e.prototype.isReady = function() {
        return !(this.texture && !this.texture.isReadyOrNotBlocking())
    }
    ,
    e.prototype.bind = function(i, o, s) {
        !this.texture || (this._isMixed && (i.setFloat(this._textureInfoName, this.texture.level),
        i.setMatrix(this._textureTransformName, this.texture.getTextureMatrix())),
        this._imageSource || i.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(i) {
        var o = this.uv;
        if (this._defineName = i._getFreeDefineName("UVTRANSFORM"),
        this._mainUVDefineName = "VMAIN" + o.associatedVariableName.toUpperCase(),
        this._mainUVName = "vMain" + o.associatedVariableName,
        this._transformedUVName = i._getFreeVariableName("transformedUV"),
        this._textureTransformName = i._getFreeVariableName("textureTransform"),
        this._textureInfoName = i._getFreeVariableName("textureInfoName"),
        this.level.associatedVariableName = this._textureInfoName,
        i._emitVaryingFromString(this._transformedUVName, "vec2", this._defineName),
        i._emitVaryingFromString(this._mainUVName, "vec2", this._mainUVDefineName),
        i._emitUniformFromString(this._textureTransformName, "mat4", this._defineName),
        i.compilationString += "#ifdef " + this._defineName + `\r
`,
        i.compilationString += this._transformedUVName + " = vec2(" + this._textureTransformName + " * vec4(" + o.associatedVariableName + `.xy, 1.0, 0.0));\r
`,
        i.compilationString += "#elif defined(" + this._mainUVDefineName + `)\r
`,
        i.compilationString += this._mainUVName + " = " + o.associatedVariableName + `.xy;\r
`,
        i.compilationString += `#endif\r
`,
        !!this._outputs.some(function(_) {
            return _.isConnectedInVertexShader
        })) {
            this._writeTextureRead(i, !0);
            for (var s = 0, c = this._outputs; s < c.length; s++) {
                var d = c[s];
                d.hasEndpoints && d.name !== "level" && this._writeOutput(i, d, d.name, !0)
            }
        }
    }
    ,
    e.prototype._generateTextureLookup = function(i) {
        var o = this.samplerName;
        i.compilationString += "#ifdef " + this._defineName + `\r
`,
        i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + o + ", " + this._transformedUVName + `);\r
`,
        i.compilationString += "#elif defined(" + this._mainUVDefineName + `)\r
`,
        i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + o + ", " + (this._mainUVName ? this._mainUVName : this.uv.associatedVariableName) + `);\r
`,
        i.compilationString += `#endif\r
`
    }
    ,
    e.prototype._writeTextureRead = function(i, o) {
        o === void 0 && (o = !1);
        var s = this.uv;
        if (o) {
            if (i.target === NodeMaterialBlockTargets.Fragment)
                return;
            this._generateTextureLookup(i);
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this.samplerName + ", " + s.associatedVariableName + `);\r
`;
            return
        }
        this._generateTextureLookup(i)
    }
    ,
    e.prototype._generateConversionCode = function(i, o, s) {
        s !== "a" && ((!this.texture || !this.texture.gammaSpace) && (i.compilationString += "#ifdef " + this._linearDefineName + `
                    ` + o.associatedVariableName + " = toGammaSpace(" + o.associatedVariableName + `);
                    #endif
                `),
        (!this.texture || this.texture.gammaSpace) && (i.compilationString += "#ifdef " + this._gammaDefineName + `
                    ` + o.associatedVariableName + " = toLinearSpace(" + o.associatedVariableName + `);
                    #endif
                `))
    }
    ,
    e.prototype._writeOutput = function(i, o, s, c) {
        if (c === void 0 && (c = !1),
        c) {
            if (i.target === NodeMaterialBlockTargets.Fragment)
                return;
            i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`,
            this._generateConversionCode(i, o, s);
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`,
            this._generateConversionCode(i, o, s);
            return
        }
        var d = "";
        this.disableLevelMultiplication || (d = " * " + this._textureInfoName),
        i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + d + `;\r
`,
        this._generateConversionCode(i, o, s)
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        this.source.isConnected ? this._imageSource = this.source.connectedPoint.ownerBlock : this._imageSource = null,
        (i.target === NodeMaterialBlockTargets.Vertex || this._fragmentOnly || i.target === NodeMaterialBlockTargets.Fragment && this._tempTextureRead === void 0) && (this._tempTextureRead = i._getFreeVariableName("tempTextureRead"),
        this._linearDefineName = i._getFreeDefineName("ISLINEAR"),
        this._gammaDefineName = i._getFreeDefineName("ISGAMMA")),
        (!this._isMixed && i.target === NodeMaterialBlockTargets.Fragment || this._isMixed && i.target === NodeMaterialBlockTargets.Vertex) && (this._imageSource || (this._samplerName = i._getFreeVariableName(this.name + "Sampler"),
        i._emit2DSampler(this._samplerName)),
        i.sharedData.blockingBlocks.push(this),
        i.sharedData.textureBlocks.push(this),
        i.sharedData.blocksWithDefines.push(this),
        i.sharedData.bindableBlocks.push(this)),
        i.target !== NodeMaterialBlockTargets.Fragment) {
            this._injectVertexCode(i);
            return
        }
        if (!!this._outputs.some(function(_) {
            return _.isConnectedInFragmentShader
        })) {
            this._isMixed && !this._imageSource && i._emit2DSampler(this._samplerName);
            var o = "//" + this.name;
            i._emitFunctionFromInclude("helperFunctions", o),
            this._isMixed && i._emitUniformFromString(this._textureInfoName, "float"),
            this._writeTextureRead(i);
            for (var s = 0, c = this._outputs; s < c.length; s++) {
                var d = c[s];
                d.hasEndpoints && d.name !== "level" && this._writeOutput(i, d, d.name)
            }
            return this
        }
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return i += this._codeVariableName + ".convertToGammaSpace = " + this.convertToGammaSpace + `;\r
`,
        i += this._codeVariableName + ".convertToLinearSpace = " + this.convertToLinearSpace + `;\r
`,
        i += this._codeVariableName + ".disableLevelMultiplication = " + this.disableLevelMultiplication + `;\r
`,
        this.texture && (i += this._codeVariableName + '.texture = new BABYLON.Texture("' + this.texture.name + '", null, ' + this.texture.noMipmap + ", " + this.texture.invertY + ", " + this.texture.samplingMode + `);\r
`,
        i += this._codeVariableName + ".texture.wrapU = " + this.texture.wrapU + `;\r
`,
        i += this._codeVariableName + ".texture.wrapV = " + this.texture.wrapV + `;\r
`,
        i += this._codeVariableName + ".texture.uAng = " + this.texture.uAng + `;\r
`,
        i += this._codeVariableName + ".texture.vAng = " + this.texture.vAng + `;\r
`,
        i += this._codeVariableName + ".texture.wAng = " + this.texture.wAng + `;\r
`,
        i += this._codeVariableName + ".texture.uOffset = " + this.texture.uOffset + `;\r
`,
        i += this._codeVariableName + ".texture.vOffset = " + this.texture.vOffset + `;\r
`,
        i += this._codeVariableName + ".texture.uScale = " + this.texture.uScale + `;\r
`,
        i += this._codeVariableName + ".texture.vScale = " + this.texture.vScale + `;\r
`,
        i += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + `;\r
`),
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.convertToGammaSpace = this.convertToGammaSpace,
        i.convertToLinearSpace = this.convertToLinearSpace,
        i.fragmentOnly = this._fragmentOnly,
        i.disableLevelMultiplication = this.disableLevelMultiplication,
        !this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture" && (i.texture = this.texture.serialize()),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.convertToGammaSpace = i.convertToGammaSpace,
        this.convertToLinearSpace = !!i.convertToLinearSpace,
        this._fragmentOnly = !!i.fragmentOnly,
        this.disableLevelMultiplication = !!i.disableLevelMultiplication,
        i.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && i.texture.url !== void 0 && (s = i.texture.url.indexOf("data:") === 0 ? "" : s,
        this.texture = Texture.Parse(i.texture, o, s))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.TextureBlock", TextureBlock);
var ReflectionTextureBaseBlock = function(a) {
    __extends(e, a);
    function e(i) {
        return a.call(this, i, NodeMaterialBlockTargets.VertexAndFragment) || this
    }
    return Object.defineProperty(e.prototype, "texture", {
        get: function() {
            return this._texture
        },
        set: function(i) {
            var o = this, s;
            if (this._texture !== i) {
                var c = (s = i == null ? void 0 : i.getScene()) !== null && s !== void 0 ? s : Engine.LastCreatedScene;
                !i && c && c.markAllMaterialsAsDirty(1, function(d) {
                    return d.hasTexture(o._texture)
                }),
                this._texture = i,
                i && c && c.markAllMaterialsAsDirty(1, function(d) {
                    return d.hasTexture(i)
                })
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "ReflectionTextureBaseBlock"
    }
    ,
    e.prototype._getTexture = function() {
        return this.texture
    }
    ,
    e.prototype.autoConfigure = function(i) {
        if (!this.position.isConnected) {
            var o = i.getInputBlockByPredicate(function(d) {
                return d.isAttribute && d.name === "position"
            });
            o || (o = new InputBlock("position"),
            o.setAsAttribute()),
            o.output.connectTo(this.position)
        }
        if (!this.world.isConnected) {
            var s = i.getInputBlockByPredicate(function(d) {
                return d.systemValue === NodeMaterialSystemValues.World
            });
            s || (s = new InputBlock("world"),
            s.setAsSystemValue(NodeMaterialSystemValues.World)),
            s.output.connectTo(this.world)
        }
        if (this.view && !this.view.isConnected) {
            var c = i.getInputBlockByPredicate(function(d) {
                return d.systemValue === NodeMaterialSystemValues.View
            });
            c || (c = new InputBlock("view"),
            c.setAsSystemValue(NodeMaterialSystemValues.View)),
            c.output.connectTo(this.view)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        if (!!s._areTexturesDirty) {
            var c = this._getTexture();
            !c || !c.getTextureMatrix || (s.setValue(this._define3DName, c.isCube, !0),
            s.setValue(this._defineLocalCubicName, !!c.boundingBoxSize, !0),
            s.setValue(this._defineExplicitName, c.coordinatesMode === 0, !0),
            s.setValue(this._defineSkyboxName, c.coordinatesMode === 5, !0),
            s.setValue(this._defineCubicName, c.coordinatesMode === 3 || c.coordinatesMode === 6, !0),
            s.setValue("INVERTCUBICMAP", c.coordinatesMode === 6, !0),
            s.setValue(this._defineSphericalName, c.coordinatesMode === 1, !0),
            s.setValue(this._definePlanarName, c.coordinatesMode === 2, !0),
            s.setValue(this._defineProjectionName, c.coordinatesMode === 4, !0),
            s.setValue(this._defineEquirectangularName, c.coordinatesMode === 7, !0),
            s.setValue(this._defineEquirectangularFixedName, c.coordinatesMode === 8, !0),
            s.setValue(this._defineMirroredEquirectangularFixedName, c.coordinatesMode === 9, !0))
        }
    }
    ,
    e.prototype.isReady = function() {
        var i = this._getTexture();
        return !(i && !i.isReadyOrNotBlocking())
    }
    ,
    e.prototype.bind = function(i, o, s) {
        var c = this._getTexture();
        if (!(!s || !c) && (i.setMatrix(this._reflectionMatrixName, c.getReflectionTextureMatrix()),
        c.isCube ? i.setTexture(this._cubeSamplerName, c) : i.setTexture(this._2DSamplerName, c),
        c.boundingBoxSize)) {
            var d = c;
            i.setVector3(this._reflectionPositionName, d.boundingBoxPosition),
            i.setVector3(this._reflectionSizeName, d.boundingBoxSize)
        }
    }
    ,
    e.prototype.handleVertexSide = function(i) {
        this._define3DName = i._getFreeDefineName("REFLECTIONMAP_3D"),
        this._defineCubicName = i._getFreeDefineName("REFLECTIONMAP_CUBIC"),
        this._defineSphericalName = i._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),
        this._definePlanarName = i._getFreeDefineName("REFLECTIONMAP_PLANAR"),
        this._defineProjectionName = i._getFreeDefineName("REFLECTIONMAP_PROJECTION"),
        this._defineExplicitName = i._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),
        this._defineEquirectangularName = i._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),
        this._defineLocalCubicName = i._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),
        this._defineMirroredEquirectangularFixedName = i._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),
        this._defineEquirectangularFixedName = i._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),
        this._defineSkyboxName = i._getFreeDefineName("REFLECTIONMAP_SKYBOX"),
        this._defineOppositeZ = i._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),
        this._reflectionMatrixName = i._getFreeVariableName("reflectionMatrix"),
        i._emitUniformFromString(this._reflectionMatrixName, "mat4");
        var o = ""
          , s = "v_" + this.worldPosition.associatedVariableName;
        return i._emitVaryingFromString(s, "vec4") && (o += s + " = " + this.worldPosition.associatedVariableName + `;\r
`),
        this._positionUVWName = i._getFreeVariableName("positionUVW"),
        this._directionWName = i._getFreeVariableName("directionW"),
        i._emitVaryingFromString(this._positionUVWName, "vec3", this._defineSkyboxName) && (o += "#ifdef " + this._defineSkyboxName + `\r
`,
        o += this._positionUVWName + " = " + this.position.associatedVariableName + `.xyz;\r
`,
        o += `#endif\r
`),
        i._emitVaryingFromString(this._directionWName, "vec3", "defined(" + this._defineEquirectangularFixedName + ") || defined(" + this._defineMirroredEquirectangularFixedName + ")") && (o += "#if defined(" + this._defineEquirectangularFixedName + ") || defined(" + this._defineMirroredEquirectangularFixedName + `)\r
`,
        o += this._directionWName + " = normalize(vec3(" + this.world.associatedVariableName + " * vec4(" + this.position.associatedVariableName + `.xyz, 0.0)));\r
`,
        o += `#endif\r
`),
        o
    }
    ,
    e.prototype.handleFragmentSideInits = function(i) {
        i.sharedData.blockingBlocks.push(this),
        i.sharedData.textureBlocks.push(this),
        this._cubeSamplerName = i._getFreeVariableName(this.name + "CubeSampler"),
        i.samplers.push(this._cubeSamplerName),
        this._2DSamplerName = i._getFreeVariableName(this.name + "2DSampler"),
        i.samplers.push(this._2DSamplerName),
        i._samplerDeclaration += "#ifdef " + this._define3DName + `\r
`,
        i._samplerDeclaration += "uniform samplerCube " + this._cubeSamplerName + `;\r
`,
        i._samplerDeclaration += `#else\r
`,
        i._samplerDeclaration += "uniform sampler2D " + this._2DSamplerName + `;\r
`,
        i._samplerDeclaration += `#endif\r
`,
        i.sharedData.blocksWithDefines.push(this),
        i.sharedData.bindableBlocks.push(this);
        var o = "//" + this.name;
        i._emitFunction("ReciprocalPI", "#define RECIPROCAL_PI2 0.15915494", ""),
        i._emitFunctionFromInclude("helperFunctions", o),
        i._emitFunctionFromInclude("reflectionFunction", o, {
            replaceStrings: [{
                search: /vec3 computeReflectionCoords/g,
                replace: "void DUMMYFUNC"
            }]
        }),
        this._reflectionColorName = i._getFreeVariableName("reflectionColor"),
        this._reflectionVectorName = i._getFreeVariableName("reflectionUVW"),
        this._reflectionCoordsName = i._getFreeVariableName("reflectionCoords"),
        this._reflectionPositionName = i._getFreeVariableName("vReflectionPosition"),
        i._emitUniformFromString(this._reflectionPositionName, "vec3"),
        this._reflectionSizeName = i._getFreeVariableName("vReflectionPosition"),
        i._emitUniformFromString(this._reflectionSizeName, "vec3")
    }
    ,
    e.prototype.handleFragmentSideCodeReflectionCoords = function(i, o, s) {
        s === void 0 && (s = !1),
        o || (o = "v_" + this.worldPosition.associatedVariableName);
        var c = this._reflectionMatrixName
          , d = "normalize(" + this._directionWName + ")"
          , _ = "" + this._positionUVWName
          , b = "" + this.cameraPosition.associatedVariableName
          , k = "" + this.view.associatedVariableName;
        i += ".xyz";
        var j = `
            #ifdef ` + this._defineMirroredEquirectangularFixedName + `
                vec3 ` + this._reflectionVectorName + " = computeMirroredFixedEquirectangularCoords(" + o + ", " + i + ", " + d + `);
            #endif

            #ifdef ` + this._defineEquirectangularFixedName + `
                vec3 ` + this._reflectionVectorName + " = computeFixedEquirectangularCoords(" + o + ", " + i + ", " + d + `);
            #endif

            #ifdef ` + this._defineEquirectangularName + `
                vec3 ` + this._reflectionVectorName + " = computeEquirectangularCoords(" + o + ", " + i + ", " + b + ".xyz, " + c + `);
            #endif

            #ifdef ` + this._defineSphericalName + `
                vec3 ` + this._reflectionVectorName + " = computeSphericalCoords(" + o + ", " + i + ", " + k + ", " + c + `);
            #endif

            #ifdef ` + this._definePlanarName + `
                vec3 ` + this._reflectionVectorName + " = computePlanarCoords(" + o + ", " + i + ", " + b + ".xyz, " + c + `);
            #endif

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

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

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

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

            #ifdef ` + this._defineOppositeZ + `
                ` + this._reflectionVectorName + `.z *= -1.0;
            #endif\r
`;
        return s || (j += `
                #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
`),
        j
    }
    ,
    e.prototype.handleFragmentSideCodeReflectionColor = function(i, o) {
        o === void 0 && (o = ".rgb");
        var s = "vec" + (o.length === 0 ? "4" : o.length - 1)
          , c = s + " " + this._reflectionColorName + `;
            #ifdef ` + this._define3DName + `\r
`;
        return i ? c += this._reflectionColorName + " = textureCubeLodEXT(" + this._cubeSamplerName + ", " + this._reflectionVectorName + ", " + i + ")" + o + `;\r
` : c += this._reflectionColorName + " = textureCube(" + this._cubeSamplerName + ", " + this._reflectionVectorName + ")" + o + `;\r
`,
        c += `
            #else\r
`,
        i ? c += this._reflectionColorName + " = texture2DLodEXT(" + this._2DSamplerName + ", " + this._reflectionCoordsName + ", " + i + ")" + o + `;\r
` : c += this._reflectionColorName + " = texture2D(" + this._2DSamplerName + ", " + this._reflectionCoordsName + ")" + o + `;\r
`,
        c += `#endif\r
`,
        c
    }
    ,
    e.prototype.writeOutputs = function(i, o) {
        var s = "";
        if (i.target === NodeMaterialBlockTargets.Fragment)
            for (var c = 0, d = this._outputs; c < d.length; c++) {
                var _ = d[c];
                _.hasEndpoints && (s += this._declareOutput(_, i) + " = " + o + "." + _.name + `;\r
`)
            }
        return s
    }
    ,
    e.prototype._buildBlock = function(i) {
        return a.prototype._buildBlock.call(this, i),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        if (!this.texture)
            return i;
        if (this.texture.isCube) {
            var o = this.texture.forcedExtension;
            i += this._codeVariableName + '.texture = new BABYLON.CubeTexture("' + this.texture.name + '", undefined, undefined, ' + this.texture.noMipmap + ", null, undefined, undefined, undefined, " + this.texture._prefiltered + ", " + (o ? '"' + o + '"' : "null") + `);\r
`
        } else
            i += this._codeVariableName + '.texture = new BABYLON.Texture("' + this.texture.name + `", null);\r
`;
        return i += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return this.texture && !this.texture.isRenderTarget && (i.texture = this.texture.serialize()),
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        i.texture && (s = i.texture.url.indexOf("data:") === 0 ? "" : s,
        i.texture.isCube ? this.texture = CubeTexture.Parse(i.texture, o, s) : this.texture = Texture.Parse(i.texture, o, s))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ReflectionTextureBaseBlock", ReflectionTextureBaseBlock);
var ReflectionTextureBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i) || this;
        return o.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3, !1, NodeMaterialBlockTargets.Vertex),
        o.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        o.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, !1, NodeMaterialBlockTargets.Vertex),
        o.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, !1, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o
    }
    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(i) {
        if (a.prototype.autoConfigure.call(this, i),
        !this.cameraPosition.isConnected) {
            var o = i.getInputBlockByPredicate(function(s) {
                return s.systemValue === NodeMaterialSystemValues.CameraPosition
            });
            o || (o = new InputBlock("cameraPosition"),
            o.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),
            o.output.connectTo(this.cameraPosition)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        !this.texture)
            return i.compilationString += this.writeOutputs(i, "vec3(0.)"),
            this;
        if (i.target !== NodeMaterialBlockTargets.Fragment)
            return i.compilationString += this.handleVertexSide(i),
            this;
        this.handleFragmentSideInits(i);
        var o = i._getFreeVariableName("normalWUnit");
        return i.compilationString += "vec4 " + o + " = normalize(" + this.worldNormal.associatedVariableName + `);\r
`,
        i.compilationString += this.handleFragmentSideCodeReflectionCoords(o),
        i.compilationString += this.handleFragmentSideCodeReflectionColor(void 0, ""),
        i.compilationString += this.writeOutputs(i, this._reflectionColorName),
        this
    }
    ,
    e
}(ReflectionTextureBaseBlock);
RegisterClass("BABYLON.ReflectionTextureBlock", ReflectionTextureBlock);
var SceneDepthBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return o._samplerName = "textureSampler",
        o.useNonLinearDepth = !1,
        o.force32itsFloat = !1,
        o._isUnique = !0,
        o.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1, NodeMaterialBlockTargets.VertexAndFragment),
        o.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[0]._prioritizeVertex = !1,
        o
    }
    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(i) {
        i._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(i) {
        var o = i.enableDepthRenderer(void 0, this.useNonLinearDepth, this.force32itsFloat);
        return o.getDepthMap()
    }
    ,
    e.prototype.bind = function(i, o, s) {
        var c = this._getTexture(o.getScene());
        i.setTexture(this._samplerName, c)
    }
    ,
    e.prototype._injectVertexCode = function(i) {
        var o = this.uv;
        if (o.connectedPoint.ownerBlock.isInput) {
            var s = o.connectedPoint.ownerBlock;
            s.isAttribute || i._emitUniformFromString(o.associatedVariableName, "vec" + (o.type === NodeMaterialBlockConnectionPointTypes.Vector3 ? "3" : o.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? "4" : "2"))
        }
        if (this._mainUVName = "vMain" + o.associatedVariableName,
        i._emitVaryingFromString(this._mainUVName, "vec2"),
        i.compilationString += this._mainUVName + " = " + o.associatedVariableName + `.xy;\r
`,
        !!this._outputs.some(function(b) {
            return b.isConnectedInVertexShader
        })) {
            this._writeTextureRead(i, !0);
            for (var c = 0, d = this._outputs; c < d.length; c++) {
                var _ = d[c];
                _.hasEndpoints && this._writeOutput(i, _, "r", !0)
            }
        }
    }
    ,
    e.prototype._writeTextureRead = function(i, o) {
        o === void 0 && (o = !1);
        var s = this.uv;
        if (o) {
            if (i.target === NodeMaterialBlockTargets.Fragment)
                return;
            i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + s.associatedVariableName + `.xy);\r
`;
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + s.associatedVariableName + `.xy);\r
`;
            return
        }
        i.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this._mainUVName + `);\r
`
    }
    ,
    e.prototype._writeOutput = function(i, o, s, c) {
        if (c === void 0 && (c = !1),
        c) {
            if (i.target === NodeMaterialBlockTargets.Fragment)
                return;
            i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`;
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`;
            return
        }
        i.compilationString += this._declareOutput(o, i) + " = " + this._tempTextureRead + "." + s + `;\r
`
    }
    ,
    e.prototype._buildBlock = function(i) {
        if (a.prototype._buildBlock.call(this, i),
        this._tempTextureRead = i._getFreeVariableName("tempTextureRead"),
        i.sharedData.bindableBlocks.indexOf(this) < 0 && i.sharedData.bindableBlocks.push(this),
        i.target !== NodeMaterialBlockTargets.Fragment) {
            i._emit2DSampler(this._samplerName),
            this._injectVertexCode(i);
            return
        }
        if (!!this._outputs.some(function(d) {
            return d.isConnectedInFragmentShader
        })) {
            i._emit2DSampler(this._samplerName),
            this._writeTextureRead(i);
            for (var o = 0, s = this._outputs; o < s.length; o++) {
                var c = s[o];
                c.hasEndpoints && this._writeOutput(i, c, "r")
            }
            return this
        }
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.useNonLinearDepth = this.useNonLinearDepth,
        i.force32itsFloat = this.force32itsFloat,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.useNonLinearDepth = i.useNonLinearDepth,
        this.force32itsFloat = i.force32itsFloat
    }
    ,
    __decorate([editableInPropertyPage("Use non linear depth", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            activatePreviewCommand: !0,
            callback: function(i) {
                return i.disableDepthRenderer()
            }
        }
    })], e.prototype, "useNonLinearDepth", void 0),
    __decorate([editableInPropertyPage("Force 32 bits float", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            activatePreviewCommand: !0,
            callback: function(i) {
                return i.disableDepthRenderer()
            }
        }
    })], e.prototype, "force32itsFloat", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SceneDepthBlock", SceneDepthBlock);
var AddBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = " + this.left.associatedVariableName + " + " + this.right.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.AddBlock", AddBlock);
var ScaleBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("factor", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = " + this.input.associatedVariableName + " * " + this.factor.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ScaleBlock", ScaleBlock);
var ClampBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.minimum = 0,
        o.maximum = 1,
        o.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = clamp(" + this.value.associatedVariableName + ", " + this._writeFloat(this.minimum) + ", " + this._writeFloat(this.maximum) + `);\r
`),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".minimum = " + this.minimum + `;\r
`);
        return i += this._codeVariableName + ".maximum = " + this.maximum + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.minimum = this.minimum,
        i.maximum = this.maximum,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.minimum = i.minimum,
        this.maximum = i.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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        o._linkConnectionTypes(0, 1),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = cross(" + this.left.associatedVariableName + ".xyz, " + this.right.associatedVariableName + `.xyz);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.CrossBlock", CrossBlock);
var CustomBlock = function(a) {
    __extends(e, a);
    function e(i) {
        return a.call(this, i) || this
    }
    return Object.defineProperty(e.prototype, "options", {
        get: function() {
            return this._options
        },
        set: function(i) {
            this._deserializeOptions(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "CustomBlock"
    }
    ,
    e.prototype._buildBlock = function(i) {
        var o = this;
        a.prototype._buildBlock.call(this, i);
        var s = this._code
          , c = this._options.functionName;
        this._inputs.forEach(function(_) {
            var b = new RegExp("\\{TYPE_" + _.name + "\\}","gm")
              , k = i._getGLType(_.type);
            s = s.replace(b, k),
            c = c.replace(b, k)
        }),
        this._outputs.forEach(function(_) {
            var b = new RegExp("\\{TYPE_" + _.name + "\\}","gm")
              , k = i._getGLType(_.type);
            s = s.replace(b, k),
            c = c.replace(b, k)
        }),
        i._emitFunction(c, s, ""),
        this._outputs.forEach(function(_) {
            i.compilationString += o._declareOutput(_, i) + `;\r
`
        }),
        i.compilationString += c + "(";
        var d = !1;
        return this._inputs.forEach(function(_, b) {
            b > 0 && (i.compilationString += ", "),
            i.compilationString += _.associatedVariableName,
            d = !0
        }),
        this._outputs.forEach(function(_, b) {
            (b > 0 || d) && (i.compilationString += ", "),
            i.compilationString += _.associatedVariableName
        }),
        i.compilationString += `);\r
`,
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return i += this._codeVariableName + ".options = " + JSON.stringify(this._options) + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.options = this._options,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        this._deserializeOptions(i.options),
        a.prototype._deserialize.call(this, i, o, s)
    }
    ,
    e.prototype._deserializeOptions = function(i) {
        var o = this, s, c, d;
        this._options = i,
        this._code = i.code.join(`\r
`) + `\r
`,
        this.name = this.name || i.name,
        this.target = NodeMaterialBlockTargets[i.target],
        (s = i.inParameters) === null || s === void 0 || s.forEach(function(_, b) {
            var k = NodeMaterialBlockConnectionPointTypes[_.type];
            o.registerInput(_.name, k),
            Object.defineProperty(o, _.name, {
                get: function() {
                    return this._inputs[b]
                },
                enumerable: !0,
                configurable: !0
            })
        }),
        (c = i.outParameters) === null || c === void 0 || c.forEach(function(_, b) {
            o.registerOutput(_.name, NodeMaterialBlockConnectionPointTypes[_.type]),
            Object.defineProperty(o, _.name, {
                get: function() {
                    return this._outputs[b]
                },
                enumerable: !0,
                configurable: !0
            }),
            _.type === "BasedOnInput" && (o._outputs[b]._typeConnectionSource = o._findInputByName(_.typeFromInput)[0])
        }),
        (d = i.inLinkedConnectionTypes) === null || d === void 0 || d.forEach(function(_) {
            o._linkConnectionTypes(o._findInputByName(_.input1)[1], o._findInputByName(_.input2)[1])
        })
    }
    ,
    e.prototype._findInputByName = function(i) {
        if (!i)
            return null;
        for (var o = 0; o < this._inputs.length; o++)
            if (this._inputs[o].name === i)
                return [this._inputs[o], o];
        return null
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.CustomBlock", CustomBlock);
var DotBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o._linkConnectionTypes(0, 1),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = dot(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DotBlock", DotBlock);
var NormalizeBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = this._inputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = normalize(" + s.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.NormalizeBlock", NormalizeBlock);
var ColorMergerBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.rSwizzle = "r",
        o.gSwizzle = "g",
        o.bSwizzle = "b",
        o.aSwizzle = "a",
        o.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, !0),
        o.registerInput("r", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("g", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4),
        o.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3),
        o
    }
    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(i) {
        return i === "rgb " ? "rgbIn" : i
    }
    ,
    e.prototype._buildSwizzle = function(i) {
        var o = this.rSwizzle + this.gSwizzle + this.bSwizzle + this.aSwizzle;
        return "." + o.substr(0, i)
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this.r
          , s = this.g
          , c = this.b
          , d = this.a
          , _ = this.rgbIn
          , b = this._outputs[0]
          , k = this._outputs[1];
        return _.isConnected ? (b.hasEndpoints && (i.compilationString += this._declareOutput(b, i) + (" = vec4(" + _.associatedVariableName + ", " + (d.isConnected ? this._writeVariable(d) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        k.hasEndpoints && (i.compilationString += this._declareOutput(k, i) + (" = " + _.associatedVariableName + this._buildSwizzle(3) + `;\r
`))) : (b.hasEndpoints && (i.compilationString += this._declareOutput(b, i) + (" = vec4(" + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (s.isConnected ? this._writeVariable(s) : "0.0") + ", " + (c.isConnected ? this._writeVariable(c) : "0.0") + ", " + (d.isConnected ? this._writeVariable(d) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        k.hasEndpoints && (i.compilationString += this._declareOutput(k, i) + (" = vec3(" + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (s.isConnected ? this._writeVariable(s) : "0.0") + ", " + (c.isConnected ? this._writeVariable(c) : "0.0") + ")" + this._buildSwizzle(3) + `;\r
`))),
        this
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.rSwizzle = this.rSwizzle,
        i.gSwizzle = this.gSwizzle,
        i.bSwizzle = this.bSwizzle,
        i.aSwizzle = this.aSwizzle,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        var c, d, _, b;
        a.prototype._deserialize.call(this, i, o, s),
        this.rSwizzle = (c = i.rSwizzle) !== null && c !== void 0 ? c : "r",
        this.gSwizzle = (d = i.gSwizzle) !== null && d !== void 0 ? d : "g",
        this.bSwizzle = (_ = i.bSwizzle) !== null && _ !== void 0 ? _ : "b",
        this.aSwizzle = (b = i.aSwizzle) !== null && b !== void 0 ? b : "a"
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return i += this._codeVariableName + ".rSwizzle = " + this.rSwizzle + `};\r
`,
        i += this._codeVariableName + ".gSwizzle = " + this.gSwizzle + `};\r
`,
        i += this._codeVariableName + ".bSwizzle = " + this.bSwizzle + `};\r
`,
        i += this._codeVariableName + ".aSwizzle = " + this.aSwizzle + `};\r
`,
        i
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ColorMergerBlock", ColorMergerBlock);
var VectorSplitterBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        o.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, !0),
        o.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, !0),
        o.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float),
        o.inputsAreExclusive = !0,
        o
    }
    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(i) {
        switch (i) {
        case "xy ":
            return "xyIn";
        case "xyz ":
            return "xyzIn";
        default:
            return i
        }
    }
    ,
    e.prototype._outputRename = function(i) {
        switch (i) {
        case "xy":
            return "xyOut";
        case "xyz":
            return "xyzOut";
        default:
            return i
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this.xyzw.isConnected ? this.xyzw : this.xyzIn.isConnected ? this.xyzIn : this.xyIn
          , s = this._outputs[0]
          , c = this._outputs[1]
          , d = this._outputs[2]
          , _ = this._outputs[3]
          , b = this._outputs[4]
          , k = this._outputs[5]
          , j = this._outputs[6];
        return s.hasEndpoints && (o === this.xyIn ? i.compilationString += this._declareOutput(s, i) + (" = vec3(" + o.associatedVariableName + `, 0.0);\r
`) : i.compilationString += this._declareOutput(s, i) + (" = " + o.associatedVariableName + `.xyz;\r
`)),
        d.hasEndpoints && this.xyzw.isConnected && (i.compilationString += this._declareOutput(d, i) + (" = " + this.xyzw.associatedVariableName + `.zw;\r
`)),
        c.hasEndpoints && (i.compilationString += this._declareOutput(c, i) + (" = " + o.associatedVariableName + `.xy;\r
`)),
        _.hasEndpoints && (i.compilationString += this._declareOutput(_, i) + (" = " + o.associatedVariableName + `.x;\r
`)),
        b.hasEndpoints && (i.compilationString += this._declareOutput(b, i) + (" = " + o.associatedVariableName + `.y;\r
`)),
        k.hasEndpoints && (i.compilationString += this._declareOutput(k, i) + (" = " + o.associatedVariableName + `.z;\r
`)),
        j.hasEndpoints && (i.compilationString += this._declareOutput(j, i) + (" = " + o.associatedVariableName + `.w;\r
`)),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.VectorSplitterBlock", VectorSplitterBlock);
var LerpBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o._linkConnectionTypes(1, 2, !0),
        o._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = mix(" + this.left.associatedVariableName + " , " + this.right.associatedVariableName + ", " + this.gradient.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.LerpBlock", LerpBlock);
var DivideBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = " + this.left.associatedVariableName + " / " + this.right.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DivideBlock", DivideBlock);
var SubtractBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = " + this.left.associatedVariableName + " - " + this.right.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SubtractBlock", SubtractBlock);
var StepBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("edge", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = step(" + this.edge.associatedVariableName + ", " + this.value.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.StepBlock", StepBlock);
var OneMinusBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = 1. - " + this.input.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.OneMinusBlock", OneMinusBlock);
RegisterClass("BABYLON.OppositeBlock", OneMinusBlock);
var ViewDirectionBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        o
    }
    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(i) {
        if (!this.cameraPosition.isConnected) {
            var o = i.getInputBlockByPredicate(function(s) {
                return s.systemValue === NodeMaterialSystemValues.CameraPosition
            });
            o || (o = new InputBlock("cameraPosition"),
            o.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),
            o.output.connectTo(this.cameraPosition)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = normalize(" + this.cameraPosition.associatedVariableName + " - " + this.worldPosition.associatedVariableName + `.xyz);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ViewDirectionBlock", ViewDirectionBlock);
var FresnelBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("bias", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("power", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("fresnel", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        if (!this.viewDirection.isConnected) {
            var o = new ViewDirectionBlock("View direction");
            o.output.connectTo(this.viewDirection),
            o.autoConfigure(i)
        }
        if (!this.bias.isConnected) {
            var s = new InputBlock("bias");
            s.value = 0,
            s.output.connectTo(this.bias)
        }
        if (!this.power.isConnected) {
            var c = new InputBlock("power");
            c.value = 1,
            c.output.connectTo(this.power)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = "//" + this.name;
        return i._emitFunctionFromInclude("fresnelFunction", o, {
            removeIfDef: !0
        }),
        i.compilationString += this._declareOutput(this.fresnel, i) + (" = 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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = max(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MaxBlock", MaxBlock);
var MinBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = min(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MinBlock", MinBlock);
var DistanceBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o._linkConnectionTypes(0, 1),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = length(" + this.left.associatedVariableName + " - " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DistanceBlock", DistanceBlock);
var LengthBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = length(" + this.value.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.LengthBlock", LengthBlock);
var NegateBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = -1.0 * " + this.value.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.NegateBlock", NegateBlock);
var PowBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("power", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = pow(" + this.value.associatedVariableName + ", " + this.power.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.PowBlock", PowBlock);
var RandomNumberBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = "//" + this.name;
        return i._emitFunctionFromInclude("helperFunctions", s),
        i.compilationString += this._declareOutput(o, i) + (" = getRand(" + this.seed.associatedVariableName + `.xy);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.RandomNumberBlock", RandomNumberBlock);
var ArcTan2Block = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = atan(" + this.x.associatedVariableName + ", " + this.y.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ArcTan2Block", ArcTan2Block);
var SmoothStepBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("edge0", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("edge1", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = smoothstep(" + this.edge0.associatedVariableName + ", " + this.edge1.associatedVariableName + ", " + this.value.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SmoothStepBlock", SmoothStepBlock);
var ReciprocalBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = 1. / " + this.input.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ReciprocalBlock", ReciprocalBlock);
var ReplaceColorBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("reference", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("distance", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("replacement", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o._linkConnectionTypes(0, 3),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + `;\r
`,
        i.compilationString += "if (length(" + this.value.associatedVariableName + " - " + this.reference.associatedVariableName + ") < " + this.distance.associatedVariableName + `) {\r
`,
        i.compilationString += o.associatedVariableName + " = " + this.replacement.associatedVariableName + `;\r
`,
        i.compilationString += `} else {\r
`,
        i.compilationString += o.associatedVariableName + " = " + this.value.associatedVariableName + `;\r
`,
        i.compilationString += `}\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ReplaceColorBlock", ReplaceColorBlock);
var PosterizeBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("steps", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = 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(a) {
    a[a.SawTooth = 0] = "SawTooth",
    a[a.Square = 1] = "Square",
    a[a.Triangle = 2] = "Triangle"
}
)(WaveBlockKind || (WaveBlockKind = {}));
var WaveBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.kind = WaveBlockKind.SawTooth,
        o.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        switch (this.kind) {
        case WaveBlockKind.SawTooth:
            {
                i.compilationString += this._declareOutput(o, i) + (" = " + this.input.associatedVariableName + " - floor(0.5 + " + this.input.associatedVariableName + `);\r
`);
                break
            }
        case WaveBlockKind.Square:
            {
                i.compilationString += this._declareOutput(o, i) + (" = 1.0 - 2.0 * round(fract(" + this.input.associatedVariableName + `));\r
`);
                break
            }
        case WaveBlockKind.Triangle:
            {
                i.compilationString += this._declareOutput(o, i) + (" = 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 i = a.prototype.serialize.call(this);
        return i.kind = this.kind,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.kind = i.kind
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.WaveBlock", WaveBlock);
var GradientBlockColorStep = function() {
    function a(e, i) {
        this.step = e,
        this.color = i
    }
    return Object.defineProperty(a.prototype, "step", {
        get: function() {
            return this._step
        },
        set: function(e) {
            this._step = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "color", {
        get: function() {
            return this._color
        },
        set: function(e) {
            this._color = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a
}()
  , GradientBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.colorSteps = [new GradientBlockColorStep(0,Color3.Black()), new GradientBlockColorStep(1,Color3.White())],
        o.onValueChangedObservable = new Observable,
        o.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o
    }
    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(i) {
        var o = this.colorSteps[i];
        return "vec3(" + o.color.r + ", " + o.color.g + ", " + o.color.b + ")"
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        if (!this.colorSteps.length || !this.gradient.connectedPoint) {
            i.compilationString += this._declareOutput(o, i) + ` = vec3(0., 0., 0.);\r
`;
            return
        }
        var s = i._getFreeVariableName("gradientTempColor")
          , c = i._getFreeVariableName("gradientTempPosition");
        i.compilationString += "vec3 " + s + " = " + this._writeColorConstant(0) + `;\r
`,
        i.compilationString += "float " + c + `;\r
`;
        var d = this.gradient.associatedVariableName;
        this.gradient.connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Float && (d += ".x");
        for (var _ = 1; _ < this.colorSteps.length; _++) {
            var b = this.colorSteps[_]
              , k = this.colorSteps[_ - 1];
            i.compilationString += c + " = clamp((" + d + " - " + i._emitFloat(k.step) + ") / (" + i._emitFloat(b.step) + " -  " + i._emitFloat(k.step) + "), 0.0, 1.0) * step(" + i._emitFloat(_) + ", " + i._emitFloat(this.colorSteps.length - 1) + `);\r
`,
            i.compilationString += s + " = mix(" + s + ", " + this._writeColorConstant(_) + ", " + c + `);\r
`
        }
        return i.compilationString += this._declareOutput(o, i) + (" = " + s + `;\r
`),
        this
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        i.colorSteps = [];
        for (var o = 0, s = this.colorSteps; o < s.length; o++) {
            var c = s[o];
            i.colorSteps.push({
                step: c.step,
                color: {
                    r: c.color.r,
                    g: c.color.g,
                    b: c.color.b
                }
            })
        }
        return i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.colorSteps = [];
        for (var c = 0, d = i.colorSteps; c < d.length; c++) {
            var _ = d[c];
            this.colorSteps.push(new GradientBlockColorStep(_.step,new Color3(_.color.r,_.color.g,_.color.b)))
        }
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        i += this._codeVariableName + `.colorSteps = [];\r
`;
        for (var o = 0, s = this.colorSteps; o < s.length; o++) {
            var c = s[o];
            i += this._codeVariableName + ".colorSteps.push(new BABYLON.GradientBlockColorStep(" + c.step + ", new BABYLON.Color3(" + c.color.r + ", " + c.color.g + ", " + c.color.b + `)));\r
`
        }
        return i
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.GradientBlock", GradientBlock);
var NLerpBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o._linkConnectionTypes(1, 2, !0),
        o._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = normalize(mix(" + this.left.associatedVariableName + " , " + this.right.associatedVariableName + ", " + this.gradient.associatedVariableName + `));\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.NLerpBlock", NLerpBlock);
var WorleyNoise3DBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.manhattanDistance = !1,
        o.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("jitter", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        if (a.prototype._buildBlock.call(this, i),
        !!this.seed.isConnected && !(!this.output.hasEndpoints && !this.x.hasEndpoints && !this.y.hasEndpoints)) {
            var o = `vec3 permute(vec3 x){\r
`;
            o += `    return mod((34.0 * x + 1.0) * x, 289.0);\r
`,
            o += `}\r
\r
`,
            o += `vec3 dist(vec3 x, vec3 y, vec3 z,  bool manhattanDistance){\r
`,
            o += `    return manhattanDistance ?  abs(x) + abs(y) + abs(z) :  (x * x + y * y + z * z);\r
`,
            o += `}\r
\r
`,
            o += `vec2 worley(vec3 P, float jitter, bool manhattanDistance){\r
`,
            o += `    float K = 0.142857142857; // 1/7\r
`,
            o += `    float Ko = 0.428571428571; // 1/2-K/2\r
`,
            o += `    float  K2 = 0.020408163265306; // 1/(7*7)\r
`,
            o += `    float Kz = 0.166666666667; // 1/6\r
`,
            o += `    float Kzo = 0.416666666667; // 1/2-1/6*2\r
`,
            o += `\r
`,
            o += `    vec3 Pi = mod(floor(P), 289.0);\r
`,
            o += `    vec3 Pf = fract(P) - 0.5;\r
`,
            o += `\r
`,
            o += `    vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\r
`,
            o += `    vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\r
`,
            o += `    vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\r
`,
            o += `\r
`,
            o += `    vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\r
`,
            o += `    vec3 p1 = permute(p + Pi.y - 1.0);\r
`,
            o += `    vec3 p2 = permute(p + Pi.y);\r
`,
            o += `    vec3 p3 = permute(p + Pi.y + 1.0);\r
`,
            o += `\r
`,
            o += `    vec3 p11 = permute(p1 + Pi.z - 1.0);\r
`,
            o += `    vec3 p12 = permute(p1 + Pi.z);\r
`,
            o += `    vec3 p13 = permute(p1 + Pi.z + 1.0);\r
`,
            o += `\r
`,
            o += `    vec3 p21 = permute(p2 + Pi.z - 1.0);\r
`,
            o += `    vec3 p22 = permute(p2 + Pi.z);\r
`,
            o += `    vec3 p23 = permute(p2 + Pi.z + 1.0);\r
`,
            o += `\r
`,
            o += `    vec3 p31 = permute(p3 + Pi.z - 1.0);\r
`,
            o += `    vec3 p32 = permute(p3 + Pi.z);\r
`,
            o += `    vec3 p33 = permute(p3 + Pi.z + 1.0);\r
`,
            o += `\r
`,
            o += `    vec3 ox11 = fract(p11*K) - Ko;\r
`,
            o += `    vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\r
`,
            o += `\r
`,
            o += `    vec3 ox12 = fract(p12*K) - Ko;\r
`,
            o += `    vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz12 = floor(p12*K2)*Kz - Kzo;\r
`,
            o += `\r
`,
            o += `    vec3 ox13 = fract(p13*K) - Ko;\r
`,
            o += `    vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz13 = floor(p13*K2)*Kz - Kzo;\r
`,
            o += `\r
`,
            o += `    vec3 ox21 = fract(p21*K) - Ko;\r
`,
            o += `    vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz21 = floor(p21*K2)*Kz - Kzo;\r
`,
            o += `\r
`,
            o += `    vec3 ox22 = fract(p22*K) - Ko;\r
`,
            o += `    vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz22 = floor(p22*K2)*Kz - Kzo;\r
`,
            o += `\r
`,
            o += `    vec3 ox23 = fract(p23*K) - Ko;\r
`,
            o += `    vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz23 = floor(p23*K2)*Kz - Kzo;\r
`,
            o += `\r
`,
            o += `    vec3 ox31 = fract(p31*K) - Ko;\r
`,
            o += `    vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz31 = floor(p31*K2)*Kz - Kzo;\r
`,
            o += `\r
`,
            o += `    vec3 ox32 = fract(p32*K) - Ko;\r
`,
            o += `    vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz32 = floor(p32*K2)*Kz - Kzo;\r
`,
            o += `\r
`,
            o += `    vec3 ox33 = fract(p33*K) - Ko;\r
`,
            o += `    vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\r
`,
            o += `    vec3 oz33 = floor(p33*K2)*Kz - Kzo;\r
`,
            o += `\r
`,
            o += `    vec3 dx11 = Pfx + jitter*ox11;\r
`,
            o += `    vec3 dy11 = Pfy.x + jitter*oy11;\r
`,
            o += `    vec3 dz11 = Pfz.x + jitter*oz11;\r
`,
            o += `\r
`,
            o += `    vec3 dx12 = Pfx + jitter*ox12;\r
`,
            o += `    vec3 dy12 = Pfy.x + jitter*oy12;\r
`,
            o += `    vec3 dz12 = Pfz.y + jitter*oz12;\r
`,
            o += `\r
`,
            o += `    vec3 dx13 = Pfx + jitter*ox13;\r
`,
            o += `    vec3 dy13 = Pfy.x + jitter*oy13;\r
`,
            o += `    vec3 dz13 = Pfz.z + jitter*oz13;\r
`,
            o += `\r
`,
            o += `    vec3 dx21 = Pfx + jitter*ox21;\r
`,
            o += `    vec3 dy21 = Pfy.y + jitter*oy21;\r
`,
            o += `    vec3 dz21 = Pfz.x + jitter*oz21;\r
`,
            o += `\r
`,
            o += `    vec3 dx22 = Pfx + jitter*ox22;\r
`,
            o += `    vec3 dy22 = Pfy.y + jitter*oy22;\r
`,
            o += `    vec3 dz22 = Pfz.y + jitter*oz22;\r
`,
            o += `\r
`,
            o += `    vec3 dx23 = Pfx + jitter*ox23;\r
`,
            o += `    vec3 dy23 = Pfy.y + jitter*oy23;\r
`,
            o += `    vec3 dz23 = Pfz.z + jitter*oz23;\r
`,
            o += `\r
`,
            o += `    vec3 dx31 = Pfx + jitter*ox31;\r
`,
            o += `    vec3 dy31 = Pfy.z + jitter*oy31;\r
`,
            o += `    vec3 dz31 = Pfz.x + jitter*oz31;\r
`,
            o += `\r
`,
            o += `    vec3 dx32 = Pfx + jitter*ox32;\r
`,
            o += `    vec3 dy32 = Pfy.z + jitter*oy32;\r
`,
            o += `    vec3 dz32 = Pfz.y + jitter*oz32;\r
`,
            o += `\r
`,
            o += `    vec3 dx33 = Pfx + jitter*ox33;\r
`,
            o += `    vec3 dy33 = Pfy.z + jitter*oy33;\r
`,
            o += `    vec3 dz33 = Pfz.z + jitter*oz33;\r
`,
            o += `\r
`,
            o += `    vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\r
`,
            o += `    vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\r
`,
            o += `    vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\r
`,
            o += `    vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\r
`,
            o += `    vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\r
`,
            o += `    vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\r
`,
            o += `    vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\r
`,
            o += `    vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\r
`,
            o += `    vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\r
`,
            o += `\r
`,
            o += `    vec3 d1a = min(d11, d12);\r
`,
            o += `    d12 = max(d11, d12);\r
`,
            o += `    d11 = min(d1a, d13); // Smallest now not in d12 or d13\r
`,
            o += `    d13 = max(d1a, d13);\r
`,
            o += `    d12 = min(d12, d13); // 2nd smallest now not in d13\r
`,
            o += `    vec3 d2a = min(d21, d22);\r
`,
            o += `    d22 = max(d21, d22);\r
`,
            o += `    d21 = min(d2a, d23); // Smallest now not in d22 or d23\r
`,
            o += `    d23 = max(d2a, d23);\r
`,
            o += `    d22 = min(d22, d23); // 2nd smallest now not in d23\r
`,
            o += `    vec3 d3a = min(d31, d32);\r
`,
            o += `    d32 = max(d31, d32);\r
`,
            o += `    d31 = min(d3a, d33); // Smallest now not in d32 or d33\r
`,
            o += `    d33 = max(d3a, d33);\r
`,
            o += `    d32 = min(d32, d33); // 2nd smallest now not in d33\r
`,
            o += `    vec3 da = min(d11, d21);\r
`,
            o += `    d21 = max(d11, d21);\r
`,
            o += `    d11 = min(da, d31); // Smallest now in d11\r
`,
            o += `    d31 = max(da, d31); // 2nd smallest now not in d31\r
`,
            o += `    d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\r
`,
            o += `    d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\r
`,
            o += `    d12 = min(d12, d21); // 2nd smallest now not in d21\r
`,
            o += `    d12 = min(d12, d22); // nor in d22\r
`,
            o += `    d12 = min(d12, d31); // nor in d31\r
`,
            o += `    d12 = min(d12, d32); // nor in d32\r
`,
            o += `    d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\r
`,
            o += `    d11.y = min(d11.y,d12.z); // Only two more to go\r
`,
            o += `    d11.y = min(d11.y,d11.z); // Done! (Phew!)\r
`,
            o += `    return sqrt(d11.xy); // F1, F2\r
`,
            o += `}\r
\r
`,
            i._emitFunction("worley3D", o, "// Worley3D");
            var s = i._getFreeVariableName("worleyTemp");
            return i.compilationString += "vec2 " + s + " = worley(" + this.seed.associatedVariableName + ", " + this.jitter.associatedVariableName + ", " + this.manhattanDistance + `);\r
`,
            this.output.hasEndpoints && (i.compilationString += this._declareOutput(this.output, i) + (" = " + s + `;\r
`)),
            this.x.hasEndpoints && (i.compilationString += this._declareOutput(this.x, i) + (" = " + s + `.x;\r
`)),
            this.y.hasEndpoints && (i.compilationString += this._declareOutput(this.y, i) + (" = " + s + `.y;\r
`)),
            this
        }
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".manhattanDistance = " + this.manhattanDistance + `;\r
`);
        return i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.manhattanDistance = this.manhattanDistance,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.manhattanDistance = i.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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        if (a.prototype._buildBlock.call(this, i),
        !!this.seed.isConnected && !!this._outputs[0].hasEndpoints) {
            var o = `const float SKEWFACTOR = 1.0/3.0;\r
`;
            return o += `const float UNSKEWFACTOR = 1.0/6.0;\r
`,
            o += `const float SIMPLEX_CORNER_POS = 0.5;\r
`,
            o += `const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\r
`,
            o += `float SimplexPerlin3D( vec3 P ){\r
`,
            o += `    P *= SIMPLEX_TETRAHADRON_HEIGHT;\r
`,
            o += "    vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );",
            o += `    vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\r
`,
            o += `    vec3 g = step(x0.yzx, x0.xyz);\r
`,
            o += `    vec3 l = 1.0 - g;\r
`,
            o += `    vec3 Pi_1 = min( g.xyz, l.zxy );\r
`,
            o += `    vec3 Pi_2 = max( g.xyz, l.zxy );\r
`,
            o += `    vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\r
`,
            o += `    vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\r
`,
            o += `    vec3 x3 = x0 - SIMPLEX_CORNER_POS;\r
`,
            o += `    vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\r
`,
            o += `    vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\r
`,
            o += `    vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\r
`,
            o += `    Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\r
`,
            o += `    vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\r
`,
            o += `    vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\r
`,
            o += `    Pt *= Pt;\r
`,
            o += `    vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\r
`,
            o += `    Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\r
`,
            o += `    const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\r
`,
            o += `    const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\r
`,
            o += `    vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\r
`,
            o += `    vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\r
`,
            o += `    Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\r
`,
            o += `    Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\r
`,
            o += `    vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\r
`,
            o += `    vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\r
`,
            o += `    vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\r
`,
            o += `    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
`,
            o += `    const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\r
`,
            o += `    vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\r
`,
            o += `    kernel_weights = max(0.5 - kernel_weights, 0.0);\r
`,
            o += `    kernel_weights = kernel_weights*kernel_weights*kernel_weights;\r
`,
            o += `    return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\r
`,
            o += `}\r
`,
            i._emitFunction("SimplexPerlin3D", o, "// SimplexPerlin3D"),
            i.compilationString += this._declareOutput(this._outputs[0], i) + (" = SimplexPerlin3D(" + this.seed.associatedVariableName + `);\r
`),
            this
        }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SimplexPerlin3DBlock", SimplexPerlin3DBlock);
var NormalBlendBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("normalMap0", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("normalMap1", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = this._inputs[0]
          , c = this._inputs[1]
          , d = i._getFreeVariableName("stepR")
          , _ = i._getFreeVariableName("stepG");
        return i.compilationString += "float " + d + " = step(0.5, " + s.associatedVariableName + `.r);\r
`,
        i.compilationString += "float " + _ + " = step(0.5, " + s.associatedVariableName + `.g);\r
`,
        i.compilationString += this._declareOutput(o, i) + `;\r
`,
        i.compilationString += o.associatedVariableName + ".r = (1.0 - " + d + ") * " + s.associatedVariableName + ".r * " + c.associatedVariableName + ".r * 2.0 + " + d + " * (1.0 - (1.0 - " + s.associatedVariableName + ".r) * (1.0 - " + c.associatedVariableName + `.r) * 2.0);\r
`,
        i.compilationString += o.associatedVariableName + ".g = (1.0 - " + _ + ") * " + s.associatedVariableName + ".g * " + c.associatedVariableName + ".g * 2.0 + " + _ + " * (1.0 - (1.0 - " + s.associatedVariableName + ".g) * (1.0 - " + c.associatedVariableName + `.g) * 2.0);\r
`,
        i.compilationString += o.associatedVariableName + ".b = " + s.associatedVariableName + ".b * " + c.associatedVariableName + `.b;\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.NormalBlendBlock", NormalBlendBlock);
var Rotate2dBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerInput("angle", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2),
        o
    }
    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(i) {
        if (!this.angle.isConnected) {
            var o = new InputBlock("angle");
            o.value = 0,
            o.output.connectTo(this.angle)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = this.angle
          , c = this.input;
        return i.compilationString += this._declareOutput(o, i) + (" = vec2(cos(" + s.associatedVariableName + ") * " + c.associatedVariableName + ".x - sin(" + s.associatedVariableName + ") * " + c.associatedVariableName + ".y, sin(" + s.associatedVariableName + ") * " + c.associatedVariableName + ".x + cos(" + s.associatedVariableName + ") * " + c.associatedVariableName + `.y);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.Rotate2dBlock", Rotate2dBlock);
var ReflectBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("incident", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = reflect(" + this.incident.associatedVariableName + ".xyz, " + this.normal.associatedVariableName + `.xyz);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ReflectBlock", ReflectBlock);
var RefractBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("incident", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3),
        o.registerInput("ior", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        o._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = refract(" + this.incident.associatedVariableName + ".xyz, " + this.normal.associatedVariableName + ".xyz, " + this.ior.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.RefractBlock", RefractBlock);
var DesaturateBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3),
        o.registerInput("level", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = this.color
          , c = s.associatedVariableName
          , d = i._getFreeVariableName("colorMin")
          , _ = i._getFreeVariableName("colorMax")
          , b = i._getFreeVariableName("colorMerge");
        return i.compilationString += "float " + d + " = min(min(" + c + ".x, " + c + ".y), " + c + `.z);\r
`,
        i.compilationString += "float " + _ + " = max(max(" + c + ".x, " + c + ".y), " + c + `.z);\r
`,
        i.compilationString += "float " + b + " = 0.5 * (" + d + " + " + _ + `);\r
`,
        i.compilationString += this._declareOutput(o, i) + (" = mix(" + c + ", vec3(" + b + ", " + b + ", " + b + "), " + this.level.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DesaturateBlock", DesaturateBlock);
var _environmentBRDFBase64Texture = "data:image/png;base64, "
  , _instanceNumber = 0
  , GetEnvironmentBRDFTexture = function(a) {
    if (!a.environmentBRDFTexture) {
        var e = a.useDelayedTextureLoading;
        a.useDelayedTextureLoading = !1;
        var i = a._blockEntityCollection;
        a._blockEntityCollection = !1;
        var o = Texture.CreateFromBase64String(_environmentBRDFBase64Texture, "EnvironmentBRDFTexture" + _instanceNumber++, a, !0, !1, Texture.BILINEAR_SAMPLINGMODE);
        a._blockEntityCollection = i;
        var s = a.getEngine().getLoadedTexturesCache()
          , c = s.indexOf(o.getInternalTexture());
        c !== -1 && s.splice(c, 1),
        o.isRGBD = !0,
        o.wrapU = Texture.CLAMP_ADDRESSMODE,
        o.wrapV = Texture.CLAMP_ADDRESSMODE,
        a.environmentBRDFTexture = o,
        a.useDelayedTextureLoading = e,
        RGBDTextureTools.ExpandRGBDTexture(o),
        a.getEngine().onContextRestoredObservable.add(function() {
            o.isRGBD = !0;
            var d = function() {
                o.isReady() ? RGBDTextureTools.ExpandRGBDTexture(o) : Tools.SetImmediate(d)
            };
            d()
        })
    }
    return a.environmentBRDFTexture
}
  , PBRClearCoatConfiguration = function() {
    function a(e) {
        this._isEnabled = !1,
        this.isEnabled = !1,
        this.intensity = 1,
        this.roughness = 0,
        this._indexOfRefraction = a._DefaultIndexOfRefraction,
        this.indexOfRefraction = a._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 a.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    a.prototype.isReadyForSubMesh = function(e, i, o, s) {
        return this._isEnabled ? !(e._areTexturesDirty && i.texturesEnabled && (this._texture && MaterialFlags.ClearCoatTextureEnabled && !this._texture.isReadyOrNotBlocking() || this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled && !this._textureRoughness.isReadyOrNotBlocking() || o.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled && !s && !this._bumpTexture.isReady() || this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled && !this._tintTexture.isReadyOrNotBlocking())) : !0
    }
    ,
    a.prototype.prepareDefines = function(e, i) {
        var o;
        this._isEnabled ? (e.CLEARCOAT = !0,
        e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture,
        e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = this._texture !== null && this._texture._texture === ((o = this._textureRoughness) === null || o === void 0 ? void 0 : o._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness),
        e.CLEARCOAT_REMAP_F0 = this._remapF0OnInterfaceChange,
        e._areTexturesDirty && i.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 === a._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)
    }
    ,
    a.prototype.bindForSubMesh = function(e, i, o, s, c, d, _, b) {
        var k, j, $, _e, et, tt, rt, it;
        if (!!this._isEnabled) {
            var nt = b.materialDefines
              , ot = nt.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;
            if (!e.useUbo || !c || !e.isSync) {
                ot && 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", (j = (k = this._texture) === null || k === void 0 ? void 0 : k.coordinatesIndex) !== null && j !== void 0 ? j : 0, (_e = ($ = this._texture) === null || $ === void 0 ? void 0 : $.level) !== null && _e !== void 0 ? _e : 0, (tt = (et = this._textureRoughness) === null || et === void 0 ? void 0 : et.coordinatesIndex) !== null && tt !== void 0 ? tt : 0, (it = (rt = this._textureRoughness) === null || rt === void 0 ? void 0 : rt.level) !== null && it !== void 0 ? it : 0),
                this._texture && MaterialHelper.BindTextureMatrix(this._texture, e, "clearCoat"),
                this._textureRoughness && !ot && !nt.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialHelper.BindTextureMatrix(this._textureRoughness, e, "clearCoatRoughness")),
                this._bumpTexture && o.getCaps().standardDerivatives && MaterialFlags.ClearCoatTextureEnabled && !s && (e.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level),
                MaterialHelper.BindTextureMatrix(this._bumpTexture, e, "clearCoatBump"),
                i._mirroredCameraPosition ? e.updateFloat2("vClearCoatTangentSpaceParams", d ? 1 : -1, _ ? 1 : -1) : e.updateFloat2("vClearCoatTangentSpaceParams", d ? -1 : 1, _ ? -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 at = 1 - this._indexOfRefraction
                  , st = 1 + this._indexOfRefraction
                  , ut = Math.pow(-at / st, 2)
                  , ct = 1 / this._indexOfRefraction;
                e.updateFloat4("vClearCoatRefractionParams", ut, ct, at, st),
                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)))
            }
            i.texturesEnabled && (this._texture && MaterialFlags.ClearCoatTextureEnabled && e.setTexture("clearCoatSampler", this._texture),
            this._textureRoughness && !ot && !nt.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.ClearCoatTextureEnabled && e.setTexture("clearCoatRoughnessSampler", this._textureRoughness),
            this._bumpTexture && o.getCaps().standardDerivatives && MaterialFlags.ClearCoatBumpTextureEnabled && !s && e.setTexture("clearCoatBumpSampler", this._bumpTexture),
            this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled && e.setTexture("clearCoatTintSampler", this._tintTexture))
        }
    }
    ,
    a.prototype.hasTexture = function(e) {
        return this._texture === e || this._textureRoughness === e || this._bumpTexture === e || this._tintTexture === e
    }
    ,
    a.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)
    }
    ,
    a.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)
    }
    ,
    a.prototype.dispose = function(e) {
        var i, o, s, c;
        e && ((i = this._texture) === null || i === void 0 || i.dispose(),
        (o = this._textureRoughness) === null || o === void 0 || o.dispose(),
        (s = this._bumpTexture) === null || s === void 0 || s.dispose(),
        (c = this._tintTexture) === null || c === void 0 || c.dispose())
    }
    ,
    a.prototype.getClassName = function() {
        return "PBRClearCoatConfiguration"
    }
    ,
    a.AddFallbacks = function(e, i, o) {
        return e.CLEARCOAT_BUMP && i.addFallback(o++, "CLEARCOAT_BUMP"),
        e.CLEARCOAT_TINT && i.addFallback(o++, "CLEARCOAT_TINT"),
        e.CLEARCOAT && i.addFallback(o++, "CLEARCOAT"),
        o
    }
    ,
    a.AddUniforms = function(e) {
        e.push("vClearCoatTangentSpaceParams", "vClearCoatParams", "vClearCoatRefractionParams", "vClearCoatTintParams", "clearCoatColorAtDistance", "clearCoatMatrix", "clearCoatRoughnessMatrix", "clearCoatBumpMatrix", "clearCoatTintMatrix", "vClearCoatInfos", "vClearCoatBumpInfos", "vClearCoatTintInfos")
    }
    ,
    a.AddSamplers = function(e) {
        e.push("clearCoatSampler", "clearCoatRoughnessSampler", "clearCoatBumpSampler", "clearCoatTintSampler")
    }
    ,
    a.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)
    }
    ,
    a.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.prototype.parse = function(e, i, o) {
        var s = this;
        SerializationHelper.Parse(function() {
            return s
        }, e, i, o)
    }
    ,
    a._DefaultIndexOfRefraction = 1.5,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "isEnabled", void 0),
    __decorate([serialize()], a.prototype, "intensity", void 0),
    __decorate([serialize()], a.prototype, "roughness", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "indexOfRefraction", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "texture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "useRoughnessFromMainTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "textureRoughness", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "remapF0OnInterfaceChange", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "bumpTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "isTintEnabled", void 0),
    __decorate([serializeAsColor3()], a.prototype, "tintColor", void 0),
    __decorate([serialize()], a.prototype, "tintColorAtDistance", void 0),
    __decorate([serialize()], a.prototype, "tintThickness", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "tintTexture", void 0),
    a
}()
  , PBRAnisotropicConfiguration = function() {
    function a(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 a.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    a.prototype.isReadyForSubMesh = function(e, i) {
        return this._isEnabled ? !(e._areTexturesDirty && i.texturesEnabled && this._texture && MaterialFlags.AnisotropicTextureEnabled && !this._texture.isReadyOrNotBlocking()) : !0
    }
    ,
    a.prototype.prepareDefines = function(e, i, o) {
        this._isEnabled ? (e.ANISOTROPIC = this._isEnabled,
        this._isEnabled && !i.isVerticesDataPresent(VertexBuffer.TangentKind) && (e._needUVs = !0,
        e.MAINUV1 = !0),
        e._areTexturesDirty && o.texturesEnabled && (this._texture && MaterialFlags.AnisotropicTextureEnabled ? MaterialHelper.PrepareDefinesForMergedUV(this._texture, e, "ANISOTROPIC_TEXTURE") : e.ANISOTROPIC_TEXTURE = !1)) : (e.ANISOTROPIC = !1,
        e.ANISOTROPIC_TEXTURE = !1)
    }
    ,
    a.prototype.bindForSubMesh = function(e, i, o) {
        !this._isEnabled || ((!e.useUbo || !o || !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)),
        i.texturesEnabled && this._texture && MaterialFlags.AnisotropicTextureEnabled && e.setTexture("anisotropySampler", this._texture))
    }
    ,
    a.prototype.hasTexture = function(e) {
        return this._texture === e
    }
    ,
    a.prototype.getActiveTextures = function(e) {
        this._texture && e.push(this._texture)
    }
    ,
    a.prototype.getAnimatables = function(e) {
        this._texture && this._texture.animations && this._texture.animations.length > 0 && e.push(this._texture)
    }
    ,
    a.prototype.dispose = function(e) {
        e && this._texture && this._texture.dispose()
    }
    ,
    a.prototype.getClassName = function() {
        return "PBRAnisotropicConfiguration"
    }
    ,
    a.AddFallbacks = function(e, i, o) {
        return e.ANISOTROPIC && i.addFallback(o++, "ANISOTROPIC"),
        o
    }
    ,
    a.AddUniforms = function(e) {
        e.push("vAnisotropy", "vAnisotropyInfos", "anisotropyMatrix")
    }
    ,
    a.PrepareUniformBuffer = function(e) {
        e.addUniform("vAnisotropy", 3),
        e.addUniform("vAnisotropyInfos", 2),
        e.addUniform("anisotropyMatrix", 16)
    }
    ,
    a.AddSamplers = function(e) {
        e.push("anisotropySampler")
    }
    ,
    a.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.prototype.parse = function(e, i, o) {
        var s = this;
        SerializationHelper.Parse(function() {
            return s
        }, e, i, o)
    }
    ,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "isEnabled", void 0),
    __decorate([serialize()], a.prototype, "intensity", void 0),
    __decorate([serializeAsVector2()], a.prototype, "direction", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "texture", void 0),
    a
}()
  , PBRBRDFConfiguration = function() {
    function a(e) {
        this._useEnergyConservation = a.DEFAULT_USE_ENERGY_CONSERVATION,
        this.useEnergyConservation = a.DEFAULT_USE_ENERGY_CONSERVATION,
        this._useSmithVisibilityHeightCorrelated = a.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,
        this.useSmithVisibilityHeightCorrelated = a.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,
        this._useSphericalHarmonics = a.DEFAULT_USE_SPHERICAL_HARMONICS,
        this.useSphericalHarmonics = a.DEFAULT_USE_SPHERICAL_HARMONICS,
        this._useSpecularGlossinessInputEnergyConservation = a.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,
        this.useSpecularGlossinessInputEnergyConservation = a.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,
        this._internalMarkAllSubMeshesAsMiscDirty = e
    }
    return a.prototype._markAllSubMeshesAsMiscDirty = function() {
        this._internalMarkAllSubMeshesAsMiscDirty()
    }
    ,
    a.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
    }
    ,
    a.prototype.getClassName = function() {
        return "PBRBRDFConfiguration"
    }
    ,
    a.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.prototype.parse = function(e, i, o) {
        var s = this;
        SerializationHelper.Parse(function() {
            return s
        }, e, i, o)
    }
    ,
    a.DEFAULT_USE_ENERGY_CONSERVATION = !0,
    a.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = !0,
    a.DEFAULT_USE_SPHERICAL_HARMONICS = !0,
    a.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = !0,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], a.prototype, "useEnergyConservation", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], a.prototype, "useSmithVisibilityHeightCorrelated", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], a.prototype, "useSphericalHarmonics", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], a.prototype, "useSpecularGlossinessInputEnergyConservation", void 0),
    a
}()
  , PBRSheenConfiguration = function() {
    function a(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 a.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    a.prototype.isReadyForSubMesh = function(e, i) {
        return this._isEnabled ? !(e._areTexturesDirty && i.texturesEnabled && (this._texture && MaterialFlags.SheenTextureEnabled && !this._texture.isReadyOrNotBlocking() || this._textureRoughness && MaterialFlags.SheenTextureEnabled && !this._textureRoughness.isReadyOrNotBlocking())) : !0
    }
    ,
    a.prototype.prepareDefines = function(e, i) {
        var o;
        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 === ((o = this._textureRoughness) === null || o === void 0 ? void 0 : o._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness),
        e._areTexturesDirty && i.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)
    }
    ,
    a.prototype.bindForSubMesh = function(e, i, o, s) {
        var c, d, _, b, k, j, $, _e;
        if (!!this._isEnabled) {
            var et = s.materialDefines
              , tt = et.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;
            (!e.useUbo || !o || !e.isSync) && (tt && 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", (d = (c = this._texture) === null || c === void 0 ? void 0 : c.coordinatesIndex) !== null && d !== void 0 ? d : 0, (b = (_ = this._texture) === null || _ === void 0 ? void 0 : _.level) !== null && b !== void 0 ? b : 0, (j = (k = this._textureRoughness) === null || k === void 0 ? void 0 : k.coordinatesIndex) !== null && j !== void 0 ? j : 0, (_e = ($ = this._textureRoughness) === null || $ === void 0 ? void 0 : $.level) !== null && _e !== void 0 ? _e : 0),
            this._texture && MaterialHelper.BindTextureMatrix(this._texture, e, "sheen"),
            this._textureRoughness && !tt && !et.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)),
            i.texturesEnabled && (this._texture && MaterialFlags.SheenTextureEnabled && e.setTexture("sheenSampler", this._texture),
            this._textureRoughness && !tt && !et.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.SheenTextureEnabled && e.setTexture("sheenRoughnessSampler", this._textureRoughness))
        }
    }
    ,
    a.prototype.hasTexture = function(e) {
        return this._texture === e || this._textureRoughness === e
    }
    ,
    a.prototype.getActiveTextures = function(e) {
        this._texture && e.push(this._texture),
        this._textureRoughness && e.push(this._textureRoughness)
    }
    ,
    a.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)
    }
    ,
    a.prototype.dispose = function(e) {
        var i, o;
        e && ((i = this._texture) === null || i === void 0 || i.dispose(),
        (o = this._textureRoughness) === null || o === void 0 || o.dispose())
    }
    ,
    a.prototype.getClassName = function() {
        return "PBRSheenConfiguration"
    }
    ,
    a.AddFallbacks = function(e, i, o) {
        return e.SHEEN && i.addFallback(o++, "SHEEN"),
        o
    }
    ,
    a.AddUniforms = function(e) {
        e.push("vSheenColor", "vSheenRoughness", "vSheenInfos", "sheenMatrix", "sheenRoughnessMatrix")
    }
    ,
    a.PrepareUniformBuffer = function(e) {
        e.addUniform("vSheenColor", 4),
        e.addUniform("vSheenRoughness", 1),
        e.addUniform("vSheenInfos", 4),
        e.addUniform("sheenMatrix", 16),
        e.addUniform("sheenRoughnessMatrix", 16)
    }
    ,
    a.AddSamplers = function(e) {
        e.push("sheenSampler"),
        e.push("sheenRoughnessSampler")
    }
    ,
    a.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.prototype.parse = function(e, i, o) {
        var s = this;
        SerializationHelper.Parse(function() {
            return s
        }, e, i, o)
    }
    ,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "isEnabled", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "linkSheenWithAlbedo", void 0),
    __decorate([serialize()], a.prototype, "intensity", void 0),
    __decorate([serializeAsColor3()], a.prototype, "color", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "texture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "useRoughnessFromMainTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "roughness", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "textureRoughness", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "albedoScaling", void 0),
    a
}()
  , PBRSubSurfaceConfiguration = function() {
    function a(e, i, o) {
        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 = i,
        this._scene = o
    }
    return Object.defineProperty(a.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(a.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
    }),
    a.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    a.prototype._markScenePrePassDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty(),
        this._internalMarkScenePrePassDirty()
    }
    ,
    a.prototype.isReadyForSubMesh = function(e, i) {
        if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled)
            return !0;
        if (e._areTexturesDirty && i.texturesEnabled) {
            if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled && !this._thicknessTexture.isReadyOrNotBlocking())
                return !1;
            var o = this._getRefractionTexture(i);
            if (o && MaterialFlags.RefractionTextureEnabled && !o.isReadyOrNotBlocking())
                return !1
        }
        return !0
    }
    ,
    a.prototype.prepareDefines = function(e, i) {
        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 o = !!this._thicknessTexture && !!this._refractionIntensityTexture && this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) && this._refractionIntensityTexture._texture === this._thicknessTexture._texture
                  , s = !!this._thicknessTexture && !!this._translucencyIntensityTexture && this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) && this._translucencyIntensityTexture._texture === this._thicknessTexture._texture
                  , c = (o || !this._refractionIntensityTexture) && (s || !this._translucencyIntensityTexture);
                e._areTexturesDirty && i.texturesEnabled && (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled && MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, e, "SS_THICKNESSANDMASK_TEXTURE"),
                this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && !c && MaterialHelper.PrepareDefinesForMergedUV(this._refractionIntensityTexture, e, "SS_REFRACTIONINTENSITY_TEXTURE"),
                this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && !c && 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) && c,
                e.SS_USE_GLTF_TEXTURES = this._useGltfStyleTextures,
                e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture) && c,
                e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._translucencyIntensityTexture) && c
            }
            if (this._isRefractionEnabled && i.texturesEnabled) {
                var d = this._getRefractionTexture(i);
                d && MaterialFlags.RefractionTextureEnabled && (e.SS_REFRACTION = !0,
                e.SS_REFRACTIONMAP_3D = d.isCube,
                e.SS_GAMMAREFRACTION = d.gammaSpace,
                e.SS_RGBDREFRACTION = d.isRGBD,
                e.SS_LINEARSPECULARREFRACTION = d.linearSpecularLOD,
                e.SS_REFRACTIONMAP_OPPOSITEZ = d.invertZ,
                e.SS_LODINREFRACTIONALPHA = d.lodLevelInAlpha,
                e.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency,
                e.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction,
                e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = d.isCube && d.boundingBoxSize,
                e.SS_USE_THICKNESS_AS_DEPTH = this.useThicknessAsDepth)
            }
            this._isTranslucencyEnabled && (e.SS_ALBEDOFORTRANSLUCENCYTINT = this.useAlbedoToTintTranslucency)
        }
    }
    ,
    a.prototype.hardBindForSubMesh = function(e, i, o, s, c, d, _) {
        if (!(!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled)) {
            _.getRenderingMesh().getWorldMatrix().decompose(TmpVectors.Vector3[0]);
            var b = 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 * b, (this.maximumThickness - this.minimumThickness) * b)
        }
    }
    ,
    a.prototype.bindForSubMesh = function(e, i, o, s, c, d, _) {
        if (!(!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled)) {
            var b = _.materialDefines
              , k = this._getRefractionTexture(i);
            if (!e.useUbo || !s || !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 && b.SS_REFRACTIONINTENSITY_TEXTURE && (e.updateFloat2("vRefractionIntensityInfos", this._refractionIntensityTexture.coordinatesIndex, this._refractionIntensityTexture.level),
                MaterialHelper.BindTextureMatrix(this._refractionIntensityTexture, e, "refractionIntensity")),
                this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && b.SS_TRANSLUCENCYINTENSITY_TEXTURE && (e.updateFloat2("vTranslucencyIntensityInfos", this._translucencyIntensityTexture.coordinatesIndex, this._translucencyIntensityTexture.level),
                MaterialHelper.BindTextureMatrix(this._translucencyIntensityTexture, e, "translucencyIntensity")),
                k && MaterialFlags.RefractionTextureEnabled) {
                    e.updateMatrix("refractionMatrix", k.getReflectionTextureMatrix());
                    var j = 1;
                    k.isCube || k.depth && (j = k.depth);
                    var $ = k.getSize().width
                      , _e = this.volumeIndexOfRefraction;
                    if (e.updateFloat4("vRefractionInfos", k.level, 1 / _e, j, this._invertRefractionY ? -1 : 1),
                    e.updateFloat4("vRefractionMicrosurfaceInfos", $, k.lodGenerationScale, k.lodGenerationOffset, 1 / this.indexOfRefraction),
                    d && e.updateFloat2("vRefractionFilteringInfo", $, Scalar.Log2($)),
                    k.boundingBoxSize) {
                        var et = k;
                        e.updateVector3("vRefractionPosition", et.boundingBoxPosition),
                        e.updateVector3("vRefractionSize", et.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)
            }
            i.texturesEnabled && (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled && e.setTexture("thicknessSampler", this._thicknessTexture),
            this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && b.SS_REFRACTIONINTENSITY_TEXTURE && e.setTexture("refractionIntensitySampler", this._refractionIntensityTexture),
            this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && b.SS_TRANSLUCENCYINTENSITY_TEXTURE && e.setTexture("translucencyIntensitySampler", this._translucencyIntensityTexture),
            k && MaterialFlags.RefractionTextureEnabled && (c ? e.setTexture("refractionSampler", k) : (e.setTexture("refractionSampler", k._lodTextureMid || k),
            e.setTexture("refractionSamplerLow", k._lodTextureLow || k),
            e.setTexture("refractionSamplerHigh", k._lodTextureHigh || k))))
        }
    }
    ,
    a.prototype.unbind = function(e) {
        return this._refractionTexture && this._refractionTexture.isRenderTarget ? (e.setTexture("refractionSampler", null),
        !0) : !1
    }
    ,
    a.prototype._getRefractionTexture = function(e) {
        return this._refractionTexture ? this._refractionTexture : this._isRefractionEnabled ? e.environmentTexture : null
    }
    ,
    Object.defineProperty(a.prototype, "disableAlphaBlending", {
        get: function() {
            return this.isRefractionEnabled && this._linkRefractionWithTransparency
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.fillRenderTargetTextures = function(e) {
        MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget && e.push(this._refractionTexture)
    }
    ,
    a.prototype.hasTexture = function(e) {
        return this._thicknessTexture === e || this._refractionTexture === e
    }
    ,
    a.prototype.hasRenderTargetTextures = function() {
        return !!(MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget)
    }
    ,
    a.prototype.getActiveTextures = function(e) {
        this._thicknessTexture && e.push(this._thicknessTexture),
        this._refractionTexture && e.push(this._refractionTexture)
    }
    ,
    a.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)
    }
    ,
    a.prototype.dispose = function(e) {
        e && (this._thicknessTexture && this._thicknessTexture.dispose(),
        this._refractionTexture && this._refractionTexture.dispose())
    }
    ,
    a.prototype.getClassName = function() {
        return "PBRSubSurfaceConfiguration"
    }
    ,
    a.AddFallbacks = function(e, i, o) {
        return e.SS_SCATTERING && i.addFallback(o++, "SS_SCATTERING"),
        e.SS_TRANSLUCENCY && i.addFallback(o++, "SS_TRANSLUCENCY"),
        o
    }
    ,
    a.AddUniforms = function(e) {
        e.push("vDiffusionDistance", "vTintColor", "vSubSurfaceIntensity", "vRefractionMicrosurfaceInfos", "vRefractionFilteringInfo", "vRefractionInfos", "vThicknessInfos", "vRefractionIntensityInfos", "vTranslucencyIntensityInfos", "vThicknessParam", "vRefractionPosition", "vRefractionSize", "refractionMatrix", "thicknessMatrix", "refractionIntensityMatrix", "translucencyIntensityMatrix", "scatteringDiffusionProfile")
    }
    ,
    a.AddSamplers = function(e) {
        e.push("thicknessSampler", "refractionIntensitySampler", "translucencyIntensitySampler", "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh")
    }
    ,
    a.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)
    }
    ,
    a.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    a.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    a.prototype.parse = function(e, i, o) {
        var s = this;
        SerializationHelper.Parse(function() {
            return s
        }, e, i, o)
    }
    ,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "isRefractionEnabled", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "isTranslucencyEnabled", void 0),
    __decorate([serialize(), expandToProperty("_markScenePrePassDirty")], a.prototype, "isScatteringEnabled", void 0),
    __decorate([serialize()], a.prototype, "_scatteringDiffusionProfileIndex", void 0),
    __decorate([serialize()], a.prototype, "refractionIntensity", void 0),
    __decorate([serialize()], a.prototype, "translucencyIntensity", void 0),
    __decorate([serialize()], a.prototype, "useAlbedoToTintRefraction", void 0),
    __decorate([serialize()], a.prototype, "useAlbedoToTintTranslucency", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "thicknessTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "refractionTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "indexOfRefraction", void 0),
    __decorate([serialize()], a.prototype, "_volumeIndexOfRefraction", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "volumeIndexOfRefraction", null),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "invertRefractionY", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "linkRefractionWithTransparency", void 0),
    __decorate([serialize()], a.prototype, "minimumThickness", void 0),
    __decorate([serialize()], a.prototype, "maximumThickness", void 0),
    __decorate([serialize()], a.prototype, "useThicknessAsDepth", void 0),
    __decorate([serializeAsColor3()], a.prototype, "tintColor", void 0),
    __decorate([serialize()], a.prototype, "tintColorAtDistance", void 0),
    __decorate([serializeAsColor3()], a.prototype, "diffusionDistance", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "useMaskFromThicknessTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "refractionIntensityTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "translucencyIntensityTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], a.prototype, "useGltfStyleTextures", void 0),
    a
}()
  , name$1e = "pbrFragmentDeclaration"
  , shader$1e = `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$1e] = shader$1e;
var name$1d = "pbrUboDeclaration"
  , shader$1d = `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$1d] = shader$1d;
var name$1c = "pbrFragmentExtraDeclaration"
  , shader$1c = `
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$1c] = shader$1c;
var name$1b = "samplerFragmentAlternateDeclaration"
  , shader$1b = `#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$1b] = shader$1b;
var name$1a = "pbrFragmentSamplersDeclaration"
  , shader$1a = `#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$1a] = shader$1a;
var name$19 = "subSurfaceScatteringFunctions"
  , shader$19 = `bool testLightingForSSS(float diffusionProfile)
{
return diffusionProfile<1.;
}`;
ShaderStore.IncludesShadersStore[name$19] = shader$19;
var name$18 = "importanceSampling"
  , shader$18 = `




























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$18] = shader$18;
var name$17 = "pbrHelperFunctions"
  , shader$17 = `
#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$17] = shader$17;
var name$16 = "harmonicsFunctions"
  , shader$16 = `#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$16] = shader$16;
var name$15 = "pbrDirectLightingSetupFunctions"
  , shader$15 = `
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$15] = shader$15;
var name$14 = "pbrDirectLightingFalloffFunctions"
  , shader$14 = `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$14] = shader$14;
var name$13 = "pbrBRDFFunctions"
  , shader$13 = `
#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$13] = shader$13;
var name$12 = "hdrFilteringFunctions"
  , shader$12 = `#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$12] = shader$12;
var name$11 = "pbrDirectLightingFunctions"
  , shader$11 = `#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$11] = shader$11;
var name$10 = "pbrIBLFunctions"
  , shader$10 = `#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$10] = shader$10;
var name$$ = "pbrBlockAlbedoOpacity"
  , shader$$ = `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$$] = shader$$;
var name$_ = "pbrBlockReflectivity"
  , shader$_ = `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$_] = shader$_;
var name$Z = "pbrBlockAmbientOcclusion"
  , shader$Z = `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$Z] = shader$Z;
var name$Y = "pbrBlockAlphaFresnel"
  , shader$Y = `#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$Y] = shader$Y;
var name$X = "pbrBlockAnisotropic"
  , shader$X = `#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$X] = shader$X;
var name$W = "pbrBlockReflection"
  , shader$W = `#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$W] = shader$W;
var name$V = "pbrBlockSheen"
  , shader$V = `#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$V] = shader$V;
var name$U = "pbrBlockClearcoat"
  , shader$U = `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$U] = shader$U;
var name$T = "pbrBlockSubSurface"
  , shader$T = `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$T] = shader$T;
var name$S = "pbrBlockNormalGeometric"
  , shader$S = `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$S] = shader$S;
var name$R = "pbrBlockNormalFinal"
  , shader$R = `#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$R] = shader$R;
var name$Q = "pbrBlockLightmapInit"
  , shader$Q = `#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$Q] = shader$Q;
var name$P = "pbrBlockGeometryInfo"
  , shader$P = `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$P] = shader$P;
var name$O = "pbrBlockReflectance0"
  , shader$O = `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$O] = shader$O;
var name$N = "pbrBlockReflectance"
  , shader$N = `#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$N] = shader$N;
var name$M = "pbrBlockDirectLighting"
  , shader$M = `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$M] = shader$M;
var name$L = "pbrBlockFinalLitComponents"
  , shader$L = `



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

            vec4 vSheenColor = vec4(` + s + ", " + c + `);

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

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

            reflectionOutParams reflectionOut;

            reflectionBlock(
                ` + ("v_" + this.worldPosition.associatedVariableName + ".xyz") + `,
                ` + o + `,
                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
`,
        s
    }
    ,
    e.prototype._buildBlock = function(i) {
        return this._scene = i.sharedData.scene,
        i.target !== NodeMaterialBlockTargets.Fragment && (this._defineLODReflectionAlpha = i._getFreeDefineName("LODINREFLECTIONALPHA"),
        this._defineLinearSpecularReflection = i._getFreeDefineName("LINEARSPECULARREFLECTION")),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return this.texture && (i += this._codeVariableName + ".texture.gammaSpace = " + this.texture.gammaSpace + `;\r
`),
        i += this._codeVariableName + ".useSphericalHarmonics = " + this.useSphericalHarmonics + `;\r
`,
        i += this._codeVariableName + ".forceIrradianceInFragment = " + this.forceIrradianceInFragment + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i, o, s = a.prototype.serialize.call(this);
        return s.useSphericalHarmonics = this.useSphericalHarmonics,
        s.forceIrradianceInFragment = this.forceIrradianceInFragment,
        s.gammaSpace = (o = (i = this.texture) === null || i === void 0 ? void 0 : i.gammaSpace) !== null && o !== void 0 ? o : !0,
        s
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.useSphericalHarmonics = i.useSphericalHarmonics,
        this.forceIrradianceInFragment = i.forceIrradianceInFragment,
        this.texture && (this.texture.gammaSpace = i.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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.remapF0OnInterfaceChange = !0,
        o._isUnique = !0,
        o.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("tintThickness", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        o.registerOutput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat",o,NodeMaterialConnectionPointDirection.Output,e,"ClearCoatBlock")),
        o
    }
    return e.prototype.initialize = function(i) {
        i._excludeVariableName("clearcoatOut"),
        i._excludeVariableName("vClearCoatParams"),
        i._excludeVariableName("vClearCoatTintParams"),
        i._excludeVariableName("vClearCoatRefractionParams"),
        i._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(i) {
        if (!this.intensity.isConnected) {
            var o = new InputBlock("ClearCoat intensity",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);
            o.value = 1,
            o.output.connectTo(this.intensity)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        a.prototype.prepareDefines.call(this, i, o, s),
        s.setValue("CLEARCOAT", !0),
        s.setValue("CLEARCOAT_TEXTURE", !1, !0),
        s.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE", !0, !0),
        s.setValue("CLEARCOAT_TINT", this.tintColor.isConnected || this.tintThickness.isConnected || this.tintAtDistance.isConnected, !0),
        s.setValue("CLEARCOAT_BUMP", this.normalMapColor.isConnected, !0),
        s.setValue("CLEARCOAT_DEFAULTIOR", this.indexOfRefraction.isConnected ? this.indexOfRefraction.connectInputBlock.value === PBRClearCoatConfiguration._DefaultIndexOfRefraction : !0, !0),
        s.setValue("CLEARCOAT_REMAP_F0", this.remapF0OnInterfaceChange, !0)
    }
    ,
    e.prototype.bind = function(i, o, s, c) {
        var d, _;
        a.prototype.bind.call(this, i, o, s);
        var b = (_ = (d = this.indexOfRefraction.connectInputBlock) === null || d === void 0 ? void 0 : d.value) !== null && _ !== void 0 ? _ : PBRClearCoatConfiguration._DefaultIndexOfRefraction
          , k = 1 - b
          , j = 1 + b
          , $ = Math.pow(-k / j, 2)
          , _e = 1 / b;
        i.setFloat4("vClearCoatRefractionParams", $, _e, k, j);
        var et = this.clearcoat.hasEndpoints ? this.clearcoat.endpoints[0].ownerBlock : null
          , tt = et != null && et.perturbedNormal.isConnected ? et.perturbedNormal.connectedPoint.ownerBlock : null;
        this._scene._mirroredCameraPosition ? i.setFloat2("vClearCoatTangentSpaceParams", tt != null && tt.invertX ? 1 : -1, tt != null && tt.invertY ? 1 : -1) : i.setFloat2("vClearCoatTangentSpaceParams", tt != null && tt.invertX ? -1 : 1, tt != null && tt.invertY ? -1 : 1)
    }
    ,
    e.prototype._generateTBNSpace = function(i, o, s) {
        var c = ""
          , d = "//" + this.name
          , _ = this.worldTangent;
        i._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
        var b = {
            search: /defined\(TANGENT\)/g,
            replace: _.isConnected ? "defined(TANGENT)" : "defined(IGNORE)"
        };
        return _.isConnected && (c += "vec3 tbnNormal = normalize(" + s + `.xyz);\r
`,
        c += "vec3 tbnTangent = normalize(" + _.associatedVariableName + `.xyz);\r
`,
        c += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r
`,
        c += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r
`),
        i._emitFunctionFromInclude("bumpFragmentMainFunctions", d, {
            replaceStrings: [b]
        }),
        c
    }
    ,
    e.GetCode = function(i, o, s, c, d, _, b) {
        var k = ""
          , j = o != null && o.intensity.isConnected ? o.intensity.associatedVariableName : "1."
          , $ = o != null && o.roughness.isConnected ? o.roughness.associatedVariableName : "0."
          , _e = o != null && o.normalMapColor.isConnected ? o.normalMapColor.associatedVariableName : "vec3(0.)"
          , et = o != null && o.uv.isConnected ? o.uv.associatedVariableName : "vec2(0.)"
          , tt = o != null && o.tintColor.isConnected ? o.tintColor.associatedVariableName : "vec3(1.)"
          , rt = o != null && o.tintThickness.isConnected ? o.tintThickness.associatedVariableName : "1."
          , it = o != null && o.tintAtDistance.isConnected ? o.tintAtDistance.associatedVariableName : "1."
          , nt = "vec4(0.)";
        return o && (i._emitUniformFromString("vClearCoatRefractionParams", "vec4"),
        i._emitUniformFromString("vClearCoatTangentSpaceParams", "vec2")),
        d && o && (k += o._generateTBNSpace(i, c, b),
        _ = o.worldTangent.isConnected),
        k += `clearcoatOutParams clearcoatOut;

        #ifdef CLEARCOAT
            vec2 vClearCoatParams = vec2(` + j + ", " + $ + `);
            vec4 vClearCoatTintParams = vec4(` + tt + ", " + rt + `);

            clearcoatBlock(
                ` + c + `.xyz,
                geometricNormalW,
                viewDirectionW,
                vClearCoatParams,
                specularEnvironmentR0,
            #ifdef CLEARCOAT_TEXTURE
                vec2(0.),
            #endif
            #ifdef CLEARCOAT_TINT
                vClearCoatTintParams,
                ` + it + `,
                vClearCoatRefractionParams,
                #ifdef CLEARCOAT_TINT_TEXTURE
                    ` + nt + `,
                #endif
            #endif
            #ifdef CLEARCOAT_BUMP
                vec2(0., 1.),
                vec4(` + _e + `, 0.),
                ` + et + `,
                #if defined(` + (_ ? "TANGENT" : "IGNORE") + `) && defined(NORMAL)
                    vTBN,
                #else
                    vClearCoatTangentSpaceParams,
                #endif
                #ifdef OBJECTSPACE_NORMALMAP
                    normalMatrix,
                #endif
            #endif
            #if defined(FORCENORMALFORWARD) && defined(NORMAL)
                faceNormal,
            #endif
            #ifdef REFLECTION
                ` + (s == null ? void 0 : s._vReflectionMicrosurfaceInfosName) + `,
                ` + (s == null ? void 0 : s._vReflectionInfosName) + `,
                ` + (s == null ? void 0 : s.reflectionColor) + `,
                vLightingIntensity,
                #ifdef ` + (s == null ? void 0 : s._define3DName) + `
                    ` + (s == null ? void 0 : s._cubeSamplerName) + `,
                #else
                    ` + (s == null ? void 0 : s._2DSamplerName) + `,
                #endif
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ` + (s == null ? void 0 : s._define3DName) + `
                        ` + (s == null ? void 0 : s._cubeSamplerName) + `,
                        ` + (s == null ? void 0 : s._cubeSamplerName) + `,
                    #else
                        ` + (s == null ? void 0 : s._2DSamplerName) + `,
                        ` + (s == null ? void 0 : s._2DSamplerName) + `,
                    #endif
                #endif
            #endif
            #if defined(ENVIRONMENTBRDF) && !defined(` + (s == null ? void 0 : s._defineSkyboxName) + `)
                #ifdef RADIANCEOCCLUSION
                    ambientMonochrome,
                #endif
            #endif
            #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
                (gl_FrontFacing ? 1. : -1.),
            #endif
                clearcoatOut
            );
        #else
            clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;
        #endif\r
`,
        k
    }
    ,
    e.prototype._buildBlock = function(i) {
        return this._scene = i.sharedData.scene,
        i.target === NodeMaterialBlockTargets.Fragment && (i.sharedData.bindableBlocks.push(this),
        i.sharedData.blocksWithDefines.push(this)),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return i += this._codeVariableName + ".remapF0OnInterfaceChange = " + this.remapF0OnInterfaceChange + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.remapF0OnInterfaceChange = this.remapF0OnInterfaceChange,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        var c;
        a.prototype._deserialize.call(this, i, o, s),
        this.remapF0OnInterfaceChange = (c = i.remapF0OnInterfaceChange) !== null && c !== void 0 ? c : !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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o.linkRefractionWithTransparency = !1,
        o.invertRefractionY = !1,
        o.useThicknessAsDepth = !1,
        o._isUnique = !0,
        o.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("volumeIndexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction",o,NodeMaterialConnectionPointDirection.Output,e,"RefractionBlock")),
        o
    }
    return e.prototype.initialize = function(i) {
        i._excludeVariableName("vRefractionPosition"),
        i._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(i) {
        if (!this.intensity.isConnected) {
            var o = new InputBlock("Refraction intensity",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);
            o.value = 1,
            o.output.connectTo(this.intensity)
        }
        if (this.view && !this.view.isConnected) {
            var s = i.getInputBlockByPredicate(function(c) {
                return c.systemValue === NodeMaterialSystemValues.View
            });
            s || (s = new InputBlock("view"),
            s.setAsSystemValue(NodeMaterialSystemValues.View)),
            s.output.connectTo(this.view)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        a.prototype.prepareDefines.call(this, i, o, s);
        var c = this._getTexture()
          , d = c && c.getTextureMatrix;
        s.setValue("SS_REFRACTION", d, !0),
        d && (s.setValue(this._define3DName, c.isCube, !0),
        s.setValue(this._defineLODRefractionAlpha, c.lodLevelInAlpha, !0),
        s.setValue(this._defineLinearSpecularRefraction, c.linearSpecularLOD, !0),
        s.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !c.invertZ : c.invertZ, !0),
        s.setValue("SS_LINKREFRACTIONTOTRANSPARENCY", this.linkRefractionWithTransparency, !0),
        s.setValue("SS_GAMMAREFRACTION", c.gammaSpace, !0),
        s.setValue("SS_RGBDREFRACTION", c.isRGBD, !0),
        s.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC", !!c.boundingBoxSize, !0),
        s.setValue("SS_USE_THICKNESS_AS_DEPTH", this.useThicknessAsDepth, !0))
    }
    ,
    e.prototype.isReady = function() {
        var i = this._getTexture();
        return !(i && !i.isReadyOrNotBlocking())
    }
    ,
    e.prototype.bind = function(i, o, s, c) {
        var d, _, b, k;
        a.prototype.bind.call(this, i, o, s);
        var j = this._getTexture();
        if (!!j) {
            j.isCube ? i.setTexture(this._cubeSamplerName, j) : i.setTexture(this._2DSamplerName, j),
            i.setMatrix(this._refractionMatrixName, j.getReflectionTextureMatrix());
            var $ = 1;
            j.isCube || j.depth && ($ = j.depth);
            var _e = (k = (_ = (d = this.volumeIndexOfRefraction.connectInputBlock) === null || d === void 0 ? void 0 : d.value) !== null && _ !== void 0 ? _ : (b = this.indexOfRefractionConnectionPoint.connectInputBlock) === null || b === void 0 ? void 0 : b.value) !== null && k !== void 0 ? k : 1.5;
            i.setFloat4(this._vRefractionInfosName, j.level, 1 / _e, $, this.invertRefractionY ? -1 : 1),
            i.setFloat4(this._vRefractionMicrosurfaceInfosName, j.getSize().width, j.lodGenerationScale, j.lodGenerationOffset, 1 / _e);
            var et = j.getSize().width;
            if (i.setFloat2(this._vRefractionFilteringInfoName, et, Scalar.Log2(et)),
            j.boundingBoxSize) {
                var tt = j;
                i.setVector3("vRefractionPosition", tt.boundingBoxPosition),
                i.setVector3("vRefractionSize", tt.boundingBoxSize)
            }
        }
    }
    ,
    e.prototype.getCode = function(i) {
        var o = "";
        return i.sharedData.blockingBlocks.push(this),
        i.sharedData.textureBlocks.push(this),
        this._cubeSamplerName = i._getFreeVariableName(this.name + "CubeSampler"),
        i.samplers.push(this._cubeSamplerName),
        this._2DSamplerName = i._getFreeVariableName(this.name + "2DSampler"),
        i.samplers.push(this._2DSamplerName),
        this._define3DName = i._getFreeDefineName("SS_REFRACTIONMAP_3D"),
        i._samplerDeclaration += "#ifdef " + this._define3DName + `\r
`,
        i._samplerDeclaration += "uniform samplerCube " + this._cubeSamplerName + `;\r
`,
        i._samplerDeclaration += `#else\r
`,
        i._samplerDeclaration += "uniform sampler2D " + this._2DSamplerName + `;\r
`,
        i._samplerDeclaration += `#endif\r
`,
        i.sharedData.blocksWithDefines.push(this),
        i.sharedData.bindableBlocks.push(this),
        this._defineLODRefractionAlpha = i._getFreeDefineName("SS_LODINREFRACTIONALPHA"),
        this._defineLinearSpecularRefraction = i._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),
        this._defineOppositeZ = i._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),
        this._refractionMatrixName = i._getFreeVariableName("refractionMatrix"),
        i._emitUniformFromString(this._refractionMatrixName, "mat4"),
        i._emitFunction("sampleRefraction", `
            #ifdef ` + this._define3DName + `
                #define sampleRefraction(s, c) textureCube(s, c)
            #else
                #define sampleRefraction(s, c) texture2D(s, c)
            #endif\r
`, "//" + this.name),
        i._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 = i._getFreeVariableName("vRefractionMicrosurfaceInfos"),
        i._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, "vec4"),
        this._vRefractionInfosName = i._getFreeVariableName("vRefractionInfos"),
        i._emitUniformFromString(this._vRefractionInfosName, "vec4"),
        this._vRefractionFilteringInfoName = i._getFreeVariableName("vRefractionFilteringInfo"),
        i._emitUniformFromString(this._vRefractionFilteringInfoName, "vec2"),
        i._emitUniformFromString("vRefractionPosition", "vec3"),
        i._emitUniformFromString("vRefractionSize", "vec3"),
        o
    }
    ,
    e.prototype._buildBlock = function(i) {
        return this._scene = i.sharedData.scene,
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return this.texture && (this.texture.isCube ? i = this._codeVariableName + '.texture = new BABYLON.CubeTexture("' + this.texture.name + `");\r
` : i = this._codeVariableName + '.texture = new BABYLON.Texture("' + this.texture.name + `");\r
`,
        i += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + `;\r
`),
        i += this._codeVariableName + ".linkRefractionWithTransparency = " + this.linkRefractionWithTransparency + `;\r
`,
        i += this._codeVariableName + ".invertRefractionY = " + this.invertRefractionY + `;\r
`,
        i += this._codeVariableName + ".useThicknessAsDepth = " + this.useThicknessAsDepth + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return this.texture && !this.texture.isRenderTarget && (i.texture = this.texture.serialize()),
        i.linkRefractionWithTransparency = this.linkRefractionWithTransparency,
        i.invertRefractionY = this.invertRefractionY,
        i.useThicknessAsDepth = this.useThicknessAsDepth,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        i.texture && (s = i.texture.url.indexOf("data:") === 0 ? "" : s,
        i.texture.isCube ? this.texture = CubeTexture.Parse(i.texture, o, s) : this.texture = Texture.Parse(i.texture, o, s)),
        this.linkRefractionWithTransparency = i.linkRefractionWithTransparency,
        this.invertRefractionY = i.invertRefractionY,
        this.useThicknessAsDepth = !!i.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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Fragment) || this;
        return o._isUnique = !0,
        o.registerInput("thickness", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        o.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("translucencyIntensity", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("translucencyDiffusionDist", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        o.registerInput("refraction", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction",o,NodeMaterialConnectionPointDirection.Input,RefractionBlock,"RefractionBlock")),
        o.registerOutput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface",o,NodeMaterialConnectionPointDirection.Output,e,"SubSurfaceBlock")),
        o
    }
    return e.prototype.initialize = function(i) {
        i._excludeVariableName("subSurfaceOut"),
        i._excludeVariableName("vThicknessParam"),
        i._excludeVariableName("vTintColor"),
        i._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(i) {
        if (!this.thickness.isConnected) {
            var o = new InputBlock("SubSurface thickness",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);
            o.value = 0,
            o.output.connectTo(this.thickness)
        }
    }
    ,
    e.prototype.prepareDefines = function(i, o, s) {
        a.prototype.prepareDefines.call(this, i, o, s);
        var c = this.translucencyDiffusionDist.isConnected || this.translucencyIntensity.isConnected;
        s.setValue("SUBSURFACE", c || this.refraction.isConnected, !0),
        s.setValue("SS_TRANSLUCENCY", c, !0),
        s.setValue("SS_THICKNESSANDMASK_TEXTURE", !1, !0),
        s.setValue("SS_REFRACTIONINTENSITY_TEXTURE", !1, !0),
        s.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE", !1, !0),
        s.setValue("SS_MASK_FROM_THICKNESS_TEXTURE", !1, !0),
        s.setValue("SS_USE_GLTF_TEXTURES", !1, !0)
    }
    ,
    e.GetCode = function(i, o, s, c) {
        var d, _, b, k, j, $, _e, et, tt, rt, it, nt, ot, at, st, ut, ct = "", lt = o != null && o.thickness.isConnected ? o.thickness.associatedVariableName : "0.", ft = o != null && o.tintColor.isConnected ? o.tintColor.associatedVariableName : "vec3(1.)", ht = o != null && o.translucencyIntensity.isConnected ? o == null ? void 0 : o.translucencyIntensity.associatedVariableName : "1.", pt = o != null && o.translucencyDiffusionDist.isConnected ? o == null ? void 0 : o.translucencyDiffusionDist.associatedVariableName : "vec3(1.)", dt = o != null && o.refraction.isConnected ? (d = o == null ? void 0 : o.refraction.connectedPoint) === null || d === void 0 ? void 0 : d.ownerBlock : null, _t = dt != null && dt.tintAtDistance.isConnected ? dt.tintAtDistance.associatedVariableName : "1.", mt = dt != null && dt.intensity.isConnected ? dt.intensity.associatedVariableName : "1.", vt = dt != null && dt.view.isConnected ? dt.view.associatedVariableName : "";
        return ct += (_ = dt == null ? void 0 : dt.getCode(i)) !== null && _ !== void 0 ? _ : "",
        ct += `subSurfaceOutParams subSurfaceOut;

        #ifdef SUBSURFACE
            vec2 vThicknessParam = vec2(0., ` + lt + `);
            vec4 vTintColor = vec4(` + ft + ", " + _t + `);
            vec3 vSubSurfaceIntensity = vec3(` + mt + ", " + ht + `, 0.);

            subSurfaceBlock(
                vSubSurfaceIntensity,
                vThicknessParam,
                vTintColor,
                normalW,
                specularEnvironmentReflectance,
            #ifdef SS_THICKNESSANDMASK_TEXTURE
                vec4(0.),
            #endif
            #ifdef REFLECTION
                #ifdef SS_TRANSLUCENCY
                    ` + (s == null ? void 0 : s._reflectionMatrixName) + `,
                    #ifdef USESPHERICALFROMREFLECTIONMAP
                        #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
                            reflectionOut.irradianceVector,
                        #endif
                        #if defined(REALTIME_FILTERING)
                            ` + (s == null ? void 0 : s._cubeSamplerName) + `,
                            ` + (s == null ? void 0 : s._vReflectionFilteringInfoName) + `,
                        #endif
                        #endif
                    #ifdef USEIRRADIANCEMAP
                        irradianceSampler,
                    #endif
                #endif
            #endif
            #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
                surfaceAlbedo,
            #endif
            #ifdef SS_REFRACTION
                ` + c + `.xyz,
                viewDirectionW,
                ` + vt + `,
                ` + ((b = dt == null ? void 0 : dt._vRefractionInfosName) !== null && b !== void 0 ? b : "") + `,
                ` + ((k = dt == null ? void 0 : dt._refractionMatrixName) !== null && k !== void 0 ? k : "") + `,
                ` + ((j = dt == null ? void 0 : dt._vRefractionMicrosurfaceInfosName) !== null && j !== void 0 ? j : "") + `,
                vLightingIntensity,
                #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
                    alpha,
                #endif
                #ifdef ` + (($ = dt == null ? void 0 : dt._defineLODRefractionAlpha) !== null && $ !== void 0 ? $ : "IGNORE") + `
                    NdotVUnclamped,
                #endif
                #ifdef ` + ((_e = dt == null ? void 0 : dt._defineLinearSpecularRefraction) !== null && _e !== void 0 ? _e : "IGNORE") + `
                    roughness,
                #endif
                alphaG,
                #ifdef ` + ((et = dt == null ? void 0 : dt._define3DName) !== null && et !== void 0 ? et : "IGNORE") + `
                    ` + ((tt = dt == null ? void 0 : dt._cubeSamplerName) !== null && tt !== void 0 ? tt : "") + `,
                #else
                    ` + ((rt = dt == null ? void 0 : dt._2DSamplerName) !== null && rt !== void 0 ? rt : "") + `,
                #endif
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ` + ((it = dt == null ? void 0 : dt._define3DName) !== null && it !== void 0 ? it : "IGNORE") + `
                        ` + ((nt = dt == null ? void 0 : dt._cubeSamplerName) !== null && nt !== void 0 ? nt : "") + `,
                        ` + ((ot = dt == null ? void 0 : dt._cubeSamplerName) !== null && ot !== void 0 ? ot : "") + `,
                    #else
                        ` + ((at = dt == null ? void 0 : dt._2DSamplerName) !== null && at !== void 0 ? at : "") + `,
                        ` + ((st = dt == null ? void 0 : dt._2DSamplerName) !== null && st !== void 0 ? st : "") + `,
                    #endif
                #endif
                #ifdef ANISOTROPIC
                    anisotropicOut,
                #endif
                #ifdef REALTIME_FILTERING
                    ` + ((ut = dt == null ? void 0 : dt._vRefractionFilteringInfoName) !== null && ut !== void 0 ? ut : "") + `,
                #endif
                #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
                    vRefractionPosition,
                    vRefractionSize,
                #endif
            #endif
            #ifdef SS_TRANSLUCENCY
                ` + pt + `,
            #endif
                subSurfaceOut
            );

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

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

            reflectivityBlock(
                vec4(` + this.metallic.associatedVariableName + ", " + this.roughness.associatedVariableName + `, 0., 0.),
            #ifdef METALLICWORKFLOW
                surfaceAlbedo,
                ` + this._vMetallicReflectanceFactorsName + `,
            #endif
            #ifdef REFLECTIVITY
                vec3(0., 0., ` + s + `),
                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
`,
        o
    }
    ,
    e.prototype._buildBlock = function(i) {
        var o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it, nt, ot, at, st, ut, ct, lt, ft, ht, pt, dt, _t, mt, vt, yt, Et, At, gt, St, xt, bt, Rt, Mt, Pt, It, Dt;
        a.prototype._buildBlock.call(this, i),
        this._scene = i.sharedData.scene,
        this._environmentBRDFTexture || (this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this._scene));
        var Ct = this.reflection.isConnected ? (o = this.reflection.connectedPoint) === null || o === void 0 ? void 0 : o.ownerBlock : null;
        if (Ct && (Ct.worldPositionConnectionPoint = this.worldPosition,
        Ct.cameraPositionConnectionPoint = this.cameraPosition,
        Ct.worldNormalConnectionPoint = this.worldNormal),
        i.target !== NodeMaterialBlockTargets.Fragment)
            return this._injectVertexCode(i),
            this;
        i.sharedData.forcedBindableBlocks.push(this),
        i.sharedData.blocksWithDefines.push(this),
        i.sharedData.blockingBlocks.push(this);
        var Ot = "//" + this.name
          , wt = "v_" + this.worldPosition.associatedVariableName
          , Nt = this.perturbedNormal;
        this._environmentBrdfSamplerName = i._getFreeVariableName("environmentBrdfSampler"),
        i._emit2DSampler(this._environmentBrdfSamplerName),
        i.sharedData.hints.needAlphaBlending = i.sharedData.hints.needAlphaBlending || this.useAlphaBlending,
        i.sharedData.hints.needAlphaTesting = i.sharedData.hints.needAlphaTesting || this.useAlphaTest,
        i._emitExtension("lod", "#extension GL_EXT_shader_texture_lod : enable", "defined(LODBASEDMICROSFURACE)"),
        i._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"),
        i.uniforms.push("exposureLinear"),
        i.uniforms.push("contrast"),
        i.uniforms.push("vInverseScreenSize"),
        i.uniforms.push("vignetteSettings1"),
        i.uniforms.push("vignetteSettings2"),
        i.uniforms.push("vCameraColorCurveNegative"),
        i.uniforms.push("vCameraColorCurveNeutral"),
        i.uniforms.push("vCameraColorCurvePositive"),
        i.uniforms.push("txColorTransform"),
        i.uniforms.push("colorTransformSettings"),
        this.light ? i._emitFunctionFromInclude(i.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", Ot, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }, this._lightId.toString()) : i._emitFunctionFromInclude(i.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", Ot, {
            repeatKey: "maxSimultaneousLights"
        }),
        i._emitFunctionFromInclude("helperFunctions", Ot),
        i._emitFunctionFromInclude("importanceSampling", Ot),
        i._emitFunctionFromInclude("pbrHelperFunctions", Ot),
        i._emitFunctionFromInclude("imageProcessingDeclaration", Ot),
        i._emitFunctionFromInclude("imageProcessingFunctions", Ot),
        i._emitFunctionFromInclude("shadowsFragmentFunctions", Ot, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: wt + ".xyz"
            }]
        }),
        i._emitFunctionFromInclude("pbrDirectLightingSetupFunctions", Ot, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: wt + ".xyz"
            }]
        }),
        i._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions", Ot),
        i._emitFunctionFromInclude("pbrBRDFFunctions", Ot, {
            replaceStrings: [{
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (s = Ct == null ? void 0 : Ct._defineSkyboxName) !== null && s !== void 0 ? s : "REFLECTIONMAP_SKYBOX"
            }]
        }),
        i._emitFunctionFromInclude("hdrFilteringFunctions", Ot),
        i._emitFunctionFromInclude("pbrDirectLightingFunctions", Ot, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: wt + ".xyz"
            }]
        }),
        i._emitFunctionFromInclude("pbrIBLFunctions", Ot),
        i._emitFunctionFromInclude("pbrBlockAlbedoOpacity", Ot),
        i._emitFunctionFromInclude("pbrBlockReflectivity", Ot),
        i._emitFunctionFromInclude("pbrBlockAmbientOcclusion", Ot),
        i._emitFunctionFromInclude("pbrBlockAlphaFresnel", Ot),
        i._emitFunctionFromInclude("pbrBlockAnisotropic", Ot),
        i._emitUniformFromString("vLightingIntensity", "vec4"),
        this._vNormalWName = i._getFreeVariableName("vNormalW"),
        i.compilationString += "vec4 " + this._vNormalWName + " = normalize(" + this.worldNormal.associatedVariableName + `);\r
`,
        i._registerTempVariable("viewDirectionW") && (i.compilationString += "vec3 viewDirectionW = normalize(" + this.cameraPosition.associatedVariableName + " - " + wt + `.xyz);\r
`),
        i.compilationString += "vec3 geometricNormalW = " + this._vNormalWName + `.xyz;\r
`,
        i.compilationString += "vec3 normalW = " + (Nt.isConnected ? "normalize(" + Nt.associatedVariableName + ".xyz)" : "geometricNormalW") + `;\r
`,
        this._invertNormalName = i._getFreeVariableName("invertNormal"),
        i._emitUniformFromString(this._invertNormalName, "float"),
        i.compilationString += i._emitCodeFromInclude("pbrBlockNormalFinal", Ot, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: wt + ".xyz"
            }, {
                search: /vEyePosition.w/g,
                replace: this._invertNormalName
            }]
        }),
        i.compilationString += this._getAlbedoOpacityCode(),
        i.compilationString += i._emitCodeFromInclude("depthPrePass", Ot),
        i.compilationString += this._getAmbientOcclusionCode(),
        i.compilationString += i._emitCodeFromInclude("pbrBlockLightmapInit", Ot),
        i.compilationString += `#ifdef UNLIT
                vec3 diffuseBase = vec3(1., 1., 1.);
            #else\r
`,
        i.compilationString += this._getReflectivityCode(i),
        i.compilationString += i._emitCodeFromInclude("pbrBlockGeometryInfo", Ot, {
            replaceStrings: [{
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (c = Ct == null ? void 0 : Ct._defineSkyboxName) !== null && c !== void 0 ? c : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /REFLECTIONMAP_3D/g,
                replace: (d = Ct == null ? void 0 : Ct._define3DName) !== null && d !== void 0 ? d : "REFLECTIONMAP_3D"
            }]
        });
        var Ft = this.anisotropy.isConnected ? (_ = this.anisotropy.connectedPoint) === null || _ === void 0 ? void 0 : _.ownerBlock : null;
        Ft && (Ft.worldPositionConnectionPoint = this.worldPosition,
        Ft.worldNormalConnectionPoint = this.worldNormal,
        i.compilationString += Ft.getCode(i, !this.perturbedNormal.isConnected)),
        Ct && Ct.hasTexture && (i.compilationString += Ct.getCode(i, Ft ? "anisotropicOut.anisotropicNormal" : "normalW")),
        i._emitFunctionFromInclude("pbrBlockReflection", Ot, {
            replaceStrings: [{
                search: /computeReflectionCoords/g,
                replace: "computeReflectionCoordsPBR"
            }, {
                search: /REFLECTIONMAP_3D/g,
                replace: (b = Ct == null ? void 0 : Ct._define3DName) !== null && b !== void 0 ? b : "REFLECTIONMAP_3D"
            }, {
                search: /REFLECTIONMAP_OPPOSITEZ/g,
                replace: (k = Ct == null ? void 0 : Ct._defineOppositeZ) !== null && k !== void 0 ? k : "REFLECTIONMAP_OPPOSITEZ"
            }, {
                search: /REFLECTIONMAP_PROJECTION/g,
                replace: (j = Ct == null ? void 0 : Ct._defineProjectionName) !== null && j !== void 0 ? j : "REFLECTIONMAP_PROJECTION"
            }, {
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: ($ = Ct == null ? void 0 : Ct._defineSkyboxName) !== null && $ !== void 0 ? $ : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /LODINREFLECTIONALPHA/g,
                replace: (_e = Ct == null ? void 0 : Ct._defineLODReflectionAlpha) !== null && _e !== void 0 ? _e : "LODINREFLECTIONALPHA"
            }, {
                search: /LINEARSPECULARREFLECTION/g,
                replace: (et = Ct == null ? void 0 : Ct._defineLinearSpecularReflection) !== null && et !== void 0 ? et : "LINEARSPECULARREFLECTION"
            }, {
                search: /vReflectionFilteringInfo/g,
                replace: (tt = Ct == null ? void 0 : Ct._vReflectionFilteringInfoName) !== null && tt !== void 0 ? tt : "vReflectionFilteringInfo"
            }]
        }),
        i.compilationString += i._emitCodeFromInclude("pbrBlockReflectance0", Ot, {
            replaceStrings: [{
                search: /metallicReflectanceFactors/g,
                replace: this._vMetallicReflectanceFactorsName
            }]
        });
        var Vt = this.sheen.isConnected ? (rt = this.sheen.connectedPoint) === null || rt === void 0 ? void 0 : rt.ownerBlock : null;
        Vt && (i.compilationString += Vt.getCode(Ct)),
        i._emitFunctionFromInclude("pbrBlockSheen", Ot, {
            replaceStrings: [{
                search: /REFLECTIONMAP_3D/g,
                replace: (it = Ct == null ? void 0 : Ct._define3DName) !== null && it !== void 0 ? it : "REFLECTIONMAP_3D"
            }, {
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (nt = Ct == null ? void 0 : Ct._defineSkyboxName) !== null && nt !== void 0 ? nt : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /LODINREFLECTIONALPHA/g,
                replace: (ot = Ct == null ? void 0 : Ct._defineLODReflectionAlpha) !== null && ot !== void 0 ? ot : "LODINREFLECTIONALPHA"
            }, {
                search: /LINEARSPECULARREFLECTION/g,
                replace: (at = Ct == null ? void 0 : Ct._defineLinearSpecularReflection) !== null && at !== void 0 ? at : "LINEARSPECULARREFLECTION"
            }]
        });
        var Lt = this.clearcoat.isConnected ? (st = this.clearcoat.connectedPoint) === null || st === void 0 ? void 0 : st.ownerBlock : null
          , kt = !this.perturbedNormal.isConnected && !this.anisotropy.isConnected
          , Bt = this.perturbedNormal.isConnected && ((ct = ((ut = this.perturbedNormal.connectedPoint) === null || ut === void 0 ? void 0 : ut.ownerBlock).worldTangent) === null || ct === void 0 ? void 0 : ct.isConnected)
          , Ut = this.anisotropy.isConnected && ((lt = this.anisotropy.connectedPoint) === null || lt === void 0 ? void 0 : lt.ownerBlock).worldTangent.isConnected
          , Gt = Bt || !this.perturbedNormal.isConnected && Ut;
        i.compilationString += ClearCoatBlock.GetCode(i, Lt, Ct, wt, kt, Gt, this.worldNormal.associatedVariableName),
        kt && (Gt = (ft = Lt == null ? void 0 : Lt.worldTangent.isConnected) !== null && ft !== void 0 ? ft : !1),
        i._emitFunctionFromInclude("pbrBlockClearcoat", Ot, {
            replaceStrings: [{
                search: /computeReflectionCoords/g,
                replace: "computeReflectionCoordsPBR"
            }, {
                search: /REFLECTIONMAP_3D/g,
                replace: (ht = Ct == null ? void 0 : Ct._define3DName) !== null && ht !== void 0 ? ht : "REFLECTIONMAP_3D"
            }, {
                search: /REFLECTIONMAP_OPPOSITEZ/g,
                replace: (pt = Ct == null ? void 0 : Ct._defineOppositeZ) !== null && pt !== void 0 ? pt : "REFLECTIONMAP_OPPOSITEZ"
            }, {
                search: /REFLECTIONMAP_PROJECTION/g,
                replace: (dt = Ct == null ? void 0 : Ct._defineProjectionName) !== null && dt !== void 0 ? dt : "REFLECTIONMAP_PROJECTION"
            }, {
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (_t = Ct == null ? void 0 : Ct._defineSkyboxName) !== null && _t !== void 0 ? _t : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /LODINREFLECTIONALPHA/g,
                replace: (mt = Ct == null ? void 0 : Ct._defineLODReflectionAlpha) !== null && mt !== void 0 ? mt : "LODINREFLECTIONALPHA"
            }, {
                search: /LINEARSPECULARREFLECTION/g,
                replace: (vt = Ct == null ? void 0 : Ct._defineLinearSpecularReflection) !== null && vt !== void 0 ? vt : "LINEARSPECULARREFLECTION"
            }, {
                search: /defined\(TANGENT\)/g,
                replace: Gt ? "defined(TANGENT)" : "defined(IGNORE)"
            }]
        }),
        i.compilationString += i._emitCodeFromInclude("pbrBlockReflectance", Ot, {
            replaceStrings: [{
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (yt = Ct == null ? void 0 : Ct._defineSkyboxName) !== null && yt !== void 0 ? yt : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /REFLECTIONMAP_3D/g,
                replace: (Et = Ct == null ? void 0 : Ct._define3DName) !== null && Et !== void 0 ? Et : "REFLECTIONMAP_3D"
            }]
        });
        var Ht = this.subsurface.isConnected ? (At = this.subsurface.connectedPoint) === null || At === void 0 ? void 0 : At.ownerBlock : null
          , zt = this.subsurface.isConnected ? (St = ((gt = this.subsurface.connectedPoint) === null || gt === void 0 ? void 0 : gt.ownerBlock).refraction.connectedPoint) === null || St === void 0 ? void 0 : St.ownerBlock : null;
        zt && (zt.viewConnectionPoint = this.view,
        zt.indexOfRefractionConnectionPoint = this.indexOfRefraction),
        i.compilationString += SubSurfaceBlock.GetCode(i, Ht, Ct, wt),
        i._emitFunctionFromInclude("pbrBlockSubSurface", Ot, {
            replaceStrings: [{
                search: /REFLECTIONMAP_3D/g,
                replace: (xt = Ct == null ? void 0 : Ct._define3DName) !== null && xt !== void 0 ? xt : "REFLECTIONMAP_3D"
            }, {
                search: /REFLECTIONMAP_OPPOSITEZ/g,
                replace: (bt = Ct == null ? void 0 : Ct._defineOppositeZ) !== null && bt !== void 0 ? bt : "REFLECTIONMAP_OPPOSITEZ"
            }, {
                search: /REFLECTIONMAP_PROJECTION/g,
                replace: (Rt = Ct == null ? void 0 : Ct._defineProjectionName) !== null && Rt !== void 0 ? Rt : "REFLECTIONMAP_PROJECTION"
            }, {
                search: /SS_REFRACTIONMAP_3D/g,
                replace: (Mt = zt == null ? void 0 : zt._define3DName) !== null && Mt !== void 0 ? Mt : "SS_REFRACTIONMAP_3D"
            }, {
                search: /SS_LODINREFRACTIONALPHA/g,
                replace: (Pt = zt == null ? void 0 : zt._defineLODRefractionAlpha) !== null && Pt !== void 0 ? Pt : "SS_LODINREFRACTIONALPHA"
            }, {
                search: /SS_LINEARSPECULARREFRACTION/g,
                replace: (It = zt == null ? void 0 : zt._defineLinearSpecularRefraction) !== null && It !== void 0 ? It : "SS_LINEARSPECULARREFRACTION"
            }, {
                search: /SS_REFRACTIONMAP_OPPOSITEZ/g,
                replace: (Dt = zt == null ? void 0 : zt._defineOppositeZ) !== null && Dt !== void 0 ? Dt : "SS_REFRACTIONMAP_OPPOSITEZ"
            }]
        }),
        i.compilationString += i._emitCodeFromInclude("pbrBlockDirectLighting", Ot),
        this.light ? i.compilationString += i._emitCodeFromInclude("lightFragment", Ot, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }) : i.compilationString += i._emitCodeFromInclude("lightFragment", Ot, {
            repeatKey: "maxSimultaneousLights"
        }),
        i.compilationString += i._emitCodeFromInclude("pbrBlockFinalLitComponents", Ot),
        i.compilationString += `#endif\r
`;
        var Wt = this.ambientColor.isConnected ? this.ambientColor.associatedVariableName : "vec3(0., 0., 0.)"
          , Kt = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();
        Kt.indexOf(".") === -1 && (Kt += "."),
        i.compilationString += i._emitCodeFromInclude("pbrBlockFinalUnlitComponents", Ot, {
            replaceStrings: [{
                search: /vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,
                replace: ""
            }, {
                search: /vAmbientColor/g,
                replace: Wt + " * ambientFromScene"
            }, {
                search: /vAmbientInfos\.w/g,
                replace: Kt
            }]
        }),
        i.compilationString += i._emitCodeFromInclude("pbrBlockFinalColorComposition", Ot, {
            replaceStrings: [{
                search: /finalEmissive/g,
                replace: "vec3(0.)"
            }]
        }),
        i.compilationString += i._emitCodeFromInclude("pbrBlockImageProcessing", Ot, {
            replaceStrings: [{
                search: /visibility/g,
                replace: "1."
            }]
        }),
        i.compilationString += i._emitCodeFromInclude("pbrDebug", Ot, {
            replaceStrings: [{
                search: /vNormalW/g,
                replace: this._vNormalWName
            }, {
                search: /vPositionW/g,
                replace: wt
            }, {
                search: /albedoTexture\.rgb;/g,
                replace: `vec3(1.);\r
gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\r
`
            }]
        });
        for (var Qt = 0, qt = this._outputs; Qt < qt.length; Qt++) {
            var Yt = qt[Qt];
            if (Yt.hasEndpoints) {
                var Jt = mapOutputToVariable[Yt.name];
                if (Jt) {
                    var jt = Jt[0]
                      , Xt = Jt[1];
                    Xt && (i.compilationString += "#if " + Xt + `\r
`),
                    i.compilationString += this._declareOutput(Yt, i) + " = " + jt + `;\r
`,
                    Xt && (i.compilationString += `#else\r
`,
                    i.compilationString += this._declareOutput(Yt, i) + ` = vec3(0.);\r
`,
                    i.compilationString += `#endif\r
`)
                } else
                    console.error("There's no remapping for the " + Yt.name + " end point! No code generated")
            }
        }
        return this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this);
        return i += this._codeVariableName + ".lightFalloff = " + this.lightFalloff + `;\r
`,
        i += this._codeVariableName + ".useAlphaTest = " + this.useAlphaTest + `;\r
`,
        i += this._codeVariableName + ".alphaTestCutoff = " + this.alphaTestCutoff + `;\r
`,
        i += this._codeVariableName + ".useAlphaBlending = " + this.useAlphaBlending + `;\r
`,
        i += this._codeVariableName + ".useRadianceOverAlpha = " + this.useRadianceOverAlpha + `;\r
`,
        i += this._codeVariableName + ".useSpecularOverAlpha = " + this.useSpecularOverAlpha + `;\r
`,
        i += this._codeVariableName + ".enableSpecularAntiAliasing = " + this.enableSpecularAntiAliasing + `;\r
`,
        i += this._codeVariableName + ".realTimeFiltering = " + this.realTimeFiltering + `;\r
`,
        i += this._codeVariableName + ".realTimeFilteringQuality = " + this.realTimeFilteringQuality + `;\r
`,
        i += this._codeVariableName + ".useEnergyConservation = " + this.useEnergyConservation + `;\r
`,
        i += this._codeVariableName + ".useRadianceOcclusion = " + this.useRadianceOcclusion + `;\r
`,
        i += this._codeVariableName + ".useHorizonOcclusion = " + this.useHorizonOcclusion + `;\r
`,
        i += this._codeVariableName + ".unlit = " + this.unlit + `;\r
`,
        i += this._codeVariableName + ".forceNormalForward = " + this.forceNormalForward + `;\r
`,
        i += this._codeVariableName + ".debugMode = " + this.debugMode + `;\r
`,
        i += this._codeVariableName + ".debugLimit = " + this.debugLimit + `;\r
`,
        i += this._codeVariableName + ".debugFactor = " + this.debugFactor + `;\r
`,
        i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return this.light && (i.lightId = this.light.id),
        i.lightFalloff = this.lightFalloff,
        i.useAlphaTest = this.useAlphaTest,
        i.alphaTestCutoff = this.alphaTestCutoff,
        i.useAlphaBlending = this.useAlphaBlending,
        i.useRadianceOverAlpha = this.useRadianceOverAlpha,
        i.useSpecularOverAlpha = this.useSpecularOverAlpha,
        i.enableSpecularAntiAliasing = this.enableSpecularAntiAliasing,
        i.realTimeFiltering = this.realTimeFiltering,
        i.realTimeFilteringQuality = this.realTimeFilteringQuality,
        i.useEnergyConservation = this.useEnergyConservation,
        i.useRadianceOcclusion = this.useRadianceOcclusion,
        i.useHorizonOcclusion = this.useHorizonOcclusion,
        i.unlit = this.unlit,
        i.forceNormalForward = this.forceNormalForward,
        i.debugMode = this.debugMode,
        i.debugLimit = this.debugLimit,
        i.debugFactor = this.debugFactor,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        var c, d;
        a.prototype._deserialize.call(this, i, o, s),
        i.lightId && (this.light = o.getLightById(i.lightId)),
        this.lightFalloff = (c = i.lightFalloff) !== null && c !== void 0 ? c : 0,
        this.useAlphaTest = i.useAlphaTest,
        this.alphaTestCutoff = i.alphaTestCutoff,
        this.useAlphaBlending = i.useAlphaBlending,
        this.useRadianceOverAlpha = i.useRadianceOverAlpha,
        this.useSpecularOverAlpha = i.useSpecularOverAlpha,
        this.enableSpecularAntiAliasing = i.enableSpecularAntiAliasing,
        this.realTimeFiltering = !!i.realTimeFiltering,
        this.realTimeFilteringQuality = (d = i.realTimeFilteringQuality) !== null && d !== void 0 ? d : 8,
        this.useEnergyConservation = i.useEnergyConservation,
        this.useRadianceOcclusion = i.useRadianceOcclusion,
        this.useHorizonOcclusion = i.useHorizonOcclusion,
        this.unlit = i.unlit,
        this.forceNormalForward = !!i.forceNormalForward,
        this.debugMode = i.debugMode,
        this.debugLimit = i.debugLimit,
        this.debugFactor = i.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(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._outputs[0]._typeConnectionSource = o._inputs[0],
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0];
        return i.compilationString += this._declareOutput(o, i) + (" = mod(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ModBlock", ModBlock);
var MatrixBuilderBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("row0", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("row1", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("row2", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerInput("row3", NodeMaterialBlockConnectionPointTypes.Vector4),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix),
        o
    }
    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(i) {
        if (!this.row0.isConnected) {
            var o = new InputBlock("row0");
            o.value = new Vector4(1,0,0,0),
            o.output.connectTo(this.row0)
        }
        if (!this.row1.isConnected) {
            var s = new InputBlock("row1");
            s.value = new Vector4(0,1,0,0),
            s.output.connectTo(this.row1)
        }
        if (!this.row2.isConnected) {
            var c = new InputBlock("row2");
            c.value = new Vector4(0,0,1,0),
            c.output.connectTo(this.row2)
        }
        if (!this.row3.isConnected) {
            var d = new InputBlock("row3");
            d.value = new Vector4(0,0,0,1),
            d.output.connectTo(this.row3)
        }
    }
    ,
    e.prototype._buildBlock = function(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = this.row0
          , c = this.row1
          , d = this.row2
          , _ = this.row3;
        return i.compilationString += this._declareOutput(o, i) + (" = mat4(" + s.associatedVariableName + ", " + c.associatedVariableName + ", " + d.associatedVariableName + ", " + _.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MatrixBuilder", MatrixBuilderBlock);
var ConditionalBlockConditions;
(function(a) {
    a[a.Equal = 0] = "Equal",
    a[a.NotEqual = 1] = "NotEqual",
    a[a.LessThan = 2] = "LessThan",
    a[a.GreaterThan = 3] = "GreaterThan",
    a[a.LessOrEqual = 4] = "LessOrEqual",
    a[a.GreaterOrEqual = 5] = "GreaterOrEqual",
    a[a.Xor = 6] = "Xor",
    a[a.Or = 7] = "Or",
    a[a.And = 8] = "And"
}
)(ConditionalBlockConditions || (ConditionalBlockConditions = {}));
var ConditionalBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.condition = ConditionalBlockConditions.LessThan,
        o.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("true", NodeMaterialBlockConnectionPointTypes.AutoDetect, !0),
        o.registerInput("false", NodeMaterialBlockConnectionPointTypes.AutoDetect, !0),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        o._linkConnectionTypes(2, 3),
        o._outputs[0]._typeConnectionSource = o._inputs[2],
        o._outputs[0]._defaultConnectionPointType = NodeMaterialBlockConnectionPointTypes.Float,
        o
    }
    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(i) {
        a.prototype._buildBlock.call(this, i);
        var o = this._outputs[0]
          , s = this.true.isConnected ? this.true.associatedVariableName : "1.0"
          , c = this.false.isConnected ? this.false.associatedVariableName : "0.0";
        switch (this.condition) {
        case ConditionalBlockConditions.Equal:
            {
                i.compilationString += this._declareOutput(o, i) + (" = " + this.a.associatedVariableName + " == " + this.b.associatedVariableName + " ? " + s + " : " + c + `;\r
`);
                break
            }
        case ConditionalBlockConditions.NotEqual:
            {
                i.compilationString += this._declareOutput(o, i) + (" = " + this.a.associatedVariableName + " != " + this.b.associatedVariableName + " ? " + s + " : " + c + `;\r
`);
                break
            }
        case ConditionalBlockConditions.LessThan:
            {
                i.compilationString += this._declareOutput(o, i) + (" = " + this.a.associatedVariableName + " < " + this.b.associatedVariableName + " ? " + s + " : " + c + `;\r
`);
                break
            }
        case ConditionalBlockConditions.LessOrEqual:
            {
                i.compilationString += this._declareOutput(o, i) + (" = " + this.a.associatedVariableName + " <= " + this.b.associatedVariableName + " ? " + s + " : " + c + `;\r
`);
                break
            }
        case ConditionalBlockConditions.GreaterThan:
            {
                i.compilationString += this._declareOutput(o, i) + (" = " + this.a.associatedVariableName + " > " + this.b.associatedVariableName + " ? " + s + " : " + c + `;\r
`);
                break
            }
        case ConditionalBlockConditions.GreaterOrEqual:
            {
                i.compilationString += this._declareOutput(o, i) + (" = " + this.a.associatedVariableName + " >= " + this.b.associatedVariableName + " ? " + s + " : " + c + `;\r
`);
                break
            }
        case ConditionalBlockConditions.Xor:
            {
                i.compilationString += this._declareOutput(o, i) + (" = (mod(" + this.a.associatedVariableName + " + " + this.b.associatedVariableName + ", 2.0) > 0.0) ? " + s + " : " + c + `;\r
`);
                break
            }
        case ConditionalBlockConditions.Or:
            {
                i.compilationString += this._declareOutput(o, i) + (" = (min(" + this.a.associatedVariableName + " + " + this.b.associatedVariableName + ", 1.0) > 0.0) ? " + s + " : " + c + `;\r
`);
                break
            }
        case ConditionalBlockConditions.And:
            {
                i.compilationString += this._declareOutput(o, i) + (" = (" + this.a.associatedVariableName + " * " + this.b.associatedVariableName + " > 0.0)  ? " + s + " : " + c + `;\r
`);
                break
            }
        }
        return this
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.condition = this.condition,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.condition = i.condition
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".condition = BABYLON.ConditionalBlockConditions." + ConditionalBlockConditions[this.condition] + `;\r
`);
        return i
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ConditionalBlock", ConditionalBlock);
var CloudBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.octaves = 6,
        o.registerInput("seed", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        o.registerInput("chaos", NodeMaterialBlockConnectionPointTypes.AutoDetect, !0),
        o.registerInput("offsetX", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("offsetY", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerInput("offsetZ", NodeMaterialBlockConnectionPointTypes.Float, !0),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),
        o._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        o._linkConnectionTypes(0, 1),
        o
    }
    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(i) {
        var o, s;
        if (a.prototype._buildBlock.call(this, i),
        !!this.seed.isConnected && !!this._outputs[0].hasEndpoints) {
            var c = `

        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);
        }`
              , d = `
        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;
        }`
              , _ = "fbm" + this.octaves;
            i._emitFunction("CloudBlockCode", c, "// CloudBlockCode"),
            i._emitFunction("CloudBlockCodeFBM" + this.octaves, d.replace(/fbm/gi, _).replace(/OCTAVES/gi, (this.octaves | 0).toString()), "// CloudBlockCode FBM");
            var b = i._getFreeVariableName("st")
              , k = ((o = this.seed.connectedPoint) === null || o === void 0 ? void 0 : o.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? "vec2" : "vec3";
            i.compilationString += k + " " + b + " = " + this.seed.associatedVariableName + `;\r
`,
            this.offsetX.isConnected && (i.compilationString += b + ".x += 0.1 * " + this.offsetX.associatedVariableName + `;\r
`),
            this.offsetY.isConnected && (i.compilationString += b + ".y += 0.1 * " + this.offsetY.associatedVariableName + `;\r
`),
            this.offsetZ.isConnected && k === "vec3" && (i.compilationString += b + ".z += 0.1 * " + this.offsetZ.associatedVariableName + `;\r
`);
            var j = "";
            return this.chaos.isConnected ? j = this.chaos.associatedVariableName : j = ((s = this.seed.connectedPoint) === null || s === void 0 ? void 0 : s.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? "vec2(0., 0.)" : "vec3(0., 0., 0.)",
            i.compilationString += this._declareOutput(this._outputs[0], i) + (" = " + _ + "(" + b + ", " + j + `);\r
`),
            this
        }
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var i = a.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".octaves = " + this.octaves + `;\r
`);
        return i
    }
    ,
    e.prototype.serialize = function() {
        var i = a.prototype.serialize.call(this);
        return i.octaves = this.octaves,
        i
    }
    ,
    e.prototype._deserialize = function(i, o, s) {
        a.prototype._deserialize.call(this, i, o, s),
        this.octaves = i.octaves
    }
    ,
    __decorate([editableInPropertyPage("Octaves", PropertyTypeForEdition.Int)], e.prototype, "octaves", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.CloudBlock", CloudBlock);
var VoronoiNoiseBlock = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i, NodeMaterialBlockTargets.Neutral) || this;
        return o.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector2),
        o.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerInput("density", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        o.registerOutput("cells", NodeMaterialBlockConnectionPointTypes.Float),
        o
    }
    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(i) {
        if (a.prototype._buildBlock.call(this, i),
        !!this.seed.isConnected) {
            var o = `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);
        }
        `;
            i._emitFunction("voronoiRandom", o, "// Voronoi random generator"),
            o = `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;
                    }
                }
            }
        }
        `,
            i._emitFunction("voronoi", o, "// Voronoi");
            var s = i._getFreeVariableName("tempOutput")
              , c = i._getFreeVariableName("tempCells");
            return i.compilationString += "float " + s + ` = 0.0;\r
`,
            i.compilationString += "float " + c + ` = 0.0;\r
`,
            i.compilationString += "voronoi(" + this.seed.associatedVariableName + ", " + this.offset.associatedVariableName + ", " + this.density.associatedVariableName + ", " + s + ", " + c + `);\r
`,
            this.output.hasEndpoints && (i.compilationString += this._declareOutput(this.output, i) + (" = " + s + `;\r
`)),
            this.cells.hasEndpoints && (i.compilationString += this._declareOutput(this.cells, i) + (" = " + c + `;\r
`)),
            this
        }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.VoronoiNoiseBlock", VoronoiNoiseBlock);
Node$2.AddNodeConstructor("Light_Type_2", function(a, e) {
    return function() {
        return new SpotLight(a,Vector3.Zero(),Vector3.Zero(),0,0,e)
    }
});
var SpotLight = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _) {
        var b = a.call(this, i, _) || this;
        return b._innerAngle = 0,
        b._projectionTextureMatrix = Matrix.Zero(),
        b._projectionTextureLightNear = 1e-6,
        b._projectionTextureLightFar = 1e3,
        b._projectionTextureUpDirection = Vector3.Up(),
        b._projectionTextureViewLightDirty = !0,
        b._projectionTextureProjectionLightDirty = !0,
        b._projectionTextureDirty = !0,
        b._projectionTextureViewTargetVector = Vector3.Zero(),
        b._projectionTextureViewLightMatrix = Matrix.Zero(),
        b._projectionTextureProjectionLightMatrix = Matrix.Zero(),
        b._projectionTextureScalingMatrix = Matrix.FromValues(.5, 0, 0, 0, 0, .5, 0, 0, 0, 0, .5, 0, .5, .5, .5, 1),
        b.position = o,
        b.direction = s,
        b.angle = c,
        b.exponent = d,
        b
    }
    return Object.defineProperty(e.prototype, "angle", {
        get: function() {
            return this._angle
        },
        set: function(i) {
            this._angle = i,
            this._cosHalfAngle = Math.cos(i * .5),
            this._projectionTextureProjectionLightDirty = !0,
            this.forceProjectionMatrixCompute(),
            this._computeAngleValues()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "innerAngle", {
        get: function() {
            return this._innerAngle
        },
        set: function(i) {
            this._innerAngle = i,
            this._computeAngleValues()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowAngleScale", {
        get: function() {
            return this._shadowAngleScale
        },
        set: function(i) {
            this._shadowAngleScale = i,
            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(i) {
            this._projectionTextureLightNear = i,
            this._projectionTextureProjectionLightDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "projectionTextureLightFar", {
        get: function() {
            return this._projectionTextureLightFar
        },
        set: function(i) {
            this._projectionTextureLightFar = i,
            this._projectionTextureProjectionLightDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "projectionTextureUpDirection", {
        get: function() {
            return this._projectionTextureUpDirection
        },
        set: function(i) {
            this._projectionTextureUpDirection = i,
            this._projectionTextureProjectionLightDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "projectionTexture", {
        get: function() {
            return this._projectionTexture
        },
        set: function(i) {
            var o = this;
            this._projectionTexture !== i && (this._projectionTexture = i,
            this._projectionTextureDirty = !0,
            this._projectionTexture && !this._projectionTexture.isReady() && (e._IsProceduralTexture(this._projectionTexture) ? this._projectionTexture.getEffect().executeWhenCompiled(function() {
                o._markMeshesAsLightDirty()
            }) : e._IsTexture(this._projectionTexture) && this._projectionTexture.onLoadObservable.addOnce(function() {
                o._markMeshesAsLightDirty()
            })))
        },
        enumerable: !1,
        configurable: !0
    }),
    e._IsProceduralTexture = function(i) {
        return i.onGeneratedObservable !== void 0
    }
    ,
    e._IsTexture = function(i) {
        return i.onLoadObservable !== void 0
    }
    ,
    Object.defineProperty(e.prototype, "projectionTextureProjectionLightMatrix", {
        get: function() {
            return this._projectionTextureProjectionLightMatrix
        },
        set: function(i) {
            this._projectionTextureProjectionLightMatrix = i,
            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(i) {
        a.prototype._setDirection.call(this, i),
        this._projectionTextureViewLightDirty = !0
    }
    ,
    e.prototype._setPosition = function(i) {
        a.prototype._setPosition.call(this, i),
        this._projectionTextureViewLightDirty = !0
    }
    ,
    e.prototype._setDefaultShadowProjectionMatrix = function(i, o, s) {
        var c = this.getScene().activeCamera;
        if (!!c) {
            this._shadowAngleScale = this._shadowAngleScale || 1;
            var d = this._shadowAngleScale * this._angle
              , _ = this.shadowMinZ !== void 0 ? this.shadowMinZ : c.minZ
              , b = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : c.maxZ
              , k = this.getScene().getEngine().useReverseDepthBuffer;
            Matrix.PerspectiveFovLHToRef(d, 1, k ? b : _, k ? _ : b, i, !0, this._scene.getEngine().isNDCHalfZRange, void 0, k)
        }
    }
    ,
    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 i = this.projectionTextureLightFar
          , o = this.projectionTextureLightNear
          , s = i / (i - o)
          , c = -s * o
          , d = 1 / Math.tan(this._angle / 2)
          , _ = 1;
        Matrix.FromValuesToRef(d / _, 0, 0, 0, 0, d, 0, 0, 0, 0, s, 1, 0, 0, c, 0, this._projectionTextureProjectionLightMatrix)
    }
    ,
    e.prototype._computeProjectionTextureMatrix = function() {
        if (this._projectionTextureDirty = !1,
        this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix),
        this._projectionTexture instanceof Texture) {
            var i = this._projectionTexture.uScale / 2
              , o = this._projectionTexture.vScale / 2;
            Matrix.FromValuesToRef(i, 0, 0, 0, 0, o, 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(i, o) {
        return this.projectionTexture && this.projectionTexture.isReady() && (this._projectionTextureViewLightDirty && this._computeProjectionTextureViewLightMatrix(),
        this._projectionTextureProjectionLightDirty && this._computeProjectionTextureProjectionLightMatrix(),
        this._projectionTextureDirty && this._computeProjectionTextureMatrix(),
        i.setMatrix("textureProjectionMatrix" + o, this._projectionTextureMatrix),
        i.setTexture("projectionLightSampler" + o, this.projectionTexture)),
        this
    }
    ,
    e.prototype.transferToEffect = function(i, o) {
        var s;
        return this.computeTransformedInformation() ? (this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, o),
        s = Vector3.Normalize(this.transformedDirection)) : (this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, o),
        s = Vector3.Normalize(this.direction)),
        this._uniformBuffer.updateFloat4("vLightDirection", s.x, s.y, s.z, this._cosHalfAngle, o),
        this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, o),
        this
    }
    ,
    e.prototype.transferToNodeMaterialEffect = function(i, o) {
        var s;
        return this.computeTransformedInformation() ? s = Vector3.Normalize(this.transformedDirection) : s = Vector3.Normalize(this.direction),
        this.getScene().useRightHandedSystem ? i.setFloat3(o, -s.x, -s.y, -s.z) : i.setFloat3(o, s.x, s.y, s.z),
        this
    }
    ,
    e.prototype.dispose = function() {
        a.prototype.dispose.call(this),
        this._projectionTexture && this._projectionTexture.dispose()
    }
    ,
    e.prototype.getDepthMinZ = function(i) {
        var o = this._scene.getEngine()
          , s = this.shadowMinZ !== void 0 ? this.shadowMinZ : i.minZ;
        return o.useReverseDepthBuffer && o.isNDCHalfZRange ? s : this._scene.getEngine().isNDCHalfZRange ? 0 : s
    }
    ,
    e.prototype.getDepthMaxZ = function(i) {
        var o = this._scene.getEngine()
          , s = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : i.maxZ;
        return o.useReverseDepthBuffer && o.isNDCHalfZRange ? 0 : s
    }
    ,
    e.prototype.prepareLightSpecificDefines = function(i, o) {
        i["SPOTLIGHT" + o] = !0,
        i["PROJECTEDLIGHTTEXTURE" + o] = !!(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$D = "glowMapGenerationPixelShader"
  , shader$D = `#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$D] = shader$D;
var name$C = "glowMapGenerationVertexShader"
  , shader$C = `
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$C] = shader$C;
var EffectLayer = function() {
    function a(e, i) {
        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 = i || EngineStore.LastCreatedScene,
        a._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(a.prototype, "camera", {
        get: function() {
            return this._effectLayerOptions.camera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "renderingGroupId", {
        get: function() {
            return this._effectLayerOptions.renderingGroupId
        },
        set: function(e) {
            this._effectLayerOptions.renderingGroupId = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setMaterialForRendering = function(e, i) {
        this._mainTexture.setMaterialForRendering(e, i)
    }
    ,
    a.prototype._numInternalDraws = function() {
        return 1
    }
    ,
    a.prototype._init = function(e) {
        this._effectLayerOptions = __assign({
            mainTextureRatio: .5,
            alphaBlendingMode: 2,
            camera: null,
            renderingGroupId: -1
        }, e),
        this._setMainTextureSize(),
        this._createMainTexture(),
        this._createTextureAndPostProcesses()
    }
    ,
    a.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)
    }
    ,
    a.prototype._generateVertexBuffer = function() {
        var e = [];
        e.push(1, 1),
        e.push(-1, 1),
        e.push(-1, -1),
        e.push(1, -1);
        var i = new VertexBuffer(this._engine,e,VertexBuffer.PositionKind,!1,!1,2);
        this._vertexBuffers[VertexBuffer.PositionKind] = i
    }
    ,
    a.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)
    }
    ,
    a.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(o, s, c, d) {
            e.onBeforeRenderMainTextureObservable.notifyObservers(e);
            var _, b = e._scene.getEngine();
            if (d.length) {
                for (b.setColorWrite(!1),
                _ = 0; _ < d.length; _++)
                    e._renderSubMesh(d.data[_]);
                b.setColorWrite(!0)
            }
            for (_ = 0; _ < o.length; _++)
                e._renderSubMesh(o.data[_]);
            for (_ = 0; _ < s.length; _++)
                e._renderSubMesh(s.data[_]);
            var k = b.getAlphaMode();
            for (_ = 0; _ < c.length; _++)
                e._renderSubMesh(c.data[_], !0);
            b.setAlphaMode(k)
        }
        ,
        this._mainTexture.onClearObservable.add(function(o) {
            o.clear(e.neutralColor, !0, !0, !0)
        }),
        this._scene.getBoundingBoxRenderer) {
            var i = this._scene.getBoundingBoxRenderer().enabled;
            this._mainTexture.onBeforeBindObservable.add(function() {
                e._scene.getBoundingBoxRenderer().enabled = !e.disableBoundingBoxesFromEffectLayer && i
            }),
            this._mainTexture.onAfterUnbindObservable.add(function() {
                e._scene.getBoundingBoxRenderer().enabled = i
            })
        }
    }
    ,
    a.prototype._addCustomEffectDefines = function(e) {}
    ,
    a.prototype._isReady = function(e, i, o) {
        var s, c = this._scene.getEngine(), d = e.getMesh(), _ = (s = d._internalAbstractMeshDataInfo._materialForRenderPass) === null || s === void 0 ? void 0 : s[c.currentRenderPassId];
        if (_)
            return _.isReadyForSubMesh(d, e, i);
        var b = e.getMaterial();
        if (!b)
            return !1;
        if (this._useMeshMaterial(e.getRenderingMesh()))
            return b.isReadyForSubMesh(e.getMesh(), e, i);
        var k = []
          , j = [VertexBuffer.PositionKind]
          , $ = !1
          , _e = !1;
        if (b) {
            var et = b.needAlphaTesting()
              , tt = b.getAlphaTestTexture()
              , rt = tt && tt.hasAlpha && (b.useAlphaFromDiffuseTexture || b._useAlphaFromAlbedoTexture);
            tt && (et || rt) && (k.push("#define DIFFUSE"),
            d.isVerticesDataPresent(VertexBuffer.UV2Kind) && tt.coordinatesIndex === 1 ? (k.push("#define DIFFUSEUV2"),
            _e = !0) : d.isVerticesDataPresent(VertexBuffer.UVKind) && (k.push("#define DIFFUSEUV1"),
            $ = !0),
            et && (k.push("#define ALPHATEST"),
            k.push("#define ALPHATESTVALUE 0.4")),
            tt.gammaSpace || k.push("#define DIFFUSE_ISLINEAR"));
            var it = b.opacityTexture;
            it && (k.push("#define OPACITY"),
            d.isVerticesDataPresent(VertexBuffer.UV2Kind) && it.coordinatesIndex === 1 ? (k.push("#define OPACITYUV2"),
            _e = !0) : d.isVerticesDataPresent(VertexBuffer.UVKind) && (k.push("#define OPACITYUV1"),
            $ = !0))
        }
        o && (k.push("#define EMISSIVE"),
        d.isVerticesDataPresent(VertexBuffer.UV2Kind) && o.coordinatesIndex === 1 ? (k.push("#define EMISSIVEUV2"),
        _e = !0) : d.isVerticesDataPresent(VertexBuffer.UVKind) && (k.push("#define EMISSIVEUV1"),
        $ = !0),
        o.gammaSpace || k.push("#define EMISSIVE_ISLINEAR")),
        d.isVerticesDataPresent(VertexBuffer.ColorKind) && d.hasVertexAlpha && (j.push(VertexBuffer.ColorKind),
        k.push("#define VERTEXALPHA")),
        $ && (j.push(VertexBuffer.UVKind),
        k.push("#define UV1")),
        _e && (j.push(VertexBuffer.UV2Kind),
        k.push("#define UV2"));
        var nt = new EffectFallbacks;
        if (d.useBones && d.computeBonesUsingShaders) {
            j.push(VertexBuffer.MatricesIndicesKind),
            j.push(VertexBuffer.MatricesWeightsKind),
            d.numBoneInfluencers > 4 && (j.push(VertexBuffer.MatricesIndicesExtraKind),
            j.push(VertexBuffer.MatricesWeightsExtraKind)),
            k.push("#define NUM_BONE_INFLUENCERS " + d.numBoneInfluencers);
            var ot = d.skeleton;
            ot && ot.isUsingTextureForMatrices ? k.push("#define BONETEXTURE") : k.push("#define BonesPerMesh " + (ot ? ot.bones.length + 1 : 0)),
            d.numBoneInfluencers > 0 && nt.addCPUSkinningFallback(0, d)
        } else
            k.push("#define NUM_BONE_INFLUENCERS 0");
        var at = d.morphTargetManager
          , st = 0;
        at && at.numInfluencers > 0 && (k.push("#define MORPHTARGETS"),
        st = at.numInfluencers,
        k.push("#define NUM_MORPH_INFLUENCERS " + st),
        at.isUsingTextureForTargets && k.push("#define MORPHTARGETS_TEXTURE"),
        MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(j, d, st)),
        i && (k.push("#define INSTANCES"),
        MaterialHelper.PushAttributesForInstances(j),
        e.getRenderingMesh().hasThinInstances && k.push("#define THIN_INSTANCES")),
        this._addCustomEffectDefines(k);
        var ut = e._getDrawWrapper(void 0, !0)
          , ct = ut.defines
          , lt = k.join(`
`);
        return ct !== lt && ut.setEffect(this._engine.createEffect("glowMapGeneration", j, ["world", "mBones", "viewProjection", "glowColor", "morphTargetInfluences", "boneTextureWidth", "diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity", "morphTargetTextureInfo", "morphTargetTextureIndices"], ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler", "morphTargets"], lt, nt, void 0, void 0, {
            maxSimultaneousMorphTargets: st
        }), lt),
        ut.effect.isReady()
    }
    ,
    a.prototype.render = function() {
        for (var e = 0; e < this._postProcesses.length; e++)
            if (!this._postProcesses[e].isReady())
                return;
        for (var i = this._scene.getEngine(), o = this._numInternalDraws(), s = !0, c = 0; c < o; ++c) {
            var d = this._mergeDrawWrapper[c];
            d || (d = this._mergeDrawWrapper[c] = new DrawWrapper(this._engine),
            d.setEffect(this._createMergeEffect())),
            s = s && d.effect.isReady()
        }
        if (!!s) {
            this.onBeforeComposeObservable.notifyObservers(this);
            for (var _ = i.getAlphaMode(), b = 0; b < o; ++b) {
                var d = this._mergeDrawWrapper[b];
                i.enableEffect(d),
                i.setState(!1),
                i.bindBuffers(this._vertexBuffers, this._indexBuffer, d.effect),
                i.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),
                this._internalRender(d.effect, b)
            }
            i.setAlphaMode(_),
            this.onAfterComposeObservable.notifyObservers(this);
            var k = this._mainTexture.getSize();
            this._setMainTextureSize(),
            (k.width !== this._mainTextureDesiredSize.width || k.height !== this._mainTextureDesiredSize.height) && this._mainTextureDesiredSize.width !== 0 && this._mainTextureDesiredSize.height !== 0 && (this.onSizeChangedObservable.notifyObservers(this),
            this._disposeTextureAndPostProcesses(),
            this._createMainTexture(),
            this._createTextureAndPostProcesses())
        }
    }
    ,
    a.prototype.hasMesh = function(e) {
        return this.renderingGroupId === -1 || e.renderingGroupId === this.renderingGroupId
    }
    ,
    a.prototype.shouldRender = function() {
        return this.isEnabled && this._shouldRender
    }
    ,
    a.prototype._shouldRenderMesh = function(e) {
        return !0
    }
    ,
    a.prototype._canRenderMesh = function(e, i) {
        return !i.needAlphaBlendingForMesh(e)
    }
    ,
    a.prototype._shouldRenderEmissiveTextureForMesh = function() {
        return !0
    }
    ,
    a.prototype._renderSubMesh = function(e, i) {
        var o, s;
        if (i === void 0 && (i = !1),
        !!this.shouldRender()) {
            var c = e.getMaterial()
              , d = e.getMesh()
              , _ = e.getReplacementMesh()
              , b = e.getRenderingMesh()
              , k = e.getEffectiveMesh()
              , j = this._scene
              , $ = j.getEngine();
            if (k._internalAbstractMeshDataInfo._isActiveIntermediate = !1,
            !!c && !!this._canRenderMesh(b, c)) {
                var _e = (o = b.overrideMaterialSideOrientation) !== null && o !== void 0 ? o : c.sideOrientation
                  , et = b._getWorldMatrixDeterminant();
                et < 0 && (_e = _e === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation);
                var tt = _e === Material.ClockWiseSideOrientation;
                $.setState(c.backFaceCulling, c.zOffset, void 0, tt, c.cullBackFaces, void 0, c.zOffsetUnits);
                var rt = b._getInstancesRenderList(e._id, !!_);
                if (!rt.mustReturn && !!this._shouldRenderMesh(b)) {
                    var it = rt.hardwareInstancedRendering[e._id] || b.hasThinInstances;
                    if (this._setEmissiveTextureAndColor(b, e, c),
                    this.onBeforeRenderMeshToEffect.notifyObservers(d),
                    this._useMeshMaterial(b))
                        b.render(e, it, _ || void 0);
                    else if (this._isReady(e, it, this._emissiveTextureAndColor.texture)) {
                        var nt = (s = k._internalAbstractMeshDataInfo._materialForRenderPass) === null || s === void 0 ? void 0 : s[$.currentRenderPassId]
                          , ot = e._getDrawWrapper();
                        if (!ot && nt && (ot = nt._getDrawWrapper()),
                        !ot)
                            return;
                        var at = ot.effect;
                        if ($.enableEffect(ot),
                        !it) {
                            var st = j.forcePointsCloud ? Material.PointFillMode : j.forceWireframe ? Material.WireFrameFillMode : c.fillMode;
                            b._bind(e, at, st)
                        }
                        if (nt ? nt.bindForSubMesh(k.getWorldMatrix(), k, e) : (at.setMatrix("viewProjection", j.getTransformMatrix()),
                        at.setMatrix("world", k.getWorldMatrix()),
                        at.setFloat4("glowColor", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a)),
                        !nt) {
                            var ut = c.needAlphaTesting()
                              , ct = c.getAlphaTestTexture()
                              , lt = ct && ct.hasAlpha && (c.useAlphaFromDiffuseTexture || c._useAlphaFromAlbedoTexture);
                            if (ct && (ut || lt)) {
                                at.setTexture("diffuseSampler", ct);
                                var ft = ct.getTextureMatrix();
                                ft && at.setMatrix("diffuseMatrix", ft)
                            }
                            var ht = c.opacityTexture;
                            if (ht) {
                                at.setTexture("opacitySampler", ht),
                                at.setFloat("opacityIntensity", ht.level);
                                var ft = ht.getTextureMatrix();
                                ft && at.setMatrix("opacityMatrix", ft)
                            }
                            if (this._emissiveTextureAndColor.texture && (at.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture),
                            at.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix())),
                            b.useBones && b.computeBonesUsingShaders && b.skeleton) {
                                var pt = b.skeleton;
                                if (pt.isUsingTextureForMatrices) {
                                    var dt = pt.getTransformMatrixTexture(b);
                                    if (!dt)
                                        return;
                                    at.setTexture("boneSampler", dt),
                                    at.setFloat("boneTextureWidth", 4 * (pt.bones.length + 1))
                                } else
                                    at.setMatrices("mBones", pt.getTransformMatrices(b))
                            }
                            MaterialHelper.BindMorphTargetParameters(b, at),
                            b.morphTargetManager && b.morphTargetManager.isUsingTextureForTargets && b.morphTargetManager._bind(at),
                            i && $.setAlphaMode(c.alphaMode)
                        }
                        b._processRendering(k, e, at, c.fillMode, rt, it, function(_t, mt) {
                            return at.setMatrix("world", mt)
                        })
                    } else
                        this._mainTexture.resetRefreshCounter();
                    this.onAfterRenderMeshToEffect.notifyObservers(d)
                }
            }
        }
    }
    ,
    a.prototype._useMeshMaterial = function(e) {
        return !1
    }
    ,
    a.prototype._rebuild = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && e._rebuild(),
        this._generateIndexBuffer()
    }
    ,
    a.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 = []
    }
    ,
    a.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 i = 0, o = this._mergeDrawWrapper; i < o.length; i++) {
            var s = o[i];
            s.dispose()
        }
        this._mergeDrawWrapper = [],
        this._disposeTextureAndPostProcesses();
        var c = this._scene.effectLayers.indexOf(this, 0);
        c > -1 && this._scene.effectLayers.splice(c, 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()
    }
    ,
    a.prototype.getClassName = function() {
        return "EffectLayer"
    }
    ,
    a.Parse = function(e, i, o) {
        var s = Tools.Instantiate(e.customType);
        return s.Parse(e, i, o)
    }
    ,
    a._SceneComponentInitialization = function(e) {
        throw _WarnImport("EffectLayerSceneComponent")
    }
    ,
    __decorate([serialize()], a.prototype, "name", void 0),
    __decorate([serializeAsColor4()], a.prototype, "neutralColor", void 0),
    __decorate([serialize()], a.prototype, "isEnabled", void 0),
    __decorate([serializeAsCameraReference()], a.prototype, "camera", null),
    __decorate([serialize()], a.prototype, "renderingGroupId", null),
    __decorate([serialize()], a.prototype, "disableBoundingBoxesFromEffectLayer", void 0),
    a
}()
  , name$B = "glowMapMergePixelShader"
  , shader$B = `
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$B] = shader$B;
var name$A = "glowMapMergeVertexShader"
  , shader$A = `
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$A] = shader$A;
AbstractScene.AddParser(SceneComponentConstants.NAME_EFFECTLAYER, function(a, e, i, o) {
    if (a.effectLayers) {
        i.effectLayers || (i.effectLayers = new Array);
        for (var s = 0; s < a.effectLayers.length; s++) {
            var c = EffectLayer.Parse(a.effectLayers[s], e, o);
            i.effectLayers.push(c)
        }
    }
});
AbstractScene.prototype.removeEffectLayer = function(a) {
    var e = this.effectLayers.indexOf(a);
    return e !== -1 && this.effectLayers.splice(e, 1),
    e
}
;
AbstractScene.prototype.addEffectLayer = function(a) {
    this.effectLayers.push(a)
}
;
var EffectLayerSceneComponent = function() {
    function a(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 a.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)
    }
    ,
    a.prototype.rebuild = function() {
        for (var e = this.scene.effectLayers, i = 0, o = e; i < o.length; i++) {
            var s = o[i];
            s._rebuild()
        }
    }
    ,
    a.prototype.serialize = function(e) {
        e.effectLayers = [];
        for (var i = this.scene.effectLayers, o = 0, s = i; o < s.length; o++) {
            var c = s[o];
            c.serialize && e.effectLayers.push(c.serialize())
        }
    }
    ,
    a.prototype.addFromContainer = function(e) {
        var i = this;
        !e.effectLayers || e.effectLayers.forEach(function(o) {
            i.scene.addEffectLayer(o)
        })
    }
    ,
    a.prototype.removeFromContainer = function(e, i) {
        var o = this;
        !e.effectLayers || e.effectLayers.forEach(function(s) {
            o.scene.removeEffectLayer(s),
            i && s.dispose()
        })
    }
    ,
    a.prototype.dispose = function() {
        for (var e = this.scene.effectLayers; e.length; )
            e[0].dispose()
    }
    ,
    a.prototype._isReadyForMesh = function(e, i) {
        for (var o = this._engine.currentRenderPassId, s = this.scene.effectLayers, c = 0, d = s; c < d.length; c++) {
            var _ = d[c];
            if (!!_.hasMesh(e)) {
                var b = _._mainTexture;
                this._engine.currentRenderPassId = b.renderPassId;
                for (var k = 0, j = e.subMeshes; k < j.length; k++) {
                    var $ = j[k];
                    if (!_.isReady($, i))
                        return this._engine.currentRenderPassId = o,
                        !1
                }
            }
        }
        return this._engine.currentRenderPassId = o,
        !0
    }
    ,
    a.prototype._renderMainTexture = function(e) {
        this._renderEffects = !1,
        this._needStencil = !1;
        var i = !1
          , o = this.scene.effectLayers;
        if (o && o.length > 0) {
            this._previousStencilState = this._engine.getStencilBuffer();
            for (var s = 0, c = o; s < c.length; s++) {
                var d = c[s];
                if (d.shouldRender() && (!d.camera || d.camera.cameraRigMode === Camera$1.RIG_MODE_NONE && e === d.camera || d.camera.cameraRigMode !== Camera$1.RIG_MODE_NONE && d.camera._rigCameras.indexOf(e) > -1)) {
                    this._renderEffects = !0,
                    this._needStencil = this._needStencil || d.needStencil();
                    var _ = d._mainTexture;
                    _._shouldRender() && (this.scene.incrementRenderId(),
                    _.render(!1, !1),
                    i = !0)
                }
            }
            this.scene.incrementRenderId()
        }
        return i
    }
    ,
    a.prototype._setStencil = function() {
        this._needStencil && this._engine.setStencilBuffer(!0)
    }
    ,
    a.prototype._setStencilBack = function() {
        this._needStencil && this._engine.setStencilBuffer(this._previousStencilState)
    }
    ,
    a.prototype._draw = function(e) {
        if (this._renderEffects) {
            this._engine.setDepthBuffer(!1);
            for (var i = this.scene.effectLayers, o = 0; o < i.length; o++) {
                var s = i[o];
                s.renderingGroupId === e && s.shouldRender() && s.render()
            }
            this._engine.setDepthBuffer(!0)
        }
    }
    ,
    a.prototype._drawCamera = function() {
        this._renderEffects && this._draw(-1)
    }
    ,
    a.prototype._drawRenderingGroup = function(e) {
        !this.scene._isInIntermediateRendering() && this._renderEffects && this._draw(e)
    }
    ,
    a
}();
EffectLayer._SceneComponentInitialization = function(a) {
    var e = a._getComponent(SceneComponentConstants.NAME_EFFECTLAYER);
    e || (e = new EffectLayerSceneComponent(a),
    a._addComponent(e))
}
;
AbstractScene.prototype.getGlowLayerByName = function(a) {
    for (var e = 0; e < this.effectLayers.length; e++)
        if (this.effectLayers[e].name === a && this.effectLayers[e].getEffectName() === GlowLayer.EffectName)
            return this.effectLayers[e];
    return null
}
;
var GlowLayer = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, o) || this;
        return c._intensity = 1,
        c._includedOnlyMeshes = [],
        c._excludedMeshes = [],
        c._meshesUsingTheirOwnMaterials = [],
        c.neutralColor = new Color4(0,0,0,1),
        c._options = __assign({
            mainTextureRatio: e.DefaultTextureRatio,
            blurKernelSize: 32,
            mainTextureFixedSize: void 0,
            camera: null,
            mainTextureSamples: 1,
            renderingGroupId: -1,
            ldrMerge: !1,
            alphaBlendingMode: 1
        }, s),
        c._init({
            alphaBlendingMode: c._options.alphaBlendingMode,
            camera: c._options.camera,
            mainTextureFixedSize: c._options.mainTextureFixedSize,
            mainTextureRatio: c._options.mainTextureRatio,
            renderingGroupId: c._options.renderingGroupId
        }),
        c
    }
    return Object.defineProperty(e.prototype, "blurKernelSize", {
        get: function() {
            return this._horizontalBlurPostprocess1.kernel
        },
        set: function(i) {
            this._horizontalBlurPostprocess1.kernel = i,
            this._verticalBlurPostprocess1.kernel = i,
            this._horizontalBlurPostprocess2.kernel = i,
            this._verticalBlurPostprocess2.kernel = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "intensity", {
        get: function() {
            return this._intensity
        },
        set: function(i) {
            this._intensity = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getEffectName = function() {
        return e.EffectName
    }
    ,
    e.prototype._createMergeEffect = function() {
        var i = `#define EMISSIVE 
`;
        return this._options.ldrMerge && (i += `#define LDR 
`),
        this._engine.createEffect("glowMapMerge", [VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], i)
    }
    ,
    e.prototype._createTextureAndPostProcesses = function() {
        var i = this
          , o = this._mainTextureDesiredSize.width
          , s = this._mainTextureDesiredSize.height;
        o = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(o, this._maxSize) : o,
        s = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(s, this._maxSize) : s;
        var c = 0;
        this._engine.getCaps().textureHalfFloatRender ? c = 2 : c = 0,
        this._blurTexture1 = new RenderTargetTexture("GlowLayerBlurRTT",{
            width: o,
            height: s
        },this._scene,!1,!0,c),
        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 d = Math.floor(o / 2)
          , _ = Math.floor(s / 2);
        this._blurTexture2 = new RenderTargetTexture("GlowLayerBlurRTT2",{
            width: d,
            height: _
        },this._scene,!1,!0,c),
        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: o,
            height: s
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),
        this._horizontalBlurPostprocess1.width = o,
        this._horizontalBlurPostprocess1.height = s,
        this._horizontalBlurPostprocess1.externalTextureSamplerBinding = !0,
        this._horizontalBlurPostprocess1.onApplyObservable.add(function(b) {
            b.setTexture("textureSampler", i._mainTexture)
        }),
        this._verticalBlurPostprocess1 = new BlurPostProcess("GlowLayerVBP1",new Vector2(0,1),this._options.blurKernelSize / 2,{
            width: o,
            height: s
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),
        this._horizontalBlurPostprocess2 = new BlurPostProcess("GlowLayerHBP2",new Vector2(1,0),this._options.blurKernelSize / 2,{
            width: d,
            height: _
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),
        this._horizontalBlurPostprocess2.width = d,
        this._horizontalBlurPostprocess2.height = _,
        this._horizontalBlurPostprocess2.externalTextureSamplerBinding = !0,
        this._horizontalBlurPostprocess2.onApplyObservable.add(function(b) {
            b.setTexture("textureSampler", i._blurTexture1)
        }),
        this._verticalBlurPostprocess2 = new BlurPostProcess("GlowLayerVBP2",new Vector2(0,1),this._options.blurKernelSize / 2,{
            width: d,
            height: _
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),
        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 b = i._blurTexture1.renderTarget;
            if (b) {
                i._scene.postProcessManager.directRender(i._postProcesses1, b, !0);
                var k = i._blurTexture2.renderTarget;
                k && i._scene.postProcessManager.directRender(i._postProcesses2, k, !0),
                i._engine.unBindFramebuffer(k != null ? k : b, !0)
            }
        }),
        this._postProcesses.map(function(b) {
            b.autoClear = !1
        })
    }
    ,
    e.prototype.isReady = function(i, o) {
        var s = i.getMaterial()
          , c = i.getRenderingMesh();
        if (!s || !c)
            return !1;
        var d = s.emissiveTexture;
        return a.prototype._isReady.call(this, i, o, d)
    }
    ,
    e.prototype.needStencil = function() {
        return !1
    }
    ,
    e.prototype._canRenderMesh = function(i, o) {
        return !0
    }
    ,
    e.prototype._internalRender = function(i) {
        i.setTexture("textureSampler", this._blurTexture1),
        i.setTexture("textureSampler2", this._blurTexture2),
        i.setFloat("offset", this._intensity);
        var o = this._engine
          , s = o.getStencilBuffer();
        o.setStencilBuffer(!1),
        o.drawElementsType(Material.TriangleFillMode, 0, 6),
        o.setStencilBuffer(s)
    }
    ,
    e.prototype._setEmissiveTextureAndColor = function(i, o, s) {
        var c, d = 1;
        if (this.customEmissiveTextureSelector ? this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(i, o, s) : s ? (this._emissiveTextureAndColor.texture = s.emissiveTexture,
        this._emissiveTextureAndColor.texture && (d = this._emissiveTextureAndColor.texture.level)) : this._emissiveTextureAndColor.texture = null,
        this.customEmissiveColorSelector)
            this.customEmissiveColorSelector(i, o, s, this._emissiveTextureAndColor.color);
        else if (s.emissiveColor) {
            var _ = (c = s.emissiveIntensity) !== null && c !== void 0 ? c : 1;
            d *= _,
            this._emissiveTextureAndColor.color.set(s.emissiveColor.r * d, s.emissiveColor.g * d, s.emissiveColor.b * d, s.alpha)
        } else
            this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a)
    }
    ,
    e.prototype._shouldRenderMesh = function(i) {
        return this.hasMesh(i)
    }
    ,
    e.prototype._addCustomEffectDefines = function(i) {
        i.push("#define GLOW")
    }
    ,
    e.prototype.addExcludedMesh = function(i) {
        this._excludedMeshes.indexOf(i.uniqueId) === -1 && this._excludedMeshes.push(i.uniqueId)
    }
    ,
    e.prototype.removeExcludedMesh = function(i) {
        var o = this._excludedMeshes.indexOf(i.uniqueId);
        o !== -1 && this._excludedMeshes.splice(o, 1)
    }
    ,
    e.prototype.addIncludedOnlyMesh = function(i) {
        this._includedOnlyMeshes.indexOf(i.uniqueId) === -1 && this._includedOnlyMeshes.push(i.uniqueId)
    }
    ,
    e.prototype.removeIncludedOnlyMesh = function(i) {
        var o = this._includedOnlyMeshes.indexOf(i.uniqueId);
        o !== -1 && this._includedOnlyMeshes.splice(o, 1)
    }
    ,
    e.prototype.hasMesh = function(i) {
        return a.prototype.hasMesh.call(this, i) ? this._includedOnlyMeshes.length ? this._includedOnlyMeshes.indexOf(i.uniqueId) !== -1 : this._excludedMeshes.length ? this._excludedMeshes.indexOf(i.uniqueId) === -1 : !0 : !1
    }
    ,
    e.prototype._useMeshMaterial = function(i) {
        return this._meshesUsingTheirOwnMaterials.length == 0 ? !1 : this._meshesUsingTheirOwnMaterials.indexOf(i.uniqueId) > -1
    }
    ,
    e.prototype.referenceMeshToUseItsOwnMaterial = function(i) {
        var o = this;
        this._meshesUsingTheirOwnMaterials.push(i.uniqueId),
        i.onDisposeObservable.add(function() {
            o._disposeMesh(i)
        })
    }
    ,
    e.prototype.unReferenceMeshFromUsingItsOwnMaterial = function(i) {
        for (var o = this._meshesUsingTheirOwnMaterials.indexOf(i.uniqueId); o >= 0; )
            this._meshesUsingTheirOwnMaterials.splice(o, 1),
            o = this._meshesUsingTheirOwnMaterials.indexOf(i.uniqueId)
    }
    ,
    e.prototype._disposeMesh = function(i) {
        this.removeIncludedOnlyMesh(i),
        this.removeExcludedMesh(i)
    }
    ,
    e.prototype.getClassName = function() {
        return "GlowLayer"
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        i.customType = "BABYLON.GlowLayer";
        var o;
        if (i.includedMeshes = [],
        this._includedOnlyMeshes.length)
            for (o = 0; o < this._includedOnlyMeshes.length; o++) {
                var s = this._scene.getMeshByUniqueId(this._includedOnlyMeshes[o]);
                s && i.includedMeshes.push(s.id)
            }
        if (i.excludedMeshes = [],
        this._excludedMeshes.length)
            for (o = 0; o < this._excludedMeshes.length; o++) {
                var s = this._scene.getMeshByUniqueId(this._excludedMeshes[o]);
                s && i.excludedMeshes.push(s.id)
            }
        return i
    }
    ,
    e.Parse = function(i, o, s) {
        var c = SerializationHelper.Parse(function() {
            return new e(i.name,o,i.options)
        }, i, o, s), d;
        for (d = 0; d < i.excludedMeshes.length; d++) {
            var _ = o.getMeshById(i.excludedMeshes[d]);
            _ && c.addExcludedMesh(_)
        }
        for (d = 0; d < i.includedMeshes.length; d++) {
            var _ = o.getMeshById(i.includedMeshes[d]);
            _ && c.addIncludedOnlyMesh(_)
        }
        return c
    }
    ,
    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$z = "glowBlurPostProcessPixelShader"
  , shader$z = `
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$z] = shader$z;
AbstractScene.prototype.getHighlightLayerByName = function(a) {
    for (var e = 0; e < this.effectLayers.length; e++)
        if (this.effectLayers[e].name === a && this.effectLayers[e].getEffectName() === HighlightLayer.EffectName)
            return this.effectLayers[e];
    return null
}
;
var GlowBlurPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        _ === void 0 && (_ = Texture.BILINEAR_SAMPLINGMODE);
        var j = a.call(this, i, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, c, d, _, b, k) || this;
        return j.direction = o,
        j.kernel = s,
        j.onApplyObservable.add(function($) {
            $.setFloat2("screenSize", j.width, j.height),
            $.setVector2("direction", j.direction),
            $.setFloat("blurWidth", j.kernel)
        }),
        j
    }
    return e
}(PostProcess)
  , HighlightLayer = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, o) || this;
        return c.name = i,
        c.innerGlow = !0,
        c.outerGlow = !0,
        c.onBeforeBlurObservable = new Observable,
        c.onAfterBlurObservable = new Observable,
        c._instanceGlowingMeshStencilReference = e.GlowingMeshStencilReference++,
        c._meshes = {},
        c._excludedMeshes = {},
        c.neutralColor = e.NeutralColor,
        c._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 }"),
        c._options = __assign({
            mainTextureRatio: .5,
            blurTextureSizeRatio: .5,
            blurHorizontalSize: 1,
            blurVerticalSize: 1,
            alphaBlendingMode: 2,
            camera: null,
            renderingGroupId: -1
        }, s),
        c._init({
            alphaBlendingMode: c._options.alphaBlendingMode,
            camera: c._options.camera,
            mainTextureFixedSize: c._options.mainTextureFixedSize,
            mainTextureRatio: c._options.mainTextureRatio,
            renderingGroupId: c._options.renderingGroupId
        }),
        c._shouldRender = !1,
        c
    }
    return Object.defineProperty(e.prototype, "blurHorizontalSize", {
        get: function() {
            return this._horizontalBlurPostprocess.kernel
        },
        set: function(i) {
            this._horizontalBlurPostprocess.kernel = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blurVerticalSize", {
        get: function() {
            return this._verticalBlurPostprocess.kernel
        },
        set: function(i) {
            this._verticalBlurPostprocess.kernel = i
        },
        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 i = this
          , o = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio
          , s = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
        o = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(o, this._maxSize) : o,
        s = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(s, this._maxSize) : s;
        var c = 0;
        this._engine.getCaps().textureHalfFloatRender ? c = 2 : c = 0,
        this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT",{
            width: o,
            height: s
        },this._scene,!1,!0,c),
        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(d) {
            d.setTexture("textureSampler", i._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(d) {
            d.setFloat2("screenSize", o, s)
        }),
        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(d) {
            d.setFloat2("screenSize", o, s)
        }),
        this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess]) : (this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP",new Vector2(1,0),this._options.blurHorizontalSize / 2,{
            width: o,
            height: s
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),
        this._horizontalBlurPostprocess.width = o,
        this._horizontalBlurPostprocess.height = s,
        this._horizontalBlurPostprocess.externalTextureSamplerBinding = !0,
        this._horizontalBlurPostprocess.onApplyObservable.add(function(d) {
            d.setTexture("textureSampler", i._mainTexture)
        }),
        this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP",new Vector2(0,1),this._options.blurVerticalSize / 2,{
            width: o,
            height: s
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,c),
        this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess]),
        this._mainTexture.onAfterUnbindObservable.add(function() {
            i.onBeforeBlurObservable.notifyObservers(i);
            var d = i._blurTexture.renderTarget;
            d && (i._scene.postProcessManager.directRender(i._postProcesses, d, !0),
            i._engine.unBindFramebuffer(d, !0)),
            i.onAfterBlurObservable.notifyObservers(i)
        }),
        this._postProcesses.map(function(d) {
            d.autoClear = !1
        })
    }
    ,
    e.prototype.needStencil = function() {
        return !0
    }
    ,
    e.prototype.isReady = function(i, o) {
        var s = i.getMaterial()
          , c = i.getRenderingMesh();
        if (!s || !c || !this._meshes)
            return !1;
        var d = null
          , _ = this._meshes[c.uniqueId];
        return _ && _.glowEmissiveOnly && s && (d = s.emissiveTexture),
        a.prototype._isReady.call(this, i, o, d)
    }
    ,
    e.prototype._internalRender = function(i, o) {
        i.setTexture("textureSampler", this._blurTexture);
        var s = this._engine;
        s.cacheStencilState(),
        s.setStencilOperationPass(7681),
        s.setStencilOperationFail(7680),
        s.setStencilOperationDepthFail(7680),
        s.setStencilMask(0),
        s.setStencilBuffer(!0),
        s.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),
        this.outerGlow && o === 0 && (i.setFloat("offset", 0),
        s.setStencilFunction(517),
        s.drawElementsType(Material.TriangleFillMode, 0, 6)),
        this.innerGlow && o === 1 && (i.setFloat("offset", 1),
        s.setStencilFunction(514),
        s.drawElementsType(Material.TriangleFillMode, 0, 6)),
        s.restoreStencilState()
    }
    ,
    e.prototype.shouldRender = function() {
        return a.prototype.shouldRender.call(this) ? !!this._meshes : !1
    }
    ,
    e.prototype._shouldRenderMesh = function(i) {
        return !(this._excludedMeshes && this._excludedMeshes[i.uniqueId] || !a.prototype.hasMesh.call(this, i))
    }
    ,
    e.prototype._canRenderMesh = function(i, o) {
        return !0
    }
    ,
    e.prototype._addCustomEffectDefines = function(i) {
        i.push("#define HIGHLIGHT")
    }
    ,
    e.prototype._setEmissiveTextureAndColor = function(i, o, s) {
        var c = this._meshes[i.uniqueId];
        c ? this._emissiveTextureAndColor.color.set(c.color.r, c.color.g, c.color.b, 1) : this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a),
        c && c.glowEmissiveOnly && s ? (this._emissiveTextureAndColor.texture = s.emissiveTexture,
        this._emissiveTextureAndColor.color.set(1, 1, 1, 1)) : this._emissiveTextureAndColor.texture = null
    }
    ,
    e.prototype.addExcludedMesh = function(i) {
        if (!!this._excludedMeshes) {
            var o = this._excludedMeshes[i.uniqueId];
            o || (this._excludedMeshes[i.uniqueId] = {
                mesh: i,
                beforeBind: i.onBeforeBindObservable.add(function(s) {
                    s.getEngine().setStencilBuffer(!1)
                }),
                afterRender: i.onAfterRenderObservable.add(function(s) {
                    s.getEngine().setStencilBuffer(!0)
                })
            })
        }
    }
    ,
    e.prototype.removeExcludedMesh = function(i) {
        if (!!this._excludedMeshes) {
            var o = this._excludedMeshes[i.uniqueId];
            o && (o.beforeBind && i.onBeforeBindObservable.remove(o.beforeBind),
            o.afterRender && i.onAfterRenderObservable.remove(o.afterRender)),
            this._excludedMeshes[i.uniqueId] = null
        }
    }
    ,
    e.prototype.hasMesh = function(i) {
        return !this._meshes || !a.prototype.hasMesh.call(this, i) ? !1 : this._meshes[i.uniqueId] !== void 0 && this._meshes[i.uniqueId] !== null
    }
    ,
    e.prototype.addMesh = function(i, o, s) {
        var c = this;
        if (s === void 0 && (s = !1),
        !!this._meshes) {
            var d = this._meshes[i.uniqueId];
            d ? d.color = o : (this._meshes[i.uniqueId] = {
                mesh: i,
                color: o,
                observerHighlight: i.onBeforeBindObservable.add(function(_) {
                    c.isEnabled && (c._excludedMeshes && c._excludedMeshes[_.uniqueId] ? c._defaultStencilReference(_) : _.getScene().getEngine().setStencilFunctionReference(c._instanceGlowingMeshStencilReference))
                }),
                observerDefault: i.onAfterRenderObservable.add(function(_) {
                    c.isEnabled && c._defaultStencilReference(_)
                }),
                glowEmissiveOnly: s
            },
            i.onDisposeObservable.add(function() {
                c._disposeMesh(i)
            })),
            this._shouldRender = !0
        }
    }
    ,
    e.prototype.removeMesh = function(i) {
        if (!!this._meshes) {
            var o = this._meshes[i.uniqueId];
            o && (o.observerHighlight && i.onBeforeBindObservable.remove(o.observerHighlight),
            o.observerDefault && i.onAfterRenderObservable.remove(o.observerDefault),
            delete this._meshes[i.uniqueId]),
            this._shouldRender = !1;
            for (var s in this._meshes)
                if (this._meshes[s]) {
                    this._shouldRender = !0;
                    break
                }
        }
    }
    ,
    e.prototype.removeAllMeshes = function() {
        if (!!this._meshes) {
            for (var i in this._meshes)
                if (this._meshes.hasOwnProperty(i)) {
                    var o = this._meshes[i];
                    o && this.removeMesh(o.mesh)
                }
        }
    }
    ,
    e.prototype._defaultStencilReference = function(i) {
        i.getScene().getEngine().setStencilFunctionReference(e.NormalMeshStencilReference)
    }
    ,
    e.prototype._disposeMesh = function(i) {
        this.removeMesh(i),
        this.removeExcludedMesh(i)
    }
    ,
    e.prototype.dispose = function() {
        if (this._meshes) {
            for (var i in this._meshes) {
                var o = this._meshes[i];
                o && o.mesh && (o.observerHighlight && o.mesh.onBeforeBindObservable.remove(o.observerHighlight),
                o.observerDefault && o.mesh.onAfterRenderObservable.remove(o.observerDefault))
            }
            this._meshes = null
        }
        if (this._excludedMeshes) {
            for (var i in this._excludedMeshes) {
                var o = this._excludedMeshes[i];
                o && (o.beforeBind && o.mesh.onBeforeBindObservable.remove(o.beforeBind),
                o.afterRender && o.mesh.onAfterRenderObservable.remove(o.afterRender))
            }
            this._excludedMeshes = null
        }
        a.prototype.dispose.call(this)
    }
    ,
    e.prototype.getClassName = function() {
        return "HighlightLayer"
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        if (i.customType = "BABYLON.HighlightLayer",
        i.meshes = [],
        this._meshes)
            for (var o in this._meshes) {
                var s = this._meshes[o];
                s && i.meshes.push({
                    glowEmissiveOnly: s.glowEmissiveOnly,
                    color: s.color.asArray(),
                    meshId: s.mesh.id
                })
            }
        if (i.excludedMeshes = [],
        this._excludedMeshes)
            for (var c in this._excludedMeshes) {
                var d = this._excludedMeshes[c];
                d && i.excludedMeshes.push(d.mesh.id)
            }
        return i
    }
    ,
    e.Parse = function(i, o, s) {
        var c = SerializationHelper.Parse(function() {
            return new e(i.name,o,i.options)
        }, i, o, s), d;
        for (d = 0; d < i.excludedMeshes.length; d++) {
            var _ = o.getMeshById(i.excludedMeshes[d]);
            _ && c.addExcludedMesh(_)
        }
        for (d = 0; d < i.meshes.length; d++) {
            var b = i.meshes[d]
              , _ = o.getMeshById(b.meshId);
            _ && c.addMesh(_, Color3.FromArray(b.color), b.glowEmissiveOnly)
        }
        return c
    }
    ,
    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$y = "sharpenPixelShader"
  , shader$y = `
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$y] = shader$y;
var SharpenPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        b === void 0 && (b = 0),
        k === void 0 && (k = !1);
        var j = a.call(this, i, "sharpen", ["sharpnessAmounts", "screenSize"], null, o, s, c, d, _, null, b, void 0, null, k) || this;
        return j.colorAmount = 1,
        j.edgeAmount = .3,
        j.onApply = function($) {
            $.setFloat2("screenSize", j.width, j.height),
            $.setFloat2("sharpnessAmounts", j.edgeAmount, j.colorAmount)
        }
        ,
        j
    }
    return e.prototype.getClassName = function() {
        return "SharpenPostProcess"
    }
    ,
    e._Parse = function(i, o, s, c) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,i.options,o,i.renderTargetSamplingMode,s.getEngine(),i.textureType,i.reusable)
        }, i, s, c)
    }
    ,
    __decorate([serialize()], e.prototype, "colorAmount", void 0),
    __decorate([serialize()], e.prototype, "edgeAmount", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.SharpenPostProcess", SharpenPostProcess);
var name$x = "imageProcessingPixelShader"
  , shader$x = `
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$x] = shader$x;
var ImageProcessingPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        s === void 0 && (s = null),
        b === void 0 && (b = 0);
        var j = a.call(this, i, "imageProcessing", [], [], o, s, c, d, _, null, b, "postprocess", null, !0) || this;
        return j._fromLinearSpace = !0,
        j._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
        },
        k ? (k.applyByPostProcess = !0,
        j._attachImageProcessingConfiguration(k, !0),
        j.fromLinearSpace = !1) : (j._attachImageProcessingConfiguration(null, !0),
        j.imageProcessingConfiguration.applyByPostProcess = !0),
        j.onApply = function($) {
            j.imageProcessingConfiguration.bind($, j.aspectRatio)
        }
        ,
        j
    }
    return Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(i) {
            i.applyByPostProcess = !0,
            this._attachImageProcessingConfiguration(i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachImageProcessingConfiguration = function(i, o) {
        var s = this;
        if (o === void 0 && (o = !1),
        i !== this._imageProcessingConfiguration) {
            if (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
            i)
                this._imageProcessingConfiguration = i;
            else {
                var c = null
                  , d = this.getEngine()
                  , _ = this.getCamera();
                if (_)
                    c = _.getScene();
                else if (d && d.scenes) {
                    var b = d.scenes;
                    c = b[b.length - 1]
                } else
                    c = EngineStore.LastCreatedScene;
                c ? this._imageProcessingConfiguration = c.imageProcessingConfiguration : this._imageProcessingConfiguration = new ImageProcessingConfiguration
            }
            this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
                s._updateParameters()
            })),
            o || this._updateParameters()
        }
    }
    ,
    Object.defineProperty(e.prototype, "isSupported", {
        get: function() {
            var i = this.getEffect();
            return !i || i.isSupported
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "colorCurves", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurves
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorCurves = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "colorCurvesEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurvesEnabled
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorCurvesEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "colorGradingTexture", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingTexture
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorGradingTexture = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "colorGradingEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingEnabled
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorGradingEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "exposure", {
        get: function() {
            return this.imageProcessingConfiguration.exposure
        },
        set: function(i) {
            this.imageProcessingConfiguration.exposure = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "toneMappingEnabled", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingEnabled
        },
        set: function(i) {
            this._imageProcessingConfiguration.toneMappingEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "toneMappingType", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingType
        },
        set: function(i) {
            this._imageProcessingConfiguration.toneMappingType = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "contrast", {
        get: function() {
            return this.imageProcessingConfiguration.contrast
        },
        set: function(i) {
            this.imageProcessingConfiguration.contrast = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteStretch", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteStretch
        },
        set: function(i) {
            this.imageProcessingConfiguration.vignetteStretch = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteCentreX", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteCentreX
        },
        set: function(i) {
            this.imageProcessingConfiguration.vignetteCentreX = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteCentreY", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteCentreY
        },
        set: function(i) {
            this.imageProcessingConfiguration.vignetteCentreY = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteWeight", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteWeight
        },
        set: function(i) {
            this.imageProcessingConfiguration.vignetteWeight = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteColor", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteColor
        },
        set: function(i) {
            this.imageProcessingConfiguration.vignetteColor = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteCameraFov", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteCameraFov
        },
        set: function(i) {
            this.imageProcessingConfiguration.vignetteCameraFov = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteBlendMode", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteBlendMode
        },
        set: function(i) {
            this.imageProcessingConfiguration.vignetteBlendMode = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteEnabled
        },
        set: function(i) {
            this.imageProcessingConfiguration.vignetteEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fromLinearSpace", {
        get: function() {
            return this._fromLinearSpace
        },
        set: function(i) {
            this._fromLinearSpace !== i && (this._fromLinearSpace = i,
            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 i = "";
        for (var o in this._defines)
            this._defines[o] && (i += "#define " + o + `;\r
`);
        var s = ["textureSampler"]
          , c = ["scale"];
        ImageProcessingConfiguration && (ImageProcessingConfiguration.PrepareSamplers(s, this._defines),
        ImageProcessingConfiguration.PrepareUniforms(c, this._defines)),
        this.updateEffect(i, c, s)
    }
    ,
    e.prototype.dispose = function(i) {
        a.prototype.dispose.call(this, i),
        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$w = "chromaticAberrationPixelShader"
  , shader$w = `
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$w] = shader$w;
var ChromaticAberrationPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $) {
        j === void 0 && (j = 0),
        $ === void 0 && ($ = !1);
        var _e = a.call(this, i, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], c, d, _, b, k, null, j, void 0, null, $) || this;
        return _e.aberrationAmount = 30,
        _e.radialIntensity = 0,
        _e.direction = new Vector2(.707,.707),
        _e.centerPosition = new Vector2(.5,.5),
        _e.screenWidth = o,
        _e.screenHeight = s,
        _e.onApplyObservable.add(function(et) {
            et.setFloat("chromatic_aberration", _e.aberrationAmount),
            et.setFloat("screen_width", o),
            et.setFloat("screen_height", s),
            et.setFloat("radialIntensity", _e.radialIntensity),
            et.setFloat2("direction", _e.direction.x, _e.direction.y),
            et.setFloat2("centerPosition", _e.centerPosition.x, _e.centerPosition.y)
        }),
        _e
    }
    return e.prototype.getClassName = function() {
        return "ChromaticAberrationPostProcess"
    }
    ,
    e._Parse = function(i, o, s, c) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,i.screenWidth,i.screenHeight,i.options,o,i.renderTargetSamplingMode,s.getEngine(),i.reusable,i.textureType,!1)
        }, i, s, c)
    }
    ,
    __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$v = "grainPixelShader"
  , shader$v = `#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$v] = shader$v;
var GrainPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        b === void 0 && (b = 0),
        k === void 0 && (k = !1);
        var j = a.call(this, i, "grain", ["intensity", "animatedSeed"], [], o, s, c, d, _, null, b, void 0, null, k) || this;
        return j.intensity = 30,
        j.animated = !1,
        j.onApplyObservable.add(function($) {
            $.setFloat("intensity", j.intensity),
            $.setFloat("animatedSeed", j.animated ? Math.random() + 1 : 1)
        }),
        j
    }
    return e.prototype.getClassName = function() {
        return "GrainPostProcess"
    }
    ,
    e._Parse = function(i, o, s, c) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,i.options,o,i.renderTargetSamplingMode,s.getEngine(),i.reusable)
        }, i, s, c)
    }
    ,
    __decorate([serialize()], e.prototype, "intensity", void 0),
    __decorate([serialize()], e.prototype, "animated", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.GrainPostProcess", GrainPostProcess);
var name$u = "fxaaPixelShader"
  , shader$u = `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$u] = shader$u;
var name$t = "fxaaVertexShader"
  , shader$t = `
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$t] = shader$t;
var FxaaPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b) {
        s === void 0 && (s = null),
        b === void 0 && (b = 0);
        var k = a.call(this, i, "fxaa", ["texelSize"], null, o, s, c || Texture.BILINEAR_SAMPLINGMODE, d, _, null, b, "fxaa", void 0, !0) || this
          , j = k._getDefines();
        return k.updateEffect(j),
        k.onApplyObservable.add(function($) {
            var _e = k.texelSize;
            $.setFloat2("texelSize", _e.x, _e.y)
        }),
        k
    }
    return e.prototype.getClassName = function() {
        return "FxaaPostProcess"
    }
    ,
    e.prototype._getDefines = function() {
        var i = this.getEngine();
        if (!i)
            return null;
        var o = i.getGlInfo();
        return o && o.renderer && o.renderer.toLowerCase().indexOf("mali") > -1 ? `#define MALI 1
` : null
    }
    ,
    e._Parse = function(i, o, s, c) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,i.options,o,i.renderTargetSamplingMode,s.getEngine(),i.reusable)
        }, i, s, c)
    }
    ,
    e
}(PostProcess);
RegisterClass("BABYLON.FxaaPostProcess", FxaaPostProcess);
var PostProcessRenderPipeline = function() {
    function a(e, i) {
        this.engine = e,
        this._name = i,
        this._renderEffects = {},
        this._renderEffectsForIsolatedPass = new Array,
        this._cameras = []
    }
    return Object.defineProperty(a.prototype, "name", {
        get: function() {
            return this._name
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "cameras", {
        get: function() {
            return this._cameras
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getClassName = function() {
        return "PostProcessRenderPipeline"
    }
    ,
    Object.defineProperty(a.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
    }),
    a.prototype.addEffect = function(e) {
        this._renderEffects[e._name] = e
    }
    ,
    a.prototype._rebuild = function() {}
    ,
    a.prototype._enableEffect = function(e, i) {
        var o = this._renderEffects[e];
        !o || o._enable(Tools.MakeArray(i || this._cameras))
    }
    ,
    a.prototype._disableEffect = function(e, i) {
        var o = this._renderEffects[e];
        !o || o._disable(Tools.MakeArray(i || this._cameras))
    }
    ,
    a.prototype._attachCameras = function(e, i) {
        var o = Tools.MakeArray(e || this._cameras);
        if (!!o) {
            var s = [], c;
            for (c = 0; c < o.length; c++) {
                var d = o[c];
                if (!!d) {
                    var _ = d.name;
                    this._cameras.indexOf(d) === -1 ? this._cameras[_] = d : i && s.push(c)
                }
            }
            for (c = 0; c < s.length; c++)
                o.splice(s[c], 1);
            for (var b in this._renderEffects)
                this._renderEffects.hasOwnProperty(b) && this._renderEffects[b]._attachCameras(o)
        }
    }
    ,
    a.prototype._detachCameras = function(e) {
        var i = Tools.MakeArray(e || this._cameras);
        if (!!i) {
            for (var o in this._renderEffects)
                this._renderEffects.hasOwnProperty(o) && this._renderEffects[o]._detachCameras(i);
            for (var s = 0; s < i.length; s++)
                this._cameras.splice(this._cameras.indexOf(i[s]), 1)
        }
    }
    ,
    a.prototype._update = function() {
        for (var e in this._renderEffects)
            this._renderEffects.hasOwnProperty(e) && this._renderEffects[e]._update();
        for (var i = 0; i < this._cameras.length; i++)
            if (!!this._cameras[i]) {
                var o = this._cameras[i].name;
                this._renderEffectsForIsolatedPass[o] && this._renderEffectsForIsolatedPass[o]._update()
            }
    }
    ,
    a.prototype._reset = function() {
        this._renderEffects = {},
        this._renderEffectsForIsolatedPass = new Array
    }
    ,
    a.prototype._enableMSAAOnFirstPostProcess = function(e) {
        if (!this.engine._features.supportMSAA)
            return !1;
        var i = Object.keys(this._renderEffects);
        if (i.length > 0) {
            var o = this._renderEffects[i[0]].getPostProcesses();
            o && (o[0].samples = e)
        }
        return !0
    }
    ,
    a.prototype.setPrePassRenderer = function(e) {
        return !1
    }
    ,
    a.prototype.dispose = function() {}
    ,
    __decorate([serialize()], a.prototype, "_name", void 0),
    a
}()
  , PostProcessRenderEffect = function() {
    function a(e, i, o, s) {
        this._name = i,
        this._singleInstance = s || !0,
        this._getPostProcesses = o,
        this._cameras = {},
        this._indicesForCamera = {},
        this._postProcesses = {}
    }
    return Object.defineProperty(a.prototype, "isSupported", {
        get: function() {
            for (var e in this._postProcesses)
                if (this._postProcesses.hasOwnProperty(e)) {
                    for (var i = this._postProcesses[e], o = 0; o < i.length; o++)
                        if (!i[o].isSupported)
                            return !1
                }
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._update = function() {}
    ,
    a.prototype._attachCameras = function(e) {
        var i = this, o, s = Tools.MakeArray(e || this._cameras);
        if (!!s)
            for (var c = 0; c < s.length; c++) {
                var d = s[c];
                if (!!d) {
                    var _ = d.name;
                    if (this._singleInstance ? o = 0 : o = _,
                    !this._postProcesses[o]) {
                        var b = this._getPostProcesses();
                        b && (this._postProcesses[o] = Array.isArray(b) ? b : [b])
                    }
                    this._indicesForCamera[_] || (this._indicesForCamera[_] = []),
                    this._postProcesses[o].forEach(function(k) {
                        var j = d.attachPostProcess(k);
                        i._indicesForCamera[_].push(j)
                    }),
                    this._cameras[_] || (this._cameras[_] = d)
                }
            }
    }
    ,
    a.prototype._detachCameras = function(e) {
        var i = Tools.MakeArray(e || this._cameras);
        if (!!i)
            for (var o = 0; o < i.length; o++) {
                var s = i[o]
                  , c = s.name
                  , d = this._postProcesses[this._singleInstance ? 0 : c];
                d && d.forEach(function(_) {
                    s.detachPostProcess(_)
                }),
                this._cameras[c] && (this._cameras[c] = null)
            }
    }
    ,
    a.prototype._enable = function(e) {
        var i = this
          , o = Tools.MakeArray(e || this._cameras);
        if (!!o)
            for (var s = 0; s < o.length; s++)
                for (var c = o[s], d = c.name, _ = 0; _ < this._indicesForCamera[d].length; _++)
                    (c._postProcesses[this._indicesForCamera[d][_]] === void 0 || c._postProcesses[this._indicesForCamera[d][_]] === null) && this._postProcesses[this._singleInstance ? 0 : d].forEach(function(b) {
                        o[s].attachPostProcess(b, i._indicesForCamera[d][_])
                    })
    }
    ,
    a.prototype._disable = function(e) {
        var i = Tools.MakeArray(e || this._cameras);
        if (!!i)
            for (var o = 0; o < i.length; o++) {
                var s = i[o]
                  , c = s.name;
                this._postProcesses[this._singleInstance ? 0 : c].forEach(function(d) {
                    s.detachPostProcess(d)
                })
            }
    }
    ,
    a.prototype.getPostProcesses = function(e) {
        return this._singleInstance ? this._postProcesses[0] : e ? this._postProcesses[e.name] : null
    }
    ,
    a
}()
  , name$s = "circleOfConfusionPixelShader"
  , shader$s = `
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$s] = shader$s;
var CircleOfConfusionPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j) {
        k === void 0 && (k = 0),
        j === void 0 && (j = !1);
        var $ = a.call(this, i, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], s, c, d, _, b, null, k, void 0, null, j) || this;
        return $.lensSize = 50,
        $.fStop = 1.4,
        $.focusDistance = 2e3,
        $.focalLength = 50,
        $._depthTexture = null,
        $._depthTexture = o,
        $.onApplyObservable.add(function(_e) {
            if (!$._depthTexture) {
                Logger$2.Warn("No depth texture set on CircleOfConfusionPostProcess");
                return
            }
            _e.setTexture("depthSampler", $._depthTexture);
            var et = $.lensSize / $.fStop
              , tt = et * $.focalLength / ($.focusDistance - $.focalLength);
            _e.setFloat("focusDistance", $.focusDistance),
            _e.setFloat("cocPrecalculation", tt),
            _e.setFloat2("cameraMinMaxZ", $._depthTexture.activeCamera.minZ, $._depthTexture.activeCamera.maxZ)
        }),
        $
    }
    return e.prototype.getClassName = function() {
        return "CircleOfConfusionPostProcess"
    }
    ,
    Object.defineProperty(e.prototype, "depthTexture", {
        set: function(i) {
            this._depthTexture = i
        },
        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(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $, _e, et, tt) {
        k === void 0 && (k = null),
        tt === void 0 && (tt = !1);
        var rt = a.call(this, i, s, c, d, _, 2, $, _e, 0, `#define DOF 1\r
`, tt) || this;
        return rt.direction = s,
        rt.externalTextureSamplerBinding = !!k,
        rt.onApplyObservable.add(function(it) {
            k != null && it.setTextureFromPostProcess("textureSampler", k),
            it.setTextureFromPostProcessOutput("circleOfConfusionSampler", b),
            o.activeCamera && it.setFloat2("cameraMinMaxZ", o.activeCamera.minZ, o.activeCamera.maxZ)
        }),
        rt
    }
    return e.prototype.getClassName = function() {
        return "DepthOfFieldBlurPostProcess"
    }
    ,
    __decorate([serialize()], e.prototype, "direction", void 0),
    e
}(BlurPostProcess);
RegisterClass("BABYLON.DepthOfFieldBlurPostProcess", DepthOfFieldBlurPostProcess);
var name$r = "depthOfFieldMergePixelShader"
  , shader$r = `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$r] = shader$r;
var DepthOfFieldMergePostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $, _e) {
        $ === void 0 && ($ = 0),
        _e === void 0 && (_e = !1);
        var et = a.call(this, i, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], d, _, b, k, j, null, $, void 0, null, !0) || this;
        return et.blurSteps = c,
        et.externalTextureSamplerBinding = !0,
        et.onApplyObservable.add(function(tt) {
            tt.setTextureFromPostProcess("textureSampler", o),
            tt.setTextureFromPostProcessOutput("circleOfConfusionSampler", s),
            c.forEach(function(rt, it) {
                tt.setTextureFromPostProcessOutput("blurStep" + (c.length - it - 1), rt)
            })
        }),
        _e || et.updateEffect(),
        et
    }
    return e.prototype.getClassName = function() {
        return "DepthOfFieldMergePostProcess"
    }
    ,
    e.prototype.updateEffect = function(i, o, s, c, d, _) {
        i === void 0 && (i = null),
        o === void 0 && (o = null),
        s === void 0 && (s = null),
        i || (i = "",
        i += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + `
`),
        a.prototype.updateEffect.call(this, i, o, s, c, d, _)
    }
    ,
    e
}(PostProcess), DepthOfFieldEffectBlurLevel;
(function(a) {
    a[a.Low = 0] = "Low",
    a[a.Medium = 1] = "Medium",
    a[a.High = 2] = "High"
}
)(DepthOfFieldEffectBlurLevel || (DepthOfFieldEffectBlurLevel = {}));
var DepthOfFieldEffect = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        s === void 0 && (s = DepthOfFieldEffectBlurLevel.Low),
        c === void 0 && (c = 0),
        d === void 0 && (d = !1);
        var _ = a.call(this, i.getEngine(), "depth of field", function() {
            return _._effects
        }, !0) || this;
        _._effects = [],
        _._circleOfConfusion = new CircleOfConfusionPostProcess("circleOfConfusion",o,1,null,Texture.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,c,d),
        _._depthOfFieldBlurY = [],
        _._depthOfFieldBlurX = [];
        var b = 1
          , k = 15;
        switch (s) {
        case DepthOfFieldEffectBlurLevel.High:
            {
                b = 3,
                k = 51;
                break
            }
        case DepthOfFieldEffectBlurLevel.Medium:
            {
                b = 2,
                k = 31;
                break
            }
        default:
            {
                k = 15,
                b = 1;
                break
            }
        }
        for (var j = k / Math.pow(2, b - 1), $ = 1, _e = 0; _e < b; _e++) {
            var et = new DepthOfFieldBlurPostProcess("vertical blur",i,new Vector2(0,1),j,$,null,_._circleOfConfusion,_e == 0 ? _._circleOfConfusion : null,Texture.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,c,d);
            et.autoClear = !1,
            $ = .75 / Math.pow(2, _e);
            var tt = new DepthOfFieldBlurPostProcess("horizontal blur",i,new Vector2(1,0),j,$,null,_._circleOfConfusion,null,Texture.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,c,d);
            tt.autoClear = !1,
            _._depthOfFieldBlurY.push(et),
            _._depthOfFieldBlurX.push(tt)
        }
        _._effects = [_._circleOfConfusion];
        for (var _e = 0; _e < _._depthOfFieldBlurX.length; _e++)
            _._effects.push(_._depthOfFieldBlurY[_e]),
            _._effects.push(_._depthOfFieldBlurX[_e]);
        return _._dofMerge = new DepthOfFieldMergePostProcess("dofMerge",_._circleOfConfusion,_._circleOfConfusion,_._depthOfFieldBlurX,$,null,Texture.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,c,d),
        _._dofMerge.autoClear = !1,
        _._effects.push(_._dofMerge),
        _
    }
    return Object.defineProperty(e.prototype, "focalLength", {
        get: function() {
            return this._circleOfConfusion.focalLength
        },
        set: function(i) {
            this._circleOfConfusion.focalLength = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fStop", {
        get: function() {
            return this._circleOfConfusion.fStop
        },
        set: function(i) {
            this._circleOfConfusion.fStop = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "focusDistance", {
        get: function() {
            return this._circleOfConfusion.focusDistance
        },
        set: function(i) {
            this._circleOfConfusion.focusDistance = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lensSize", {
        get: function() {
            return this._circleOfConfusion.lensSize
        },
        set: function(i) {
            this._circleOfConfusion.lensSize = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "DepthOfFieldEffect"
    }
    ,
    Object.defineProperty(e.prototype, "depthTexture", {
        set: function(i) {
            this._circleOfConfusion.depthTexture = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.disposeEffects = function(i) {
        for (var o = 0; o < this._effects.length; o++)
            this._effects[o].dispose(i)
    }
    ,
    e.prototype._updateEffects = function() {
        for (var i = 0; i < this._effects.length; i++)
            this._effects[i].updateEffect()
    }
    ,
    e.prototype._isReady = function() {
        for (var i = 0; i < this._effects.length; i++)
            if (!this._effects[i].isReady())
                return !1;
        return !0
    }
    ,
    e
}(PostProcessRenderEffect)
  , name$q = "extractHighlightsPixelShader"
  , shader$q = `#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$q] = shader$q;
var ExtractHighlightsPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k) {
        b === void 0 && (b = 0),
        k === void 0 && (k = !1);
        var j = a.call(this, i, "extractHighlights", ["threshold", "exposure"], null, o, s, c, d, _, null, b, void 0, null, k) || this;
        return j.threshold = .9,
        j._exposure = 1,
        j._inputPostProcess = null,
        j.onApplyObservable.add(function($) {
            j.externalTextureSamplerBinding = !!j._inputPostProcess,
            j._inputPostProcess && $.setTextureFromPostProcess("textureSampler", j._inputPostProcess),
            $.setFloat("threshold", Math.pow(j.threshold, ToGammaSpace)),
            $.setFloat("exposure", j._exposure)
        }),
        j
    }
    return e.prototype.getClassName = function() {
        return "ExtractHighlightsPostProcess"
    }
    ,
    __decorate([serialize()], e.prototype, "threshold", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.ExtractHighlightsPostProcess", ExtractHighlightsPostProcess);
var name$p = "bloomMergePixelShader"
  , shader$p = `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$p] = shader$p;
var BloomMergePostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $, _e) {
        $ === void 0 && ($ = 0),
        _e === void 0 && (_e = !1);
        var et = a.call(this, i, "bloomMerge", ["bloomWeight"], ["bloomBlur"], d, _, b, k, j, null, $, void 0, null, !0) || this;
        return et.weight = 1,
        et.weight = c,
        et.externalTextureSamplerBinding = !0,
        et.onApplyObservable.add(function(tt) {
            tt.setTextureFromPostProcess("textureSampler", o),
            tt.setTextureFromPostProcessOutput("bloomBlur", s),
            tt.setFloat("bloomWeight", et.weight)
        }),
        _e || et.updateEffect(),
        et
    }
    return e.prototype.getClassName = function() {
        return "BloomMergePostProcess"
    }
    ,
    __decorate([serialize()], e.prototype, "weight", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.BloomMergePostProcess", BloomMergePostProcess);
var BloomEffect = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _) {
        d === void 0 && (d = 0),
        _ === void 0 && (_ = !1);
        var b = a.call(this, i.getEngine(), "bloom", function() {
            return b._effects
        }, !0) || this;
        return b.bloomScale = o,
        b._effects = [],
        b._downscale = new ExtractHighlightsPostProcess("highlights",1,null,Texture.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,d,_),
        b._blurX = new BlurPostProcess("horizontal blur",new Vector2(1,0),10,o,null,Texture.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,d,void 0,_),
        b._blurX.alwaysForcePOT = !0,
        b._blurX.autoClear = !1,
        b._blurY = new BlurPostProcess("vertical blur",new Vector2(0,1),10,o,null,Texture.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,d,void 0,_),
        b._blurY.alwaysForcePOT = !0,
        b._blurY.autoClear = !1,
        b.kernel = c,
        b._effects = [b._downscale, b._blurX, b._blurY],
        b._merge = new BloomMergePostProcess("bloomMerge",b._downscale,b._blurY,s,o,null,Texture.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,d,_),
        b._merge.autoClear = !1,
        b._effects.push(b._merge),
        b
    }
    return Object.defineProperty(e.prototype, "threshold", {
        get: function() {
            return this._downscale.threshold
        },
        set: function(i) {
            this._downscale.threshold = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "weight", {
        get: function() {
            return this._merge.weight
        },
        set: function(i) {
            this._merge.weight = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "kernel", {
        get: function() {
            return this._blurX.kernel / this.bloomScale
        },
        set: function(i) {
            this._blurX.kernel = i * this.bloomScale,
            this._blurY.kernel = i * this.bloomScale
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.disposeEffects = function(i) {
        for (var o = 0; o < this._effects.length; o++)
            this._effects[o].dispose(i)
    }
    ,
    e.prototype._updateEffects = function() {
        for (var i = 0; i < this._effects.length; i++)
            this._effects[i].updateEffect()
    }
    ,
    e.prototype._isReady = function() {
        for (var i = 0; i < this._effects.length; i++)
            if (!this._effects[i].isReady())
                return !1;
        return !0
    }
    ,
    e
}(PostProcessRenderEffect)
  , PostProcessRenderPipelineManager = function() {
    function a() {
        this._renderPipelines = {}
    }
    return Object.defineProperty(a.prototype, "supportedPipelines", {
        get: function() {
            var e = [];
            for (var i in this._renderPipelines)
                if (this._renderPipelines.hasOwnProperty(i)) {
                    var o = this._renderPipelines[i];
                    o.isSupported && e.push(o)
                }
            return e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.addPipeline = function(e) {
        this._renderPipelines[e._name] = e
    }
    ,
    a.prototype.attachCamerasToRenderPipeline = function(e, i, o) {
        o === void 0 && (o = !1);
        var s = this._renderPipelines[e];
        !s || s._attachCameras(i, o)
    }
    ,
    a.prototype.detachCamerasFromRenderPipeline = function(e, i) {
        var o = this._renderPipelines[e];
        !o || o._detachCameras(i)
    }
    ,
    a.prototype.enableEffectInPipeline = function(e, i, o) {
        var s = this._renderPipelines[e];
        !s || s._enableEffect(i, o)
    }
    ,
    a.prototype.disableEffectInPipeline = function(e, i, o) {
        var s = this._renderPipelines[e];
        !s || s._disableEffect(i, o)
    }
    ,
    a.prototype.update = function() {
        for (var e in this._renderPipelines)
            if (this._renderPipelines.hasOwnProperty(e)) {
                var i = this._renderPipelines[e];
                i.isSupported ? i._update() : (i.dispose(),
                delete this._renderPipelines[e])
            }
    }
    ,
    a.prototype._rebuild = function() {
        for (var e in this._renderPipelines)
            if (this._renderPipelines.hasOwnProperty(e)) {
                var i = this._renderPipelines[e];
                i._rebuild()
            }
    }
    ,
    a.prototype.dispose = function() {
        for (var e in this._renderPipelines)
            if (this._renderPipelines.hasOwnProperty(e)) {
                var i = this._renderPipelines[e];
                i.dispose()
            }
    }
    ,
    a
}();
Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
    get: function() {
        if (!this._postProcessRenderPipelineManager) {
            var a = this._getComponent(SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
            a || (a = new PostProcessRenderPipelineManagerSceneComponent(this),
            this._addComponent(a)),
            this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager
        }
        return this._postProcessRenderPipelineManager
    },
    enumerable: !0,
    configurable: !0
});
var PostProcessRenderPipelineManagerSceneComponent = function() {
    function a(e) {
        this.name = SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER,
        this.scene = e
    }
    return a.prototype.register = function() {
        this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets)
    }
    ,
    a.prototype.rebuild = function() {
        this.scene._postProcessRenderPipelineManager && this.scene._postProcessRenderPipelineManager._rebuild()
    }
    ,
    a.prototype.dispose = function() {
        this.scene._postProcessRenderPipelineManager && this.scene._postProcessRenderPipelineManager.dispose()
    }
    ,
    a.prototype._gatherRenderTargets = function() {
        this.scene._postProcessRenderPipelineManager && this.scene._postProcessRenderPipelineManager.update()
    }
    ,
    a
}()
  , DefaultRenderingPipeline = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        i === void 0 && (i = ""),
        o === void 0 && (o = !0),
        s === void 0 && (s = EngineStore.LastCreatedScene),
        d === void 0 && (d = !0);
        var _ = a.call(this, s.getEngine(), i) || this;
        _._camerasToBeAttached = [],
        _.SharpenPostProcessId = "SharpenPostProcessEffect",
        _.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect",
        _.FxaaPostProcessId = "FxaaPostProcessEffect",
        _.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect",
        _.GrainPostProcessId = "GrainPostProcessEffect",
        _._glowLayer = null,
        _.animations = [],
        _._imageProcessingConfigurationObserver = null,
        _._sharpenEnabled = !1,
        _._bloomEnabled = !1,
        _._depthOfFieldEnabled = !1,
        _._depthOfFieldBlurLevel = DepthOfFieldEffectBlurLevel.Low,
        _._fxaaEnabled = !1,
        _._imageProcessingEnabled = !0,
        _._bloomScale = .5,
        _._chromaticAberrationEnabled = !1,
        _._grainEnabled = !1,
        _._buildAllowed = !0,
        _.onBuildObservable = new Observable,
        _._resizeObserver = null,
        _._hardwareScaleLevel = 1,
        _._bloomKernel = 64,
        _._bloomWeight = .15,
        _._bloomThreshold = .9,
        _._samples = 1,
        _._hasCleared = !1,
        _._prevPostProcess = null,
        _._prevPrevPostProcess = null,
        _._depthOfFieldSceneObserver = null,
        _._cameras = c || s.cameras,
        _._cameras = _._cameras.slice(),
        _._camerasToBeAttached = _._cameras.slice(),
        _._buildAllowed = d,
        _._scene = s;
        var b = _._scene.getEngine().getCaps();
        _._hdr = o && (b.textureHalfFloatRender || b.textureFloatRender),
        _._hdr ? b.textureHalfFloatRender ? _._defaultPipelineTextureType = 2 : b.textureFloatRender && (_._defaultPipelineTextureType = 1) : _._defaultPipelineTextureType = 0,
        s.postProcessRenderPipelineManager.addPipeline(_);
        var k = _._scene.getEngine();
        return _.sharpen = new SharpenPostProcess("sharpen",1,null,Texture.BILINEAR_SAMPLINGMODE,k,!1,_._defaultPipelineTextureType,!0),
        _._sharpenEffect = new PostProcessRenderEffect(k,_.SharpenPostProcessId,function() {
            return _.sharpen
        }
        ,!0),
        _.depthOfField = new DepthOfFieldEffect(_._scene,null,_._depthOfFieldBlurLevel,_._defaultPipelineTextureType,!0),
        _.bloom = new BloomEffect(_._scene,_._bloomScale,_._bloomWeight,_.bloomKernel,_._defaultPipelineTextureType,!0),
        _.chromaticAberration = new ChromaticAberrationPostProcess("ChromaticAberration",k.getRenderWidth(),k.getRenderHeight(),1,null,Texture.BILINEAR_SAMPLINGMODE,k,!1,_._defaultPipelineTextureType,!0),
        _._chromaticAberrationEffect = new PostProcessRenderEffect(k,_.ChromaticAberrationPostProcessId,function() {
            return _.chromaticAberration
        }
        ,!0),
        _.grain = new GrainPostProcess("Grain",1,null,Texture.BILINEAR_SAMPLINGMODE,k,!1,_._defaultPipelineTextureType,!0),
        _._grainEffect = new PostProcessRenderEffect(k,_.GrainPostProcessId,function() {
            return _.grain
        }
        ,!0),
        _._resizeObserver = k.onResizeObservable.add(function() {
            _._hardwareScaleLevel = k.getHardwareScalingLevel(),
            _.bloomKernel = _.bloomKernel
        }),
        _._imageProcessingConfigurationObserver = _._scene.imageProcessingConfiguration.onUpdateParameters.add(function() {
            _.bloom._downscale._exposure = _._scene.imageProcessingConfiguration.exposure,
            _.imageProcessingEnabled !== _._scene.imageProcessingConfiguration.isEnabled && (_._imageProcessingEnabled = _._scene.imageProcessingConfiguration.isEnabled,
            _._buildPipeline())
        }),
        _._buildPipeline(),
        _
    }
    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(i) {
            this._sharpenEnabled !== i && (this._sharpenEnabled = i,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomKernel", {
        get: function() {
            return this._bloomKernel
        },
        set: function(i) {
            this._bloomKernel = i,
            this.bloom.kernel = i / this._hardwareScaleLevel
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomWeight", {
        get: function() {
            return this._bloomWeight
        },
        set: function(i) {
            this._bloomWeight !== i && (this.bloom.weight = i,
            this._bloomWeight = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomThreshold", {
        get: function() {
            return this._bloomThreshold
        },
        set: function(i) {
            this._bloomThreshold !== i && (this.bloom.threshold = i,
            this._bloomThreshold = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomScale", {
        get: function() {
            return this._bloomScale
        },
        set: function(i) {
            this._bloomScale !== i && (this._bloomScale = i,
            this._rebuildBloom(),
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomEnabled", {
        get: function() {
            return this._bloomEnabled
        },
        set: function(i) {
            this._bloomEnabled !== i && (this._bloomEnabled = i,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._rebuildBloom = function() {
        var i = this.bloom;
        this.bloom = new BloomEffect(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel,this._defaultPipelineTextureType,!1),
        this.bloom.threshold = i.threshold;
        for (var o = 0; o < this._cameras.length; o++)
            i.disposeEffects(this._cameras[o])
    }
    ,
    Object.defineProperty(e.prototype, "depthOfFieldEnabled", {
        get: function() {
            return this._depthOfFieldEnabled
        },
        set: function(i) {
            this._depthOfFieldEnabled !== i && (this._depthOfFieldEnabled = i,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthOfFieldBlurLevel", {
        get: function() {
            return this._depthOfFieldBlurLevel
        },
        set: function(i) {
            if (this._depthOfFieldBlurLevel !== i) {
                this._depthOfFieldBlurLevel = i;
                var o = this.depthOfField;
                this.depthOfField = new DepthOfFieldEffect(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),
                this.depthOfField.focalLength = o.focalLength,
                this.depthOfField.focusDistance = o.focusDistance,
                this.depthOfField.fStop = o.fStop,
                this.depthOfField.lensSize = o.lensSize;
                for (var s = 0; s < this._cameras.length; s++)
                    o.disposeEffects(this._cameras[s]);
                this._buildPipeline()
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fxaaEnabled", {
        get: function() {
            return this._fxaaEnabled
        },
        set: function(i) {
            this._fxaaEnabled !== i && (this._fxaaEnabled = i,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "samples", {
        get: function() {
            return this._samples
        },
        set: function(i) {
            this._samples !== i && (this._samples = i,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "imageProcessingEnabled", {
        get: function() {
            return this._imageProcessingEnabled
        },
        set: function(i) {
            this._imageProcessingEnabled !== i && (this._scene.imageProcessingConfiguration.isEnabled = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "glowLayerEnabled", {
        get: function() {
            return this._glowLayer != null
        },
        set: function(i) {
            i && !this._glowLayer ? this._glowLayer = new GlowLayer("",this._scene) : !i && 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(i) {
            this._chromaticAberrationEnabled !== i && (this._chromaticAberrationEnabled = i,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "grainEnabled", {
        get: function() {
            return this._grainEnabled
        },
        set: function(i) {
            this._grainEnabled !== i && (this._grainEnabled = i,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "DefaultRenderingPipeline"
    }
    ,
    e.prototype.prepare = function() {
        var i = this._buildAllowed;
        this._buildAllowed = !0,
        this._buildPipeline(),
        this._buildAllowed = i
    }
    ,
    e.prototype._setAutoClearAndTextureSharing = function(i, o) {
        o === void 0 && (o = !1),
        this._hasCleared ? i.autoClear = !1 : (i.autoClear = !0,
        this._scene.autoClear = !1,
        this._hasCleared = !0),
        o || (this._prevPrevPostProcess ? i.shareOutputWith(this._prevPrevPostProcess) : i.useOwnOutput(),
        this._prevPostProcess && (this._prevPrevPostProcess = this._prevPostProcess),
        this._prevPostProcess = i)
    }
    ,
    e.prototype._buildPipeline = function() {
        var i = this;
        if (!!this._buildAllowed) {
            this._scene.autoClear = !0;
            var o = 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 s = 0, c = this._cameras; s < c.length; s++) {
                        var d = c[s]
                          , _ = this._scene.enableDepthRenderer(d);
                        _.useOnlyInActiveCamera = !0
                    }
                    this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function(b) {
                        i._cameras.indexOf(b.activeCamera) > -1 && (i.depthOfField.depthTexture = b.enableDepthRenderer(b.activeCamera).getDepthMap())
                    })
                } else {
                    this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
                    var _ = this._scene.enableDepthRenderer(this._cameras[0]);
                    this.depthOfField.depthTexture = _.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,o,!1,this._defaultPipelineTextureType),
            this._hdr ? (this.addEffect(new PostProcessRenderEffect(o,this.ImageProcessingPostProcessId,function() {
                return i.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,o,!1,this._defaultPipelineTextureType),
            this.addEffect(new PostProcessRenderEffect(o,this.FxaaPostProcessId,function() {
                return i.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(i) {
        i === void 0 && (i = !1);
        for (var o = 0; o < this._cameras.length; o++) {
            var s = this._cameras[o];
            this.imageProcessing && this.imageProcessing.dispose(s),
            this.fxaa && this.fxaa.dispose(s),
            i && (this.sharpen && this.sharpen.dispose(s),
            this.depthOfField && (this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),
            this.depthOfField.disposeEffects(s)),
            this.bloom && this.bloom.disposeEffects(s),
            this.chromaticAberration && this.chromaticAberration.dispose(s),
            this.grain && this.grain.dispose(s),
            this._glowLayer && this._glowLayer.dispose())
        }
        this.imageProcessing = null,
        this.fxaa = null,
        i && (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(i) {
        this._camerasToBeAttached.push(i),
        this._buildPipeline()
    }
    ,
    e.prototype.removeCamera = function(i) {
        var o = this._camerasToBeAttached.indexOf(i);
        this._camerasToBeAttached.splice(o, 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),
        a.prototype.dispose.call(this)
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        return i.customType = "DefaultRenderingPipeline",
        i
    }
    ,
    e.Parse = function(i, o, s) {
        return SerializationHelper.Parse(function() {
            return new e(i._name,i._name._hdr,o)
        }, i, o, s)
    }
    ,
    __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 name$o = "imageProcessingCompatibility"
  , shader$o = `#ifdef IMAGEPROCESSINGPOSTPROCESS
gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));
#endif`;
ShaderStore.IncludesShadersStore[name$o] = shader$o;
var name$n = "gridPixelShader"
  , shader$n = `#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$n] = shader$n;
var name$m = "gridVertexShader"
  , shader$m = `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$m] = shader$m;
var GridMaterialDefines = function(a) {
    __extends(e, a);
    function e() {
        var i = a.call(this) || this;
        return i.OPACITY = !1,
        i.TRANSPARENT = !1,
        i.FOG = !1,
        i.PREMULTIPLYALPHA = !1,
        i.MAX_LINE = !1,
        i.UV1 = !1,
        i.UV2 = !1,
        i.INSTANCES = !1,
        i.THIN_INSTANCES = !1,
        i.IMAGEPROCESSINGPOSTPROCESS = !1,
        i.SKIPFINALCOLORCLAMP = !1,
        i.rebuild(),
        i
    }
    return e
}(MaterialDefines)
  , GridMaterial = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o) || this;
        return s.mainColor = Color3.Black(),
        s.lineColor = Color3.Teal(),
        s.gridRatio = 1,
        s.gridOffset = Vector3.Zero(),
        s.majorUnitFrequency = 10,
        s.minorUnitVisibility = .33,
        s.opacity = 1,
        s.preMultiplyAlpha = !1,
        s.useMaxLine = !1,
        s._gridControl = new Vector4(s.gridRatio,s.majorUnitFrequency,s.minorUnitVisibility,s.opacity),
        s
    }
    return e.prototype.needAlphaBlending = function() {
        return this.opacity < 1 || this._opacityTexture && this._opacityTexture.isReady()
    }
    ,
    e.prototype.needAlphaBlendingForMesh = function(i) {
        return i.visibility < 1 || this.needAlphaBlending()
    }
    ,
    e.prototype.isReadyForSubMesh = function(i, o, s) {
        if (this.isFrozen && o.effect && o.effect._wasPreviouslyReady)
            return !0;
        o.materialDefines || (o.materialDefines = new GridMaterialDefines);
        var c = o.materialDefines
          , d = this.getScene();
        if (this._isReadyForSubMesh(o))
            return !0;
        if (c.TRANSPARENT !== this.opacity < 1 && (c.TRANSPARENT = !c.TRANSPARENT,
        c.markAsUnprocessed()),
        c.PREMULTIPLYALPHA != this.preMultiplyAlpha && (c.PREMULTIPLYALPHA = !c.PREMULTIPLYALPHA,
        c.markAsUnprocessed()),
        c.MAX_LINE !== this.useMaxLine && (c.MAX_LINE = !c.MAX_LINE,
        c.markAsUnprocessed()),
        c._areTexturesDirty && (c._needUVs = !1,
        d.texturesEnabled && this._opacityTexture && MaterialFlags.OpacityTextureEnabled))
            if (this._opacityTexture.isReady())
                c._needUVs = !0,
                c.OPACITY = !0;
            else
                return !1;
        if (MaterialHelper.PrepareDefinesForMisc(i, d, !1, !1, this.fogEnabled, !1, c),
        MaterialHelper.PrepareDefinesForFrameBoundValues(d, d.getEngine(), c, !!s),
        c.isDirty) {
            c.markAsProcessed(),
            d.resetCachedMaterial(),
            MaterialHelper.PrepareDefinesForAttributes(i, c, !1, !1);
            var _ = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];
            c.UV1 && _.push(VertexBuffer.UVKind),
            c.UV2 && _.push(VertexBuffer.UV2Kind),
            c.IMAGEPROCESSINGPOSTPROCESS = d.imageProcessingConfiguration.applyByPostProcess,
            MaterialHelper.PrepareAttributesForInstances(_, c);
            var b = c.toString();
            o.setEffect(d.getEngine().createEffect("grid", _, ["projection", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view", "opacityMatrix", "vOpacityInfos", "visibility"], ["opacitySampler"], b, void 0, this.onCompiled, this.onError), c, this._materialContext)
        }
        return !o.effect || !o.effect.isReady() ? !1 : (c._renderId = d.getRenderId(),
        o.effect._wasPreviouslyReady = !0,
        !0)
    }
    ,
    e.prototype.bindForSubMesh = function(i, o, s) {
        var c = this.getScene()
          , d = s.materialDefines;
        if (!!d) {
            var _ = s.effect;
            !_ || (this._activeEffect = _,
            this._activeEffect.setFloat("visibility", o.visibility),
            (!d.INSTANCES || d.THIN_INSTANCE) && this.bindOnlyWorldMatrix(i),
            this._activeEffect.setMatrix("view", c.getViewMatrix()),
            this._activeEffect.setMatrix("projection", c.getProjectionMatrix()),
            this._mustRebind(c, _) && (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(c, o, this._activeEffect),
            this._afterBind(o, this._activeEffect))
        }
    }
    ,
    e.prototype.dispose = function(i) {
        a.prototype.dispose.call(this, i)
    }
    ,
    e.prototype.clone = function(i) {
        var o = this;
        return SerializationHelper.Clone(function() {
            return new e(i,o.getScene())
        }, this)
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        return i.customType = "BABYLON.GridMaterial",
        i
    }
    ,
    e.prototype.getClassName = function() {
        return "GridMaterial"
    }
    ,
    e.Parse = function(i, o, s) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,o)
        }, i, o, s)
    }
    ,
    __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 a(e) {
        var i = 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() {
            i._captureActiveMeshesEvaluationTime && i._activeMeshesEvaluationTime.fetchNewFrame(),
            i._captureRenderTargetsRenderTime && i._renderTargetsRenderTime.fetchNewFrame(),
            i._captureFrameTime && (Tools.StartPerformanceCounter("Scene rendering"),
            i._frameTime.beginMonitoring()),
            i._captureInterFrameTime && i._interFrameTime.endMonitoring(),
            i._captureParticlesRenderTime && i._particlesRenderTime.fetchNewFrame(),
            i._captureSpritesRenderTime && i._spritesRenderTime.fetchNewFrame(),
            i._captureAnimationsTime && i._animationsTime.beginMonitoring(),
            i.scene.getEngine()._drawCalls.fetchNewFrame()
        }),
        this._onAfterRenderObserver = e.onAfterRenderObservable.add(function() {
            i._captureFrameTime && (Tools.EndPerformanceCounter("Scene rendering"),
            i._frameTime.endMonitoring()),
            i._captureRenderTime && i._renderTime.endMonitoring(!1),
            i._captureInterFrameTime && i._interFrameTime.beginMonitoring()
        }),
        this._onBeforeRegisterBeforeRenderObserver = e.onBeforeRunRegisterBeforeRenderObservable.add(function() {
            i._registerBeforeRenderTime.beginMonitoring()
        }),
        this._onAfterRegisterBeforeRenderObserver = e.onAfterRunRegisterBeforeRenderObservable.add(function() {
            i._registerBeforeRenderTime.endMonitoring()
        }),
        this._onBeforeRegisterAfterRenderObserver = e.onBeforeRunRegisterAfterRenderObservable.add(function() {
            i._registerAfterRenderTime.beginMonitoring()
        }),
        this._onAfterRegisterAfterRenderObserver = e.onAfterRunRegisterAfterRenderObservable.add(function() {
            i._registerAfterRenderTime.endMonitoring()
        }),
        this._onBeforeRTT1Observer = e.onBeforeRTT1Observable.add(function() {
            i._RTT1Time.beginMonitoring()
        }),
        this._onAfterRTT1Observer = e.onAfterRTT1Observable.add(function() {
            i._RTT1Time.endMonitoring()
        })
    }
    return Object.defineProperty(a.prototype, "activeMeshesEvaluationTimeCounter", {
        get: function() {
            return this._activeMeshesEvaluationTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureActiveMeshesEvaluationTime", {
        get: function() {
            return this._captureActiveMeshesEvaluationTime
        },
        set: function(e) {
            var i = this;
            e !== this._captureActiveMeshesEvaluationTime && (this._captureActiveMeshesEvaluationTime = e,
            e ? (this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function() {
                Tools.StartPerformanceCounter("Active meshes evaluation"),
                i._activeMeshesEvaluationTime.beginMonitoring()
            }),
            this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function() {
                Tools.EndPerformanceCounter("Active meshes evaluation"),
                i._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(a.prototype, "renderTargetsRenderTimeCounter", {
        get: function() {
            return this._renderTargetsRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "registerBeforeTimeCounter", {
        get: function() {
            return this._registerBeforeRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "getRTT1TimeCounter", {
        get: function() {
            return this._RTT1Time
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "registerAfterTimeCounter", {
        get: function() {
            return this._registerAfterRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureRenderTargetsRenderTime", {
        get: function() {
            return this._captureRenderTargetsRenderTime
        },
        set: function(e) {
            var i = this;
            e !== this._captureRenderTargetsRenderTime && (this._captureRenderTargetsRenderTime = e,
            e ? (this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function() {
                Tools.StartPerformanceCounter("Render targets rendering"),
                i._renderTargetsRenderTime.beginMonitoring()
            }),
            this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function() {
                Tools.EndPerformanceCounter("Render targets rendering"),
                i._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(a.prototype, "particlesRenderTimeCounter", {
        get: function() {
            return this._particlesRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureParticlesRenderTime", {
        get: function() {
            return this._captureParticlesRenderTime
        },
        set: function(e) {
            var i = this;
            e !== this._captureParticlesRenderTime && (this._captureParticlesRenderTime = e,
            e ? (this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function() {
                Tools.StartPerformanceCounter("Particles"),
                i._particlesRenderTime.beginMonitoring()
            }),
            this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function() {
                Tools.EndPerformanceCounter("Particles"),
                i._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(a.prototype, "spritesRenderTimeCounter", {
        get: function() {
            return this._spritesRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureSpritesRenderTime", {
        get: function() {
            return this._captureSpritesRenderTime
        },
        set: function(e) {
            var i = this;
            e !== this._captureSpritesRenderTime && (this._captureSpritesRenderTime = e,
            this.scene.spriteManagers && (e ? (this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function() {
                Tools.StartPerformanceCounter("Sprites"),
                i._spritesRenderTime.beginMonitoring()
            }),
            this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function() {
                Tools.EndPerformanceCounter("Sprites"),
                i._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(a.prototype, "physicsTimeCounter", {
        get: function() {
            return this._physicsTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "capturePhysicsTime", {
        get: function() {
            return this._capturePhysicsTime
        },
        set: function(e) {
            var i = this;
            e !== this._capturePhysicsTime && (!this.scene.onBeforePhysicsObservable || (this._capturePhysicsTime = e,
            e ? (this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function() {
                Tools.StartPerformanceCounter("Physics"),
                i._physicsTime.beginMonitoring()
            }),
            this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function() {
                Tools.EndPerformanceCounter("Physics"),
                i._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(a.prototype, "animationsTimeCounter", {
        get: function() {
            return this._animationsTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureAnimationsTime", {
        get: function() {
            return this._captureAnimationsTime
        },
        set: function(e) {
            var i = this;
            e !== this._captureAnimationsTime && (this._captureAnimationsTime = e,
            e ? this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function() {
                i._animationsTime.endMonitoring()
            }) : (this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),
            this._onAfterAnimationsObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "frameTimeCounter", {
        get: function() {
            return this._frameTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureFrameTime", {
        get: function() {
            return this._captureFrameTime
        },
        set: function(e) {
            this._captureFrameTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "interFrameTimeCounter", {
        get: function() {
            return this._interFrameTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureInterFrameTime", {
        get: function() {
            return this._captureInterFrameTime
        },
        set: function(e) {
            this._captureInterFrameTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "renderTimeCounter", {
        get: function() {
            return this._renderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureRenderTime", {
        get: function() {
            return this._captureRenderTime
        },
        set: function(e) {
            var i = this;
            e !== this._captureRenderTime && (this._captureRenderTime = e,
            e ? (this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function() {
                i._renderTime.beginMonitoring(),
                Tools.StartPerformanceCounter("Main render")
            }),
            this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function() {
                i._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(a.prototype, "cameraRenderTimeCounter", {
        get: function() {
            return this._cameraRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureCameraRenderTime", {
        get: function() {
            return this._captureCameraRenderTime
        },
        set: function(e) {
            var i = this;
            e !== this._captureCameraRenderTime && (this._captureCameraRenderTime = e,
            e ? (this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function(o) {
                i._cameraRenderTime.beginMonitoring(),
                Tools.StartPerformanceCounter("Rendering camera " + o.name)
            }),
            this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function(o) {
                i._cameraRenderTime.endMonitoring(!1),
                Tools.EndPerformanceCounter("Rendering camera " + o.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(a.prototype, "drawCallsCounter", {
        get: function() {
            return this.scene.getEngine()._drawCalls
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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
    }
    ,
    a
}()
  , EngineInstrumentation = function() {
    function a(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(a.prototype, "gpuFrameTimeCounter", {
        get: function() {
            return this.engine.getGPUFrameTimeCounter()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "shaderCompilationTimeCounter", {
        get: function() {
            return this._shaderCompilationTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "captureShaderCompilationTime", {
        get: function() {
            return this._captureShaderCompilationTime
        },
        set: function(e) {
            var i = this;
            e !== this._captureShaderCompilationTime && (this._captureShaderCompilationTime = e,
            e ? (this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function() {
                i._shaderCompilationTime.fetchNewFrame(),
                i._shaderCompilationTime.beginMonitoring()
            }),
            this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function() {
                i._shaderCompilationTime.endMonitoring()
            })) : (this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),
            this._onBeforeShaderCompilationObserver = null,
            this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),
            this._onAfterShaderCompilationObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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
    }
    ,
    a
}()
  , KeepAssets = function(a) {
    __extends(e, a);
    function e() {
        return a !== null && a.apply(this, arguments) || this
    }
    return e
}(AbstractScene)
  , InstantiatedEntries = function() {
    function a() {
        this.rootNodes = [],
        this.skeletons = [],
        this.animationGroups = []
    }
    return a
}()
  , AssetContainer = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this) || this;
        return o._wasAddedToScene = !1,
        o.scene = i,
        o.sounds = [],
        o.effectLayers = [],
        o.layers = [],
        o.lensFlareSystems = [],
        o.proceduralTextures = [],
        o.reflectionProbes = [],
        i.onDisposeObservable.add(function() {
            o._wasAddedToScene || o.dispose()
        }),
        o._onContextRestoredObserver = i.getEngine().onContextRestoredObservable.add(function() {
            for (var s = 0, c = o.geometries; s < c.length; s++) {
                var d = c[s];
                d._rebuild()
            }
            for (var _ = 0, b = o.meshes; _ < b.length; _++) {
                var k = b[_];
                k._rebuild()
            }
            for (var j = 0, $ = o.particleSystems; j < $.length; j++) {
                var _e = $[j];
                _e.rebuild()
            }
            for (var et = 0, tt = o.textures; et < tt.length; et++) {
                var rt = tt[et];
                rt._rebuild()
            }
        }),
        o
    }
    return e.prototype.instantiateModelsToScene = function(i, o, s) {
        var c = this;
        o === void 0 && (o = !1);
        var d = {}
          , _ = {}
          , b = new InstantiatedEntries
          , k = []
          , j = [];
        s || (s = {
            doNotInstantiate: !0
        });
        var $ = function(_e, et) {
            if (d[_e.uniqueId] = et.uniqueId,
            _[et.uniqueId] = et,
            i && (et.name = i(_e.name)),
            et instanceof Mesh) {
                var tt = et;
                if (tt.morphTargetManager) {
                    var rt = _e.morphTargetManager;
                    tt.morphTargetManager = rt.clone();
                    for (var it = 0; it < rt.numTargets; it++) {
                        var nt = rt.getTarget(it)
                          , ot = tt.morphTargetManager.getTarget(it);
                        d[nt.uniqueId] = ot.uniqueId,
                        _[ot.uniqueId] = ot
                    }
                }
            }
        };
        return this.transformNodes.forEach(function(_e) {
            if (!_e.parent) {
                var et = _e.instantiateHierarchy(null, s, function(tt, rt) {
                    $(tt, rt)
                });
                et && b.rootNodes.push(et)
            }
        }),
        this.meshes.forEach(function(_e) {
            if (!_e.parent) {
                var et = _e.instantiateHierarchy(null, s, function(tt, rt) {
                    if ($(tt, rt),
                    rt.material) {
                        var it = rt;
                        if (it.material)
                            if (o) {
                                var nt = tt.material;
                                if (j.indexOf(nt) === -1) {
                                    var ot = nt.clone(i ? i(nt.name) : "Clone of " + nt.name);
                                    if (j.push(nt),
                                    d[nt.uniqueId] = ot.uniqueId,
                                    _[ot.uniqueId] = ot,
                                    nt.getClassName() === "MultiMaterial") {
                                        for (var at = nt, st = 0, ut = at.subMaterials; st < ut.length; st++) {
                                            var ct = ut[st];
                                            !ct || (ot = ct.clone(i ? i(ct.name) : "Clone of " + ct.name),
                                            j.push(ct),
                                            d[ct.uniqueId] = ot.uniqueId,
                                            _[ot.uniqueId] = ot)
                                        }
                                        at.subMaterials = at.subMaterials.map(function(lt) {
                                            return lt && _[d[lt.uniqueId]]
                                        })
                                    }
                                }
                                it.getClassName() !== "InstancedMesh" && (it.material = _[d[nt.uniqueId]])
                            } else
                                it.material.getClassName() === "MultiMaterial" ? c.scene.multiMaterials.indexOf(it.material) === -1 && c.scene.addMultiMaterial(it.material) : c.scene.materials.indexOf(it.material) === -1 && c.scene.addMaterial(it.material)
                    }
                });
                et && b.rootNodes.push(et)
            }
        }),
        this.skeletons.forEach(function(_e) {
            var et = _e.clone(i ? i(_e.name) : "Clone of " + _e.name);
            _e.overrideMesh && (et.overrideMesh = _[d[_e.overrideMesh.uniqueId]]);
            for (var tt = 0, rt = c.meshes; tt < rt.length; tt++) {
                var it = rt[tt];
                if (it.skeleton === _e && !it.isAnInstance) {
                    var nt = _[d[it.uniqueId]];
                    if (nt.isAnInstance || (nt.skeleton = et,
                    k.indexOf(et) !== -1))
                        continue;
                    k.push(et);
                    for (var ot = 0, at = et.bones; ot < at.length; ot++) {
                        var st = at[ot];
                        st._linkedTransformNode && (st._linkedTransformNode = _[d[st._linkedTransformNode.uniqueId]])
                    }
                }
            }
            b.skeletons.push(et)
        }),
        this.animationGroups.forEach(function(_e) {
            var et = _e.clone(_e.name, function(tt) {
                var rt = _[d[tt.uniqueId]];
                return rt || tt
            });
            b.animationGroups.push(et)
        }),
        b
    }
    ,
    e.prototype.addAllToScene = function() {
        var i = this;
        this._wasAddedToScene = !0,
        this.cameras.forEach(function(d) {
            i.scene.addCamera(d)
        }),
        this.lights.forEach(function(d) {
            i.scene.addLight(d)
        }),
        this.meshes.forEach(function(d) {
            i.scene.addMesh(d)
        }),
        this.skeletons.forEach(function(d) {
            i.scene.addSkeleton(d)
        }),
        this.animations.forEach(function(d) {
            i.scene.addAnimation(d)
        }),
        this.animationGroups.forEach(function(d) {
            i.scene.addAnimationGroup(d)
        }),
        this.multiMaterials.forEach(function(d) {
            i.scene.addMultiMaterial(d)
        }),
        this.materials.forEach(function(d) {
            i.scene.addMaterial(d)
        }),
        this.morphTargetManagers.forEach(function(d) {
            i.scene.addMorphTargetManager(d)
        }),
        this.geometries.forEach(function(d) {
            i.scene.addGeometry(d)
        }),
        this.transformNodes.forEach(function(d) {
            i.scene.addTransformNode(d)
        }),
        this.actionManagers.forEach(function(d) {
            i.scene.addActionManager(d)
        }),
        this.textures.forEach(function(d) {
            i.scene.addTexture(d)
        }),
        this.reflectionProbes.forEach(function(d) {
            i.scene.addReflectionProbe(d)
        }),
        this.environmentTexture && (this.scene.environmentTexture = this.environmentTexture);
        for (var o = 0, s = this.scene._serializableComponents; o < s.length; o++) {
            var c = s[o];
            c.addFromContainer(this)
        }
        this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),
        this._onContextRestoredObserver = null
    }
    ,
    e.prototype.removeAllFromScene = function() {
        var i = this;
        this._wasAddedToScene = !1,
        this.cameras.forEach(function(d) {
            i.scene.removeCamera(d)
        }),
        this.lights.forEach(function(d) {
            i.scene.removeLight(d)
        }),
        this.meshes.forEach(function(d) {
            i.scene.removeMesh(d)
        }),
        this.skeletons.forEach(function(d) {
            i.scene.removeSkeleton(d)
        }),
        this.animations.forEach(function(d) {
            i.scene.removeAnimation(d)
        }),
        this.animationGroups.forEach(function(d) {
            i.scene.removeAnimationGroup(d)
        }),
        this.multiMaterials.forEach(function(d) {
            i.scene.removeMultiMaterial(d)
        }),
        this.materials.forEach(function(d) {
            i.scene.removeMaterial(d)
        }),
        this.morphTargetManagers.forEach(function(d) {
            i.scene.removeMorphTargetManager(d)
        }),
        this.geometries.forEach(function(d) {
            i.scene.removeGeometry(d)
        }),
        this.transformNodes.forEach(function(d) {
            i.scene.removeTransformNode(d)
        }),
        this.actionManagers.forEach(function(d) {
            i.scene.removeActionManager(d)
        }),
        this.textures.forEach(function(d) {
            i.scene.removeTexture(d)
        }),
        this.reflectionProbes.forEach(function(d) {
            i.scene.removeReflectionProbe(d)
        }),
        this.environmentTexture === this.scene.environmentTexture && (this.scene.environmentTexture = null);
        for (var o = 0, s = this.scene._serializableComponents; o < s.length; o++) {
            var c = s[o];
            c.removeFromContainer(this)
        }
    }
    ,
    e.prototype.dispose = function() {
        this.cameras.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.cameras = [],
        this.lights.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.lights = [],
        this.meshes.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.meshes = [],
        this.skeletons.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.skeletons = [],
        this.animationGroups.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.animationGroups = [],
        this.multiMaterials.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.multiMaterials = [],
        this.materials.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.materials = [],
        this.geometries.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.geometries = [],
        this.transformNodes.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.transformNodes = [],
        this.actionManagers.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.actionManagers = [],
        this.textures.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.textures = [],
        this.reflectionProbes.slice(0).forEach(function(c) {
            c.dispose()
        }),
        this.reflectionProbes = [],
        this.environmentTexture && (this.environmentTexture.dispose(),
        this.environmentTexture = null);
        for (var i = 0, o = this.scene._serializableComponents; i < o.length; i++) {
            var s = o[i];
            s.removeFromContainer(this, !0)
        }
        this._onContextRestoredObserver && (this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),
        this._onContextRestoredObserver = null)
    }
    ,
    e.prototype._moveAssets = function(i, o, s) {
        if (!!i)
            for (var c = 0, d = i; c < d.length; c++) {
                var _ = d[c]
                  , b = !0;
                if (s)
                    for (var k = 0, j = s; k < j.length; k++) {
                        var $ = j[k];
                        if (_ === $) {
                            b = !1;
                            break
                        }
                    }
                b && (o.push(_),
                _._parentContainer = this)
            }
    }
    ,
    e.prototype.moveAllFromScene = function(i) {
        this._wasAddedToScene = !1,
        i === void 0 && (i = new KeepAssets);
        for (var o in this)
            this.hasOwnProperty(o) && (this[o] = this[o] || (o === "environmentTexture" ? null : []),
            this._moveAssets(this.scene[o], this[o], i[o]));
        this.environmentTexture = this.scene.environmentTexture,
        this.removeAllFromScene()
    }
    ,
    e.prototype.createRootMesh = function() {
        var i = new Mesh("assetContainerRootMesh",this.scene);
        return this.meshes.forEach(function(o) {
            o.parent || i.addChild(o)
        }),
        this.meshes.unshift(i),
        i
    }
    ,
    e.prototype.mergeAnimationsTo = function(i, o, s) {
        if (i === void 0 && (i = EngineStore.LastCreatedScene),
        s === void 0 && (s = null),
        !i)
            return Logger$2.Error("No scene available to merge animations to"),
            [];
        var c = s || function(b) {
            var k = null
              , j = b.animations.length ? b.animations[0].targetProperty : ""
              , $ = b.name.split(".").join("").split("_primitive")[0];
            switch (j) {
            case "position":
            case "rotationQuaternion":
                k = i.getTransformNodeByName(b.name) || i.getTransformNodeByName($);
                break;
            case "influence":
                k = i.getMorphTargetByName(b.name) || i.getMorphTargetByName($);
                break;
            default:
                k = i.getNodeByName(b.name) || i.getNodeByName($)
            }
            return k
        }
          , d = this.getNodes();
        d.forEach(function(b) {
            var k = c(b);
            if (k !== null) {
                for (var j = function(tt) {
                    for (var rt = k.animations.filter(function(st) {
                        return st.targetProperty === tt.targetProperty
                    }), it = 0, nt = rt; it < nt.length; it++) {
                        var ot = nt[it]
                          , at = k.animations.indexOf(ot, 0);
                        at > -1 && k.animations.splice(at, 1)
                    }
                }, $ = 0, _e = b.animations; $ < _e.length; $++) {
                    var et = _e[$];
                    j(et)
                }
                k.animations = k.animations.concat(b.animations)
            }
        });
        var _ = new Array;
        return this.animationGroups.slice().forEach(function(b) {
            _.push(b.clone(b.name, c)),
            b.animatables.forEach(function(k) {
                k.stop()
            })
        }),
        o.forEach(function(b) {
            var k = c(b.target);
            k && (i.beginAnimation(k, b.fromFrame, b.toFrame, b.loopAnimation, b.speedRatio, b.onAnimationEnd ? b.onAnimationEnd : void 0, void 0, !0, void 0, b.onAnimationLoop ? b.onAnimationLoop : void 0),
            i.stopAnimation(b.target))
        }),
        _
    }
    ,
    e
}(AbstractScene)
  , Sound = function() {
    function a(e, i, o, s, c) {
        var d = this;
        s === void 0 && (s = null);
        var _, b, k, j, $;
        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 = o,
        a._SceneComponentInitialization(o),
        this._readyToPlayCallback = s,
        this._customAttenuationFunction = function(nt, ot, at, st, ut) {
            return ot < at ? nt * (1 - ot / at) : 0
        }
        ,
        c && (this.autoplay = c.autoplay || !1,
        this._loop = c.loop || !1,
        c.volume !== void 0 && (this._volume = c.volume),
        this.spatialSound = (_ = c.spatialSound) !== null && _ !== void 0 ? _ : !1,
        this.maxDistance = (b = c.maxDistance) !== null && b !== void 0 ? b : 100,
        this.useCustomAttenuation = (k = c.useCustomAttenuation) !== null && k !== void 0 ? k : !1,
        this.rolloffFactor = c.rolloffFactor || 1,
        this.refDistance = c.refDistance || 1,
        this.distanceModel = c.distanceModel || "linear",
        this._playbackRate = c.playbackRate || 1,
        this._streaming = (j = c.streaming) !== null && j !== void 0 ? j : !1,
        this._length = c.length,
        this._offset = c.offset),
        (($ = Engine.audioEngine) === null || $ === void 0 ? void 0 : $.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 _e = !0;
            if (i)
                try {
                    typeof i == "string" ? this._urlType = "String" : i instanceof ArrayBuffer ? this._urlType = "ArrayBuffer" : i instanceof HTMLMediaElement ? this._urlType = "MediaElement" : i instanceof MediaStream ? this._urlType = "MediaStream" : Array.isArray(i) && (this._urlType = "Array");
                    var et = []
                      , tt = !1;
                    switch (this._urlType) {
                    case "MediaElement":
                        this._streaming = !0,
                        this._isReadyToPlay = !0,
                        this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(i),
                        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(i),
                        this.autoplay && this.play(0, this._offset, this._length),
                        this._readyToPlayCallback && this._readyToPlayCallback();
                        break;
                    case "ArrayBuffer":
                        i.byteLength > 0 && (tt = !0,
                        this._soundLoaded(i));
                        break;
                    case "String":
                        et.push(i);
                    case "Array":
                        et.length === 0 && (et = i);
                        for (var rt = 0; rt < et.length; rt++) {
                            var it = et[rt];
                            if (tt = c && c.skipCodecCheck || it.indexOf(".mp3", it.length - 4) !== -1 && Engine.audioEngine.isMP3supported || it.indexOf(".ogg", it.length - 4) !== -1 && Engine.audioEngine.isOGGsupported || it.indexOf(".wav", it.length - 4) !== -1 || it.indexOf(".m4a", it.length - 4) !== -1 || it.indexOf("blob:") !== -1,
                            tt) {
                                this._streaming ? (this._htmlAudioElement = new Audio(it),
                                this._htmlAudioElement.controls = !1,
                                this._htmlAudioElement.loop = this.loop,
                                Tools.SetCorsBehavior(it, this._htmlAudioElement),
                                this._htmlAudioElement.preload = "auto",
                                this._htmlAudioElement.addEventListener("canplaythrough", function() {
                                    d._isReadyToPlay = !0,
                                    d.autoplay && d.play(0, d._offset, d._length),
                                    d._readyToPlayCallback && d._readyToPlayCallback()
                                }),
                                document.body.appendChild(this._htmlAudioElement),
                                this._htmlAudioElement.load()) : this._scene._loadFile(it, function(nt) {
                                    d._soundLoaded(nt)
                                }, void 0, !0, !0, function(nt) {
                                    nt && Logger$2.Error("XHR " + nt.status + " error on: " + it + "."),
                                    Logger$2.Error("Sound creation aborted."),
                                    d._scene.mainSoundTrack.removeSound(d)
                                });
                                break
                            }
                        }
                        break;
                    default:
                        _e = !1;
                        break
                    }
                    _e ? tt || (this._isReadyToPlay = !0,
                    this._readyToPlayCallback && window.setTimeout(function() {
                        d._readyToPlayCallback && d._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() {
                d._readyToPlayCallback && d._readyToPlayCallback()
            }, 1e3)
    }
    return Object.defineProperty(a.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(a.prototype, "currentTime", {
        get: function() {
            var e;
            if (this._htmlAudioElement)
                return this._htmlAudioElement.currentTime;
            var i = this._startOffset;
            return this.isPlaying && ((e = Engine.audioEngine) === null || e === void 0 ? void 0 : e.audioContext) && (i += Engine.audioEngine.audioContext.currentTime - this._startTime),
            i
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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))
    }
    ,
    a.prototype.isReady = function() {
        return this._isReadyToPlay
    }
    ,
    a.prototype.getClassName = function() {
        return "Sound"
    }
    ,
    a.prototype._soundLoaded = function(e) {
        var i = this, o;
        !(!((o = Engine.audioEngine) === null || o === void 0) && o.audioContext) || Engine.audioEngine.audioContext.decodeAudioData(e, function(s) {
            i._audioBuffer = s,
            i._isReadyToPlay = !0,
            i.autoplay && i.play(0, i._offset, i._length),
            i._readyToPlayCallback && i._readyToPlayCallback()
        }, function(s) {
            Logger$2.Error("Error while decoding audio data for: " + i.name + " / Error: " + s)
        })
    }
    ,
    a.prototype.setAudioBuffer = function(e) {
        var i;
        !((i = Engine.audioEngine) === null || i === void 0) && i.canUseWebAudio && (this._audioBuffer = e,
        this._isReadyToPlay = !0)
    }
    ,
    a.prototype.updateOptions = function(e) {
        var i, o, s, c, d, _, b, k, j;
        e && (this.loop = (i = e.loop) !== null && i !== void 0 ? i : this.loop,
        this.maxDistance = (o = e.maxDistance) !== null && o !== void 0 ? o : this.maxDistance,
        this.useCustomAttenuation = (s = e.useCustomAttenuation) !== null && s !== void 0 ? s : this.useCustomAttenuation,
        this.rolloffFactor = (c = e.rolloffFactor) !== null && c !== void 0 ? c : this.rolloffFactor,
        this.refDistance = (d = e.refDistance) !== null && d !== void 0 ? d : this.refDistance,
        this.distanceModel = (_ = e.distanceModel) !== null && _ !== void 0 ? _ : this.distanceModel,
        this._playbackRate = (b = e.playbackRate) !== null && b !== void 0 ? b : this._playbackRate,
        this._length = (k = e.length) !== null && k !== void 0 ? k : void 0,
        this._offset = (j = e.offset) !== null && j !== void 0 ? j : 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))))
    }
    ,
    a.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))
    }
    ,
    a.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))
    }
    ,
    a.prototype.switchPanningModelToHRTF = function() {
        this._panningModel = "HRTF",
        this._switchPanningModel()
    }
    ,
    a.prototype.switchPanningModelToEqualPower = function() {
        this._panningModel = "equalpower",
        this._switchPanningModel()
    }
    ,
    a.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)
    }
    ,
    a.prototype.connectToSoundTrackAudioNode = function(e) {
        var i;
        ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.canUseWebAudio) && this._outputAudioNode && (this._isOutputConnected && this._outputAudioNode.disconnect(),
        this._outputAudioNode.connect(e),
        this._isOutputConnected = !0)
    }
    ,
    a.prototype.setDirectionalCone = function(e, i, o) {
        if (i < 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 = i,
        this._coneOuterGain = o,
        this._isDirectional = !0,
        this.isPlaying && this.loop && (this.stop(),
        this.play(0, this._offset, this._length))
    }
    ,
    Object.defineProperty(a.prototype, "directionalConeInnerAngle", {
        get: function() {
            return this._coneInnerAngle
        },
        set: function(e) {
            var i;
            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,
                ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.canUseWebAudio) && this.spatialSound && this._soundPanner && (this._soundPanner.coneInnerAngle = this._coneInnerAngle)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "directionalConeOuterAngle", {
        get: function() {
            return this._coneOuterAngle
        },
        set: function(e) {
            var i;
            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,
                ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.canUseWebAudio) && this.spatialSound && this._soundPanner && (this._soundPanner.coneOuterAngle = this._coneOuterAngle)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setPosition = function(e) {
        var i;
        e.equals(this._position) || (this._position.copyFrom(e),
        ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.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))
    }
    ,
    a.prototype.setLocalDirectionToMesh = function(e) {
        var i;
        this._localDirection = e,
        ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.canUseWebAudio) && this._connectedTransformNode && this.isPlaying && this._updateDirection()
    }
    ,
    a.prototype._updateDirection = function() {
        if (!(!this._connectedTransformNode || !this._soundPanner)) {
            var e = this._connectedTransformNode.getWorldMatrix()
              , i = Vector3.TransformNormal(this._localDirection, e);
            i.normalize(),
            this._soundPanner.setOrientation(i.x, i.y, i.z)
        }
    }
    ,
    a.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 i = this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);
            this._soundGain.gain.value = this._customAttenuationFunction(this._volume, i, this.maxDistance, this.refDistance, this.rolloffFactor)
        }
    }
    ,
    a.prototype.setAttenuationFunction = function(e) {
        this._customAttenuationFunction = e
    }
    ,
    a.prototype.play = function(e, i, o) {
        var s = this, c, d, _, b;
        if (this._isReadyToPlay && this._scene.audioEnabled && ((c = Engine.audioEngine) === null || c === void 0 ? void 0 : c.audioContext))
            try {
                this._startOffset < 0 && (e = -this._startOffset,
                this._startOffset = 0);
                var k = e ? ((d = Engine.audioEngine) === null || d === void 0 ? void 0 : d.audioContext.currentTime) + e : (_ = Engine.audioEngine) === null || _ === void 0 ? void 0 : _.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() {
                        s._onended()
                    }
                    ,
                    this._htmlAudioElement.playbackRate = this._playbackRate),
                    this._streamingSource.disconnect(),
                    this._inputAudioNode && this._streamingSource.connect(this._inputAudioNode),
                    this._htmlAudioElement) {
                        var j = function() {
                            var $, _e;
                            if (!(($ = Engine.audioEngine) === null || $ === void 0) && $.unlocked) {
                                var et = s._htmlAudioElement.play();
                                et !== void 0 && et.catch(function(tt) {
                                    var rt, it;
                                    (rt = Engine.audioEngine) === null || rt === void 0 || rt.lock(),
                                    (s.loop || s.autoplay) && ((it = Engine.audioEngine) === null || it === void 0 || it.onAudioUnlockedObservable.addOnce(function() {
                                        j()
                                    }))
                                })
                            } else
                                (s.loop || s.autoplay) && ((_e = Engine.audioEngine) === null || _e === void 0 || _e.onAudioUnlockedObservable.addOnce(function() {
                                    j()
                                }))
                        };
                        j()
                    }
                } else {
                    var j = function() {
                        var _e, et, tt;
                        if (!((_e = Engine.audioEngine) === null || _e === void 0) && _e.audioContext) {
                            if (o = o || s._length,
                            i = i || s._offset,
                            s._soundSource) {
                                var rt = s._soundSource;
                                rt.onended = function() {
                                    rt.disconnect()
                                }
                            }
                            if (s._soundSource = (et = Engine.audioEngine) === null || et === void 0 ? void 0 : et.audioContext.createBufferSource(),
                            s._soundSource && s._inputAudioNode) {
                                s._soundSource.buffer = s._audioBuffer,
                                s._soundSource.connect(s._inputAudioNode),
                                s._soundSource.loop = s.loop,
                                i !== void 0 && (s._soundSource.loopStart = i),
                                o !== void 0 && (s._soundSource.loopEnd = (i | 0) + o),
                                s._soundSource.playbackRate.value = s._playbackRate,
                                s._soundSource.onended = function() {
                                    s._onended()
                                }
                                ,
                                k = e ? ((tt = Engine.audioEngine) === null || tt === void 0 ? void 0 : tt.audioContext.currentTime) + e : Engine.audioEngine.audioContext.currentTime;
                                var it = s.isPaused ? s._startOffset % s._soundSource.buffer.duration : i || 0;
                                s._soundSource.start(k, it, s.loop ? void 0 : o)
                            }
                        }
                    };
                    ((b = Engine.audioEngine) === null || b === void 0 ? void 0 : b.audioContext.state) === "suspended" ? setTimeout(function() {
                        var _e;
                        ((_e = Engine.audioEngine) === null || _e === void 0 ? void 0 : _e.audioContext.state) === "suspended" ? (Engine.audioEngine.lock(),
                        (s.loop || s.autoplay) && Engine.audioEngine.onAudioUnlockedObservable.addOnce(function() {
                            j()
                        })) : j()
                    }, 500) : j()
                }
                this._startTime = k,
                this.isPlaying = !0,
                this.isPaused = !1
            } catch ($) {
                Logger$2.Error("Error while trying to play audio: " + this.name + ", " + $.message)
            }
    }
    ,
    a.prototype._onended = function() {
        this.isPlaying = !1,
        this._startOffset = 0,
        this.onended && this.onended(),
        this.onEndedObservable.notifyObservers(this)
    }
    ,
    a.prototype.stop = function(e) {
        var i = this, o;
        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 (((o = Engine.audioEngine) === null || o === void 0 ? void 0 : o.audioContext) && this._soundSource) {
                var s = e ? Engine.audioEngine.audioContext.currentTime + e : void 0;
                this._soundSource.stop(s),
                s === void 0 ? (this.isPlaying = !1,
                this._soundSource.onended = function() {}
                ) : this._soundSource.onended = function() {
                    i.isPlaying = !1
                }
                ,
                this.isPaused || (this._startOffset = 0)
            }
        }
    }
    ,
    a.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))
    }
    ,
    a.prototype.setVolume = function(e, i) {
        var o;
        ((o = Engine.audioEngine) === null || o === void 0 ? void 0 : o.canUseWebAudio) && this._soundGain && (i && 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 + i)) : this._soundGain.gain.value = e),
        this._volume = e
    }
    ,
    a.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))
    }
    ,
    a.prototype.getVolume = function() {
        return this._volume
    }
    ,
    a.prototype.attachToMesh = function(e) {
        var i = 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(o) {
            return i._onRegisterAfterWorldMatrixUpdate(o)
        }
        ,
        this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)
    }
    ,
    a.prototype.detachFromMesh = function() {
        this._connectedTransformNode && this._registerFunc && (this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),
        this._registerFunc = null,
        this._connectedTransformNode = null)
    }
    ,
    a.prototype._onRegisterAfterWorldMatrixUpdate = function(e) {
        var i;
        if (!e.getBoundingInfo)
            this.setPosition(e.absolutePosition);
        else {
            var o = e
              , s = o.getBoundingInfo();
            this.setPosition(s.boundingSphere.centerWorld)
        }
        ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.canUseWebAudio) && this._isDirectional && this.isPlaying && this._updateDirection()
    }
    ,
    a.prototype.clone = function() {
        var e = this;
        if (this._streaming)
            return null;
        var i = function() {
            e._isReadyToPlay ? (s._audioBuffer = e.getAudioBuffer(),
            s._isReadyToPlay = !0,
            s.autoplay && s.play(0, e._offset, e._length)) : window.setTimeout(i, 300)
        }
          , o = {
            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
        }
          , s = new a(this.name + "_cloned",new ArrayBuffer(0),this._scene,null,o);
        return this.useCustomAttenuation && s.setAttenuationFunction(this._customAttenuationFunction),
        s.setPosition(this._position),
        s.setPlaybackRate(this._playbackRate),
        i(),
        s
    }
    ,
    a.prototype.getAudioBuffer = function() {
        return this._audioBuffer
    }
    ,
    a.prototype.getSoundSource = function() {
        return this._soundSource
    }
    ,
    a.prototype.getSoundGain = function() {
        return this._soundGain
    }
    ,
    a.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
    }
    ,
    a.Parse = function(e, i, o, s) {
        var c = e.name, d;
        e.url ? d = o + e.url : d = o + c;
        var _ = {
            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
        }, b;
        if (!s)
            b = new a(c,d,i,function() {
                i._removePendingData(b)
            }
            ,_),
            i._addPendingData(b);
        else {
            var k = function() {
                s._isReadyToPlay ? (b._audioBuffer = s.getAudioBuffer(),
                b._isReadyToPlay = !0,
                b.autoplay && b.play(0, b._offset, b._length)) : window.setTimeout(k, 300)
            };
            b = new a(c,new ArrayBuffer(0),i,null,_),
            k()
        }
        if (e.position) {
            var j = Vector3.FromArray(e.position);
            b.setPosition(j)
        }
        if (e.isDirectional && (b.setDirectionalCone(e.coneInnerAngle || 360, e.coneOuterAngle || 360, e.coneOuterGain || 0),
        e.localDirectionToMesh)) {
            var $ = Vector3.FromArray(e.localDirectionToMesh);
            b.setLocalDirectionToMesh($)
        }
        if (e.connectedMeshId) {
            var _e = i.getMeshById(e.connectedMeshId);
            _e && b.attachToMesh(_e)
        }
        return e.metadata && (b.metadata = e.metadata),
        b
    }
    ,
    a._SceneComponentInitialization = function(e) {
        throw _WarnImport("AudioSceneComponent")
    }
    ,
    a
}()
  , ThinSprite = function() {
    function a() {
        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(a.prototype, "animationStarted", {
        get: function() {
            return this._animationStarted
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "fromIndex", {
        get: function() {
            return this._fromIndex
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "toIndex", {
        get: function() {
            return this._toIndex
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "loopAnimation", {
        get: function() {
            return this._loopAnimation
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "delay", {
        get: function() {
            return Math.max(this._delay, 1)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.playAnimation = function(e, i, o, s, c) {
        this._fromIndex = e,
        this._toIndex = i,
        this._loopAnimation = o,
        this._delay = s || 1,
        this._animationStarted = !0,
        this._onBaseAnimationEnd = c,
        e < i ? this._direction = 1 : (this._direction = -1,
        this._toIndex = e,
        this._fromIndex = i),
        this.cellIndex = e,
        this._time = 0
    }
    ,
    a.prototype.stopAnimation = function() {
        this._animationStarted = !1
    }
    ,
    a.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()))))
    }
    ,
    a
}()
  , Sprite = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this) || this;
        return s.name = i,
        s.animations = new Array,
        s.isPickable = !1,
        s.useAlphaForPicking = !1,
        s.onDisposeObservable = new Observable,
        s._onAnimationEnd = null,
        s._endAnimation = function() {
            s._onAnimationEnd && s._onAnimationEnd(),
            s.disposeWhenFinishedAnimating && s.dispose()
        }
        ,
        s.color = new Color4(1,1,1,1),
        s.position = Vector3.Zero(),
        s._manager = o,
        s._manager.sprites.push(s),
        s.uniqueId = s._manager.scene.getUniqueId(),
        s
    }
    return Object.defineProperty(e.prototype, "size", {
        get: function() {
            return this.width
        },
        set: function(i) {
            this.width = i,
            this.height = i
        },
        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(i) {
            this.playAnimation(i, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "toIndex", {
        get: function() {
            return this._toIndex
        },
        set: function(i) {
            this.playAnimation(this._fromIndex, i, this._loopAnimation, this._delay, this._onAnimationEnd)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "loopAnimation", {
        get: function() {
            return this._loopAnimation
        },
        set: function(i) {
            this.playAnimation(this._fromIndex, this._toIndex, i, this._delay, this._onAnimationEnd)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "delay", {
        get: function() {
            return Math.max(this._delay, 1)
        },
        set: function(i) {
            this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, i, this._onAnimationEnd)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.playAnimation = function(i, o, s, c, d) {
        d === void 0 && (d = null),
        this._onAnimationEnd = d,
        a.prototype.playAnimation.call(this, i, o, s, c, this._endAnimation)
    }
    ,
    e.prototype.dispose = function() {
        for (var i = 0; i < this._manager.sprites.length; i++)
            this._manager.sprites[i] == this && this._manager.sprites.splice(i, 1);
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear()
    }
    ,
    e.prototype.serialize = function() {
        var i = {};
        return i.name = this.name,
        i.position = this.position.asArray(),
        i.color = this.color.asArray(),
        i.width = this.width,
        i.height = this.height,
        i.angle = this.angle,
        i.cellIndex = this.cellIndex,
        i.cellRef = this.cellRef,
        i.invertU = this.invertU,
        i.invertV = this.invertV,
        i.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating,
        i.isPickable = this.isPickable,
        i.isVisible = this.isVisible,
        i.useAlphaForPicking = this.useAlphaForPicking,
        i.animationStarted = this.animationStarted,
        i.fromIndex = this.fromIndex,
        i.toIndex = this.toIndex,
        i.loopAnimation = this.loopAnimation,
        i.delay = this.delay,
        i
    }
    ,
    e.Parse = function(i, o) {
        var s = new e(i.name,o);
        return s.position = Vector3.FromArray(i.position),
        s.color = Color4.FromArray(i.color),
        s.width = i.width,
        s.height = i.height,
        s.angle = i.angle,
        s.cellIndex = i.cellIndex,
        s.cellRef = i.cellRef,
        s.invertU = i.invertU,
        s.invertV = i.invertV,
        s.disposeWhenFinishedAnimating = i.disposeWhenFinishedAnimating,
        s.isPickable = i.isPickable,
        s.isVisible = i.isVisible,
        s.useAlphaForPicking = i.useAlphaForPicking,
        s.fromIndex = i.fromIndex,
        s.toIndex = i.toIndex,
        s.loopAnimation = i.loopAnimation,
        s.delay = i.delay,
        i.animationStarted && s.playAnimation(s.fromIndex, s.toIndex, s.loopAnimation, s.delay),
        s
    }
    ,
    e
}(ThinSprite);
Scene.prototype._internalPickSprites = function(a, e, i, o) {
    if (!PickingInfo)
        return null;
    var s = null;
    if (!o) {
        if (!this.activeCamera)
            return null;
        o = this.activeCamera
    }
    if (this.spriteManagers.length > 0)
        for (var c = 0; c < this.spriteManagers.length; c++) {
            var d = this.spriteManagers[c];
            if (!!d.isPickable) {
                var _ = d.intersects(a, o, e, i);
                if (!(!_ || !_.hit) && !(!i && s != null && _.distance >= s.distance) && (s = _,
                i))
                    break
            }
        }
    return s || new PickingInfo
}
;
Scene.prototype._internalMultiPickSprites = function(a, e, i) {
    if (!PickingInfo)
        return null;
    var o = new Array;
    if (!i) {
        if (!this.activeCamera)
            return null;
        i = this.activeCamera
    }
    if (this.spriteManagers.length > 0)
        for (var s = 0; s < this.spriteManagers.length; s++) {
            var c = this.spriteManagers[s];
            if (!!c.isPickable) {
                var d = c.multiIntersects(a, i, e);
                d !== null && (o = o.concat(d))
            }
        }
    return o
}
;
Scene.prototype.pickSprite = function(a, e, i, o, s) {
    if (!this._tempSpritePickingRay)
        return null;
    this.createPickingRayInCameraSpaceToRef(a, e, this._tempSpritePickingRay, s);
    var c = this._internalPickSprites(this._tempSpritePickingRay, i, o, s);
    return c && (c.ray = this.createPickingRayInCameraSpace(a, e, s)),
    c
}
;
Scene.prototype.pickSpriteWithRay = function(a, e, i, o) {
    if (!this._tempSpritePickingRay)
        return null;
    if (!o) {
        if (!this.activeCamera)
            return null;
        o = this.activeCamera
    }
    Ray.TransformToRef(a, o.getViewMatrix(), this._tempSpritePickingRay);
    var s = this._internalPickSprites(this._tempSpritePickingRay, e, i, o);
    return s && (s.ray = a),
    s
}
;
Scene.prototype.multiPickSprite = function(a, e, i, o) {
    return this.createPickingRayInCameraSpaceToRef(a, e, this._tempSpritePickingRay, o),
    this._internalMultiPickSprites(this._tempSpritePickingRay, i, o)
}
;
Scene.prototype.multiPickSpriteWithRay = function(a, e, i) {
    if (!this._tempSpritePickingRay)
        return null;
    if (!i) {
        if (!this.activeCamera)
            return null;
        i = this.activeCamera
    }
    return Ray.TransformToRef(a, i.getViewMatrix(), this._tempSpritePickingRay),
    this._internalMultiPickSprites(this._tempSpritePickingRay, e, i)
}
;
Scene.prototype.setPointerOverSprite = function(a) {
    this._pointerOverSprite !== a && (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.processTrigger(10, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)),
    this._pointerOverSprite = a,
    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 a(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(i) {
            return i.actionManager ? i.isPickable && i.actionManager.hasPointerTriggers : !1
        }
    }
    return a.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)
    }
    ,
    a.prototype.rebuild = function() {}
    ,
    a.prototype.dispose = function() {
        this.scene.onBeforeSpritesRenderingObservable.clear(),
        this.scene.onAfterSpritesRenderingObservable.clear();
        for (var e = this.scene.spriteManagers; e.length; )
            e[0].dispose()
    }
    ,
    a.prototype._pickSpriteButKeepRay = function(e, i, o, s, c) {
        var d = this.scene.pickSprite(i, o, this._spritePredicate, s, c);
        return d && (d.ray = e ? e.ray : null),
        d
    }
    ,
    a.prototype._pointerMove = function(e, i, o, s, c) {
        var d = this.scene;
        return s ? d.setPointerOverSprite(null) : (o = this._pickSpriteButKeepRay(o, e, i, !1, d.cameraToUseForPointers || void 0),
        o && o.hit && o.pickedSprite ? (d.setPointerOverSprite(o.pickedSprite),
        !d.doNotHandleCursors && c && (d._pointerOverSprite && d._pointerOverSprite.actionManager && d._pointerOverSprite.actionManager.hoverCursor ? c.style.cursor = d._pointerOverSprite.actionManager.hoverCursor : c.style.cursor = d.hoverCursor)) : d.setPointerOverSprite(null)),
        o
    }
    ,
    a.prototype._pointerDown = function(e, i, o, s) {
        var c = this.scene;
        if (c._pickedDownSprite = null,
        c.spriteManagers.length > 0 && (o = c.pickSprite(e, i, this._spritePredicate, !1, c.cameraToUseForPointers || void 0),
        o && o.hit && o.pickedSprite && o.pickedSprite.actionManager)) {
            switch (c._pickedDownSprite = o.pickedSprite,
            s.button) {
            case 0:
                o.pickedSprite.actionManager.processTrigger(2, ActionEvent.CreateNewFromSprite(o.pickedSprite, c, s));
                break;
            case 1:
                o.pickedSprite.actionManager.processTrigger(4, ActionEvent.CreateNewFromSprite(o.pickedSprite, c, s));
                break;
            case 2:
                o.pickedSprite.actionManager.processTrigger(3, ActionEvent.CreateNewFromSprite(o.pickedSprite, c, s));
                break
            }
            o.pickedSprite.actionManager && o.pickedSprite.actionManager.processTrigger(5, ActionEvent.CreateNewFromSprite(o.pickedSprite, c, s))
        }
        return o
    }
    ,
    a.prototype._pointerUp = function(e, i, o, s) {
        var c = this.scene;
        if (c.spriteManagers.length > 0) {
            var d = c.pickSprite(e, i, this._spritePredicate, !1, c.cameraToUseForPointers || void 0);
            d && (d.hit && d.pickedSprite && d.pickedSprite.actionManager && (d.pickedSprite.actionManager.processTrigger(7, ActionEvent.CreateNewFromSprite(d.pickedSprite, c, s)),
            d.pickedSprite.actionManager && (this.scene._inputManager._isPointerSwiping() || d.pickedSprite.actionManager.processTrigger(1, ActionEvent.CreateNewFromSprite(d.pickedSprite, c, s)))),
            c._pickedDownSprite && c._pickedDownSprite.actionManager && c._pickedDownSprite !== d.pickedSprite && c._pickedDownSprite.actionManager.processTrigger(16, ActionEvent.CreateNewFromSprite(c._pickedDownSprite, c, s)))
        }
        return o
    }
    ,
    a
}()
  , name$l = "spritesPixelShader"
  , shader$l = `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$l] = shader$l;
var name$k = "spritesVertexShader"
  , shader$k = `
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$k] = shader$k;
var SpriteRenderer = function() {
    function a(e, i, o, s) {
        o === void 0 && (o = .01),
        s === void 0 && (s = null),
        this.blendMode = 2,
        this.autoResetAlpha = !0,
        this.disableDepthWrite = !1,
        this.fogEnabled = !0,
        this._useVAO = !1,
        this._useInstancing = !1,
        this._vertexBuffers = {},
        this._capacity = i,
        this._epsilon = o,
        this._engine = e,
        this._useInstancing = e.getCaps().instancedArrays,
        this._useVAO = e.getCaps().vertexArrayObject && !e.disableVertexArrayObjects,
        this._scene = s,
        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(i * this._vertexBufferSize * (this._useInstancing ? 1 : 4)),
        this._buffer = new Buffer(e,this._vertexData,!0,this._vertexBufferSize);
        var c = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing), d = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing), _ = 6, b;
        if (this._useInstancing) {
            var k = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
            this._spriteBuffer = new Buffer(e,k,!1,2),
            b = this._spriteBuffer.createVertexBuffer("offsets", 0, 2)
        } else
            b = this._buffer.createVertexBuffer("offsets", _, 2, this._vertexBufferSize, this._useInstancing),
            _ += 2;
        var j = this._buffer.createVertexBuffer("inverts", _, 2, this._vertexBufferSize, this._useInstancing)
          , $ = this._buffer.createVertexBuffer("cellInfo", _ + 2, 4, this._vertexBufferSize, this._useInstancing)
          , _e = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, _ + 6, 4, this._vertexBufferSize, this._useInstancing);
        this._vertexBuffers[VertexBuffer.PositionKind] = c,
        this._vertexBuffers.options = d,
        this._vertexBuffers.offsets = b,
        this._vertexBuffers.inverts = j,
        this._vertexBuffers.cellInfo = $,
        this._vertexBuffers[VertexBuffer.ColorKind] = _e,
        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(a.prototype, "capacity", {
        get: function() {
            return this._capacity
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.render = function(e, i, o, s, c) {
        if (c === void 0 && (c = null),
        !(!this.texture || !this.texture.isReady() || !e.length)) {
            var d = this._drawWrapperBase
              , _ = this._drawWrapperDepth
              , b = !1;
            this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0 && (d = this._drawWrapperFog,
            _ = this._drawWrapperFogDepth,
            b = !0);
            var k = d.effect;
            if (!!k.isReady()) {
                for (var j = this._engine, $ = !!(this._scene && this._scene.useRightHandedSystem), _e = this.texture.getBaseSize(), et = Math.min(this._capacity, e.length), tt = 0, rt = !0, it = 0; it < et; it++) {
                    var nt = e[it];
                    !nt || !nt.isVisible || (rt = !1,
                    nt._animate(i),
                    this._appendSpriteVertex(tt++, nt, 0, 0, _e, $, c),
                    this._useInstancing || (this._appendSpriteVertex(tt++, nt, 1, 0, _e, $, c),
                    this._appendSpriteVertex(tt++, nt, 1, 1, _e, $, c),
                    this._appendSpriteVertex(tt++, nt, 0, 1, _e, $, c)))
                }
                if (!rt) {
                    this._buffer.update(this._vertexData);
                    var ot = j.depthCullingState.cull || !0
                      , at = j.depthCullingState.zOffset
                      , st = j.depthCullingState.zOffsetUnits;
                    if (j.setState(ot, at, !1, !1, void 0, void 0, st),
                    j.enableEffect(d),
                    k.setTexture("diffuseSampler", this.texture),
                    k.setMatrix("view", o),
                    k.setMatrix("projection", s),
                    b) {
                        var ut = this._scene;
                        k.setFloat4("vFogInfos", ut.fogMode, ut.fogStart, ut.fogEnd, ut.fogDensity),
                        k.setColor3("vFogColor", ut.fogColor)
                    }
                    this._useVAO ? (this._vertexArrayObject || (this._vertexArrayObject = j.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, k)),
                    j.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer)) : j.bindBuffers(this._vertexBuffers, this._indexBuffer, k),
                    j.depthCullingState.depthFunc = j.useReverseDepthBuffer ? 518 : 515,
                    this.disableDepthWrite || (k.setBool("alphaTest", !0),
                    j.setColorWrite(!1),
                    j.enableEffect(_),
                    this._useInstancing ? j.drawArraysType(7, 0, 4, tt) : j.drawElementsType(0, 0, tt / 4 * 6),
                    j.enableEffect(d),
                    j.setColorWrite(!0),
                    k.setBool("alphaTest", !1)),
                    j.setAlphaMode(this.blendMode),
                    this._useInstancing ? j.drawArraysType(7, 0, 4, tt) : j.drawElementsType(0, 0, tt / 4 * 6),
                    this.autoResetAlpha && j.setAlphaMode(0),
                    $ && this._scene.getEngine().setState(ot, at, !1, !0, void 0, void 0, st),
                    j.unbindInstanceAttributes()
                }
            }
        }
    }
    ,
    a.prototype._appendSpriteVertex = function(e, i, o, s, c, d, _) {
        var b = e * this._vertexBufferSize;
        if (o === 0 ? o = this._epsilon : o === 1 && (o = 1 - this._epsilon),
        s === 0 ? s = this._epsilon : s === 1 && (s = 1 - this._epsilon),
        _)
            _(i, c);
        else {
            i.cellIndex || (i.cellIndex = 0);
            var k = c.width / this.cellWidth
              , j = i.cellIndex / k >> 0;
            i._xOffset = (i.cellIndex - j * k) * this.cellWidth / c.width,
            i._yOffset = j * this.cellHeight / c.height,
            i._xSize = this.cellWidth,
            i._ySize = this.cellHeight
        }
        this._vertexData[b] = i.position.x,
        this._vertexData[b + 1] = i.position.y,
        this._vertexData[b + 2] = i.position.z,
        this._vertexData[b + 3] = i.angle,
        this._vertexData[b + 4] = i.width,
        this._vertexData[b + 5] = i.height,
        this._useInstancing ? b -= 2 : (this._vertexData[b + 6] = o,
        this._vertexData[b + 7] = s),
        d ? this._vertexData[b + 8] = i.invertU ? 0 : 1 : this._vertexData[b + 8] = i.invertU ? 1 : 0,
        this._vertexData[b + 9] = i.invertV ? 1 : 0,
        this._vertexData[b + 10] = i._xOffset,
        this._vertexData[b + 11] = i._yOffset,
        this._vertexData[b + 12] = i._xSize / c.width,
        this._vertexData[b + 13] = i._ySize / c.height,
        this._vertexData[b + 14] = i.color.r,
        this._vertexData[b + 15] = i.color.g,
        this._vertexData[b + 16] = i.color.b,
        this._vertexData[b + 17] = i.color.a
    }
    ,
    a.prototype._buildIndexBuffer = function() {
        for (var e = [], i = 0, o = 0; o < this._capacity; o++)
            e.push(i),
            e.push(i + 1),
            e.push(i + 2),
            e.push(i),
            e.push(i + 2),
            e.push(i + 3),
            i += 4;
        this._indexBuffer = this._engine.createIndexBuffer(e)
    }
    ,
    a.prototype.rebuild = function() {
        var e;
        this._indexBuffer && this._buildIndexBuffer(),
        this._useVAO && (this._vertexArrayObject = void 0),
        this._buffer._rebuild();
        for (var i in this._vertexBuffers) {
            var o = this._vertexBuffers[i];
            o._rebuild()
        }
        (e = this._spriteBuffer) === null || e === void 0 || e._rebuild()
    }
    ,
    a.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()
    }
    ,
    a
}()
  , SpriteManager = function() {
    function a(e, i, o, s, c, d, _, b, k) {
        var j = this;
        d === void 0 && (d = .01),
        _ === void 0 && (_ = Texture.TRILINEAR_SAMPLINGMODE),
        b === void 0 && (b = !1),
        k === void 0 && (k = 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(_e, et) {
            _e.cellRef || (_e.cellIndex = 0);
            var tt = _e.cellIndex;
            typeof tt == "number" && isFinite(tt) && Math.floor(tt) === tt && (_e.cellRef = j._spriteMap[_e.cellIndex]),
            _e._xOffset = j._cellData[_e.cellRef].frame.x / et.width,
            _e._yOffset = j._cellData[_e.cellRef].frame.y / et.height,
            _e._xSize = j._cellData[_e.cellRef].frame.w,
            _e._ySize = j._cellData[_e.cellRef].frame.h
        }
        ,
        c || (c = Engine.LastCreatedScene),
        c._getComponent(SceneComponentConstants.NAME_SPRITE) || c._addComponent(new SpriteSceneComponent(c)),
        this._fromPacked = b,
        this._scene = c;
        var $ = this._scene.getEngine();
        if (this._spriteRenderer = new SpriteRenderer($,o,d,c),
        s.width && s.height)
            this.cellWidth = s.width,
            this.cellHeight = s.height;
        else if (s !== void 0)
            this.cellWidth = s,
            this.cellHeight = s;
        else {
            this._spriteRenderer = null;
            return
        }
        this._scene.spriteManagers.push(this),
        this.uniqueId = this.scene.getUniqueId(),
        i && (this.texture = new Texture(i,c,!0,!1,_)),
        this._fromPacked && this._makePacked(i, k)
    }
    return Object.defineProperty(a.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "children", {
        get: function() {
            return this.sprites
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "scene", {
        get: function() {
            return this._scene
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "capacity", {
        get: function() {
            return this._spriteRenderer.capacity
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "cellWidth", {
        get: function() {
            return this._spriteRenderer.cellWidth
        },
        set: function(e) {
            this._spriteRenderer.cellWidth = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "cellHeight", {
        get: function() {
            return this._spriteRenderer.cellHeight
        },
        set: function(e) {
            this._spriteRenderer.cellHeight = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "fogEnabled", {
        get: function() {
            return this._spriteRenderer.fogEnabled
        },
        set: function(e) {
            this._spriteRenderer.fogEnabled = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "blendMode", {
        get: function() {
            return this._spriteRenderer.blendMode
        },
        set: function(e) {
            this._spriteRenderer.blendMode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "disableDepthWrite", {
        get: function() {
            return this._disableDepthWrite
        },
        set: function(e) {
            this._disableDepthWrite = e,
            this._spriteRenderer.disableDepthWrite = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getClassName = function() {
        return "SpriteManager"
    }
    ,
    a.prototype._makePacked = function(e, i) {
        var o = this;
        if (i !== null)
            try {
                var s = void 0;
                if (typeof i == "string" ? s = JSON.parse(i) : s = i,
                s.frames.length) {
                    for (var c = {}, d = 0; d < s.frames.length; d++) {
                        var _ = s.frames[d];
                        if (typeof Object.keys(_)[0] != "string")
                            throw new Error("Invalid JSON Format.  Check the frame values and make sure the name is the first parameter.");
                        var b = _[Object.keys(_)[0]];
                        c[b] = _
                    }
                    s.frames = c
                }
                var k = Reflect.ownKeys(s.frames);
                this._spriteMap = k,
                this._packedAndReady = !0,
                this._cellData = s.frames
            } catch {
                throw this._fromPacked = !1,
                this._packedAndReady = !1,
                new Error("Invalid JSON from string. Spritesheet managed with constant cell size.")
            }
        else {
            var j = /\./g
              , $ = void 0;
            do
                $ = j.lastIndex,
                j.test(e);
            while (j.lastIndex > 0);
            var _e = e.substring(0, $ - 1) + ".json"
              , et = new XMLHttpRequest;
            et.open("GET", _e, !0),
            et.onerror = function() {
                Logger$2.Error("JSON ERROR: Unable to load JSON file."),
                o._fromPacked = !1,
                o._packedAndReady = !1
            }
            ,
            et.onload = function() {
                try {
                    var tt = JSON.parse(et.response)
                      , rt = Reflect.ownKeys(tt.frames);
                    o._spriteMap = rt,
                    o._packedAndReady = !0,
                    o._cellData = tt.frames
                } catch {
                    throw o._fromPacked = !1,
                    o._packedAndReady = !1,
                    new Error("Invalid JSON format. Please check documentation for format specifications.")
                }
            }
            ,
            et.send()
        }
    }
    ,
    a.prototype._checkTextureAlpha = function(e, i, o, s, c) {
        if (!e.useAlphaForPicking || !this.texture)
            return !0;
        var d = this.texture.getSize();
        this._textureContent || (this._textureContent = new Uint8Array(d.width * d.height * 4),
        this.texture.readPixels(0, 0, this._textureContent));
        var _ = TmpVectors.Vector3[0];
        _.copyFrom(i.direction),
        _.normalize(),
        _.scaleInPlace(o),
        _.addInPlace(i.origin);
        var b = (_.x - s.x) / (c.x - s.x) - .5
          , k = 1 - (_.y - s.y) / (c.y - s.y) - .5
          , j = e.angle
          , $ = .5 + (b * Math.cos(j) - k * Math.sin(j))
          , _e = .5 + (b * Math.sin(j) + k * Math.cos(j))
          , et = e._xOffset * d.width + $ * e._xSize | 0
          , tt = e._yOffset * d.height + _e * e._ySize | 0
          , rt = this._textureContent[(et + tt * d.width) * 4 + 3];
        return rt > .5
    }
    ,
    a.prototype.intersects = function(e, i, o, s) {
        for (var c = Math.min(this.capacity, this.sprites.length), d = Vector3.Zero(), _ = Vector3.Zero(), b = Number.MAX_VALUE, k = null, j = TmpVectors.Vector3[0], $ = TmpVectors.Vector3[1], _e = i.getViewMatrix(), et = e, tt = e, rt = 0; rt < c; rt++) {
            var it = this.sprites[rt];
            if (!!it) {
                if (o) {
                    if (!o(it))
                        continue
                } else if (!it.isPickable)
                    continue;
                if (Vector3.TransformCoordinatesToRef(it.position, _e, $),
                it.angle ? (Matrix.TranslationToRef(-$.x, -$.y, 0, TmpVectors.Matrix[1]),
                Matrix.TranslationToRef($.x, $.y, 0, TmpVectors.Matrix[2]),
                Matrix.RotationZToRef(it.angle, TmpVectors.Matrix[3]),
                TmpVectors.Matrix[1].multiplyToRef(TmpVectors.Matrix[3], TmpVectors.Matrix[4]),
                TmpVectors.Matrix[4].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[0]),
                et = e.clone(),
                Vector3.TransformCoordinatesToRef(e.origin, TmpVectors.Matrix[0], et.origin),
                Vector3.TransformNormalToRef(e.direction, TmpVectors.Matrix[0], et.direction)) : et = e,
                d.copyFromFloats($.x - it.width / 2, $.y - it.height / 2, $.z),
                _.copyFromFloats($.x + it.width / 2, $.y + it.height / 2, $.z),
                et.intersectsBoxMinMax(d, _)) {
                    var nt = Vector3.Distance($, et.origin);
                    if (b > nt) {
                        if (!this._checkTextureAlpha(it, et, nt, d, _))
                            continue;
                        if (tt = et,
                        b = nt,
                        k = it,
                        s)
                            break
                    }
                }
            }
        }
        if (k) {
            var ot = new PickingInfo;
            _e.invertToRef(TmpVectors.Matrix[0]),
            ot.hit = !0,
            ot.pickedSprite = k,
            ot.distance = b;
            var at = TmpVectors.Vector3[2];
            return at.copyFrom(tt.direction),
            at.normalize(),
            at.scaleInPlace(b),
            tt.origin.addToRef(at, j),
            ot.pickedPoint = Vector3.TransformCoordinates(j, TmpVectors.Matrix[0]),
            ot
        }
        return null
    }
    ,
    a.prototype.multiIntersects = function(e, i, o) {
        for (var s = Math.min(this.capacity, this.sprites.length), c = Vector3.Zero(), d = Vector3.Zero(), _, b = [], k = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0), j = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0), $ = i.getViewMatrix(), _e = 0; _e < s; _e++) {
            var et = this.sprites[_e];
            if (!!et) {
                if (o) {
                    if (!o(et))
                        continue
                } else if (!et.isPickable)
                    continue;
                if (Vector3.TransformCoordinatesToRef(et.position, $, j),
                c.copyFromFloats(j.x - et.width / 2, j.y - et.height / 2, j.z),
                d.copyFromFloats(j.x + et.width / 2, j.y + et.height / 2, j.z),
                e.intersectsBoxMinMax(c, d)) {
                    if (_ = Vector3.Distance(j, e.origin),
                    !this._checkTextureAlpha(et, e, _, c, d))
                        continue;
                    var tt = new PickingInfo;
                    b.push(tt),
                    $.invertToRef(TmpVectors.Matrix[0]),
                    tt.hit = !0,
                    tt.pickedSprite = et,
                    tt.distance = _;
                    var rt = TmpVectors.Vector3[2];
                    rt.copyFrom(e.direction),
                    rt.normalize(),
                    rt.scaleInPlace(_),
                    e.origin.addToRef(rt, k),
                    tt.pickedPoint = Vector3.TransformCoordinates(k, TmpVectors.Matrix[0])
                }
            }
        }
        return b
    }
    ,
    a.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())
        }
    }
    ,
    a.prototype.rebuild = function() {
        var e;
        (e = this._spriteRenderer) === null || e === void 0 || e.rebuild()
    }
    ,
    a.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()
    }
    ,
    a.prototype.serialize = function(e) {
        e === void 0 && (e = !1);
        var i = {};
        i.name = this.name,
        i.capacity = this.capacity,
        i.cellWidth = this.cellWidth,
        i.cellHeight = this.cellHeight,
        this.texture && (e ? i.texture = this.texture.serialize() : (i.textureUrl = this.texture.name,
        i.invertY = this.texture._invertY)),
        i.sprites = [];
        for (var o = 0, s = this.sprites; o < s.length; o++) {
            var c = s[o];
            i.sprites.push(c.serialize())
        }
        return i
    }
    ,
    a.Parse = function(e, i, o) {
        var s = new a(e.name,"",e.capacity,{
            width: e.cellWidth,
            height: e.cellHeight
        },i);
        e.texture ? s.texture = Texture.Parse(e.texture, i, o) : e.textureName && (s.texture = new Texture(o + e.textureUrl,i,!1,e.invertY !== void 0 ? e.invertY : !0));
        for (var c = 0, d = e.sprites; c < d.length; c++) {
            var _ = d[c];
            Sprite.Parse(_, s)
        }
        return s
    }
    ,
    a.ParseFromFileAsync = function(e, i, o, s) {
        return s === void 0 && (s = ""),
        new Promise(function(c, d) {
            var _ = new WebRequest;
            _.addEventListener("readystatechange", function() {
                if (_.readyState == 4)
                    if (_.status == 200) {
                        var b = JSON.parse(_.responseText)
                          , k = a.Parse(b, o || Engine.LastCreatedScene, s);
                        e && (k.name = e),
                        c(k)
                    } else
                        d("Unable to load the sprite manager")
            }),
            _.open("GET", i),
            _.send()
        }
        )
    }
    ,
    a.CreateFromSnippetAsync = function(e, i, o) {
        var s = this;
        return o === void 0 && (o = ""),
        e === "_BLANK" ? Promise.resolve(new a("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,i)) : new Promise(function(c, d) {
            var _ = new WebRequest;
            _.addEventListener("readystatechange", function() {
                if (_.readyState == 4)
                    if (_.status == 200) {
                        var b = JSON.parse(JSON.parse(_.responseText).jsonPayload)
                          , k = JSON.parse(b.spriteManager)
                          , j = a.Parse(k, i || Engine.LastCreatedScene, o);
                        j.snippetId = e,
                        c(j)
                    } else
                        d("Unable to load the snippet " + e)
            }),
            _.open("GET", s.SnippetUrl + "/" + e.replace(/#/g, "/")),
            _.send()
        }
        )
    }
    ,
    a.SnippetUrl = "https://snippet.babylonjs.com",
    a
}()
  , UtilityLayerRenderer = function() {
    function a(e, i) {
        var o = this;
        i === void 0 && (i = !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(),
        i && (this._originalPointerObserver = e.onPrePointerObservable.add(function(s, c) {
            if (!!o.utilityLayerScene.activeCamera && !!o.pickingEnabled && !(!o.processAllEvents && s.type !== PointerEventTypes.POINTERMOVE && s.type !== PointerEventTypes.POINTERUP && s.type !== PointerEventTypes.POINTERDOWN && s.type !== PointerEventTypes.POINTERDOUBLETAP)) {
                o.utilityLayerScene.pointerX = e.pointerX,
                o.utilityLayerScene.pointerY = e.pointerY;
                var d = s.event;
                if (e.isPointerCaptured(d.pointerId)) {
                    o._pointerCaptures[d.pointerId] = !1;
                    return
                }
                var _ = function($) {
                    var _e = null;
                    if (s.nearInteractionPickingInfo)
                        s.nearInteractionPickingInfo.pickedMesh.getScene() == $ ? _e = s.nearInteractionPickingInfo : _e = new PickingInfo;
                    else {
                        var et = null;
                        o._renderCamera && (et = $._activeCamera,
                        $._activeCamera = o._renderCamera,
                        s.ray = null),
                        _e = s.ray ? $.pickWithRay(s.ray) : $.pick(e.pointerX, e.pointerY),
                        et && ($._activeCamera = et)
                    }
                    return _e
                }
                  , b = _(o.utilityLayerScene);
                if (!s.ray && b && (s.ray = b.ray),
                o.utilityLayerScene.onPrePointerObservable.notifyObservers(s),
                o.onlyCheckPointerDownEvents && s.type != PointerEventTypes.POINTERDOWN) {
                    s.skipOnPointerObservable || o.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(s.type,s.event,b), s.type),
                    s.type === PointerEventTypes.POINTERUP && o._pointerCaptures[d.pointerId] && (o._pointerCaptures[d.pointerId] = !1);
                    return
                }
                if (o.utilityLayerScene.autoClearDepthAndStencil || o.pickUtilitySceneFirst)
                    b && b.hit && (s.skipOnPointerObservable || o.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(s.type,s.event,b), s.type),
                    s.skipOnPointerObservable = !0);
                else {
                    var k = _(e)
                      , j = s.event;
                    k && b && (b.distance === 0 && k.pickedMesh ? o.mainSceneTrackerPredicate && o.mainSceneTrackerPredicate(k.pickedMesh) ? (o._notifyObservers(s, k, j),
                    s.skipOnPointerObservable = !0) : s.type === PointerEventTypes.POINTERDOWN ? o._pointerCaptures[j.pointerId] = !0 : (s.type === PointerEventTypes.POINTERMOVE || s.type === PointerEventTypes.POINTERUP) && (o._lastPointerEvents[j.pointerId] && (o.onPointerOutObservable.notifyObservers(j.pointerId),
                    delete o._lastPointerEvents[j.pointerId]),
                    o._notifyObservers(s, k, j)) : !o._pointerCaptures[j.pointerId] && (b.distance < k.distance || k.distance === 0) ? (o._notifyObservers(s, b, j),
                    s.skipOnPointerObservable || (s.skipOnPointerObservable = b.distance > 0)) : !o._pointerCaptures[j.pointerId] && b.distance > k.distance && (o.mainSceneTrackerPredicate && o.mainSceneTrackerPredicate(k.pickedMesh) ? (o._notifyObservers(s, k, j),
                    s.skipOnPointerObservable = !0) : (s.type === PointerEventTypes.POINTERMOVE || s.type === PointerEventTypes.POINTERUP) && (o._lastPointerEvents[j.pointerId] && (o.onPointerOutObservable.notifyObservers(j.pointerId),
                    delete o._lastPointerEvents[j.pointerId]),
                    o._notifyObservers(s, b, j))),
                    s.type === PointerEventTypes.POINTERUP && o._pointerCaptures[j.pointerId] && (o._pointerCaptures[j.pointerId] = !1))
                }
            }
        }),
        this._originalPointerObserver && e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),
        this.utilityLayerScene.autoClear = !1,
        this._afterRenderObserver = this.originalScene.onAfterCameraRenderObservable.add(function(s) {
            o.shouldRender && s == o.getRenderCamera() && o.render()
        }),
        this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function() {
            o.dispose()
        }),
        this._updateCamera()
    }
    return a.prototype.getRenderCamera = function(e) {
        if (this._renderCamera)
            return this._renderCamera;
        var i = void 0;
        return this.originalScene.activeCameras && this.originalScene.activeCameras.length > 1 ? i = this.originalScene.activeCameras[this.originalScene.activeCameras.length - 1] : i = this.originalScene.activeCamera,
        e && i && i.isRigCamera ? i.rigParent : i
    }
    ,
    a.prototype.setRenderCamera = function(e) {
        this._renderCamera = e
    }
    ,
    a.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(a, "DefaultUtilityLayer", {
        get: function() {
            return a._DefaultUtilityLayer == null ? a._CreateDefaultUtilityLayerFromScene(EngineStore.LastCreatedScene) : a._DefaultUtilityLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    a._CreateDefaultUtilityLayerFromScene = function(e) {
        return a._DefaultUtilityLayer = new a(e),
        a._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function() {
            a._DefaultUtilityLayer = null
        }),
        a._DefaultUtilityLayer
    }
    ,
    Object.defineProperty(a, "DefaultKeepDepthUtilityLayer", {
        get: function() {
            return a._DefaultKeepDepthUtilityLayer == null && (a._DefaultKeepDepthUtilityLayer = new a(EngineStore.LastCreatedScene),
            a._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = !1,
            a._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function() {
                a._DefaultKeepDepthUtilityLayer = null
            })),
            a._DefaultKeepDepthUtilityLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._notifyObservers = function(e, i, o) {
        e.skipOnPointerObservable || (this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(e.type,e.event,i), e.type),
        this._lastPointerEvents[o.pointerId] = !0)
    }
    ,
    a.prototype.render = function() {
        if (this._updateCamera(),
        this.utilityLayerScene.activeCamera) {
            var e = this.utilityLayerScene.activeCamera.getScene()
              , i = this.utilityLayerScene.activeCamera;
            i._scene = this.utilityLayerScene,
            i.leftCamera && (i.leftCamera._scene = this.utilityLayerScene),
            i.rightCamera && (i.rightCamera._scene = this.utilityLayerScene),
            this.utilityLayerScene.render(!1),
            i._scene = e,
            i.leftCamera && (i.leftCamera._scene = e),
            i.rightCamera && (i.rightCamera._scene = e)
        }
    }
    ,
    a.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()
    }
    ,
    a.prototype._updateCamera = function() {
        this.utilityLayerScene.cameraToUseForPointers = this.getRenderCamera(),
        this.utilityLayerScene.activeCamera = this.getRenderCamera()
    }
    ,
    a._DefaultUtilityLayer = null,
    a._DefaultKeepDepthUtilityLayer = null,
    a
}()
  , BaseSixDofDragBehavior = function() {
    function a() {
        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(a.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(a.prototype, "currentDraggingPointerID", {
        get: function() {
            return this.currentDraggingPointerId
        },
        set: function(e) {
            this.currentDraggingPointerId = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "name", {
        get: function() {
            return "BaseSixDofDrag"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isMoving", {
        get: function() {
            return this._moving
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.init = function() {}
    ,
    Object.defineProperty(a.prototype, "_pointerCamera", {
        get: function() {
            return this._scene.cameraToUseForPointers ? this._scene.cameraToUseForPointers : this._scene.activeCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._createVirtualMeshInfo = function() {
        var e = new AbstractMesh("",a._virtualScene);
        e.rotationQuaternion = new Quaternion;
        var i = new AbstractMesh("",a._virtualScene);
        i.rotationQuaternion = new Quaternion;
        var o = new AbstractMesh("",a._virtualScene);
        return o.rotationQuaternion = new Quaternion,
        {
            dragging: !1,
            moving: !1,
            dragMesh: e,
            originMesh: i,
            pivotMesh: o,
            startingPivotPosition: new Vector3,
            startingPivotOrientation: new Quaternion,
            startingPosition: new Vector3,
            startingOrientation: new Quaternion,
            lastOriginPosition: new Vector3,
            lastDragPosition: new Vector3
        }
    }
    ,
    a.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)
    }
    ,
    a.prototype._pointerUpdate2D = function(e, i, o) {
        this._pointerCamera && this._pointerCamera.cameraRigMode == Camera$1.RIG_MODE_NONE && !this._pointerCamera._isLeftCamera && !this._pointerCamera._isRightCamera && (e.origin.copyFrom(this._pointerCamera.globalPosition),
        o = 0);
        var s = this._virtualMeshesInfo[i]
          , c = TmpVectors.Vector3[0];
        e.origin.subtractToRef(s.lastOriginPosition, c),
        s.lastOriginPosition.copyFrom(e.origin);
        var d = -Vector3.Dot(c, e.direction);
        s.originMesh.addChild(s.dragMesh),
        s.originMesh.addChild(s.pivotMesh),
        this._applyZOffset(s.dragMesh, d, o),
        this._applyZOffset(s.pivotMesh, d, o),
        s.originMesh.position.copyFrom(e.origin);
        var _ = TmpVectors.Vector3[0];
        e.origin.addToRef(e.direction, _),
        s.originMesh.lookAt(_),
        s.originMesh.removeChild(s.dragMesh),
        s.originMesh.removeChild(s.pivotMesh)
    }
    ,
    a.prototype._pointerUpdateXR = function(e, i, o, s) {
        var c = this._virtualMeshesInfo[o];
        c.originMesh.position.copyFrom(e.position),
        this._dragging === this._dragType.NEAR_DRAG && i ? c.originMesh.rotationQuaternion.copyFrom(i.rotationQuaternion) : c.originMesh.rotationQuaternion.copyFrom(e.rotationQuaternion);
        var d = TmpVectors.Vector3[0]
          , _ = TmpVectors.Vector3[1];
        d.copyFrom(this._pointerCamera.getForwardRay().direction),
        c.originMesh.position.subtractToRef(c.lastOriginPosition, _),
        c.lastOriginPosition.copyFrom(c.originMesh.position);
        var b = _.length();
        _.normalize(),
        c.pivotMesh.computeWorldMatrix(!0),
        c.dragMesh.computeWorldMatrix(!0);
        var k = TmpVectors.Vector3[2]
          , j = TmpVectors.Vector3[3];
        c.dragMesh.absolutePosition.subtractToRef(this._pointerCamera.globalPosition, k),
        c.dragMesh.absolutePosition.subtractToRef(c.originMesh.position, j);
        var $ = j.length();
        k.normalize(),
        j.normalize();
        var _e = Math.abs(Vector3.Dot(_, j)) * Vector3.Dot(_, d)
          , et = _e * s * b * $;
        et + $ < .1 && (et = Math.min($, .1)),
        j.scaleInPlace(et),
        j.addToRef(c.pivotMesh.absolutePosition, this._tmpVector),
        c.pivotMesh.setAbsolutePosition(this._tmpVector),
        j.addToRef(c.dragMesh.absolutePosition, this._tmpVector),
        c.dragMesh.setAbsolutePosition(this._tmpVector)
    }
    ,
    a.prototype.attach = function(e) {
        var i = this;
        this._ownerNode = e,
        this._scene = this._ownerNode.getScene(),
        a._virtualScene || (a._virtualScene = new Scene(this._scene.getEngine(),{
            virtual: !0
        }),
        a._virtualScene.detachControl());
        var o = function(s) {
            return i._ownerNode === s || s.isDescendantOf(i._ownerNode) && (!i.draggableMeshes || i.draggableMeshes.indexOf(s) !== -1)
        };
        this._pointerObserver = this._scene.onPointerObservable.add(function(s, c) {
            var d = s.event.pointerId;
            i._virtualMeshesInfo[d] || (i._virtualMeshesInfo[d] = i._createVirtualMeshInfo());
            var _ = i._virtualMeshesInfo[d]
              , b = s.event.pointerType === "xr";
            if (s.type == PointerEventTypes.POINTERDOWN) {
                if (!_.dragging && s.pickInfo && s.pickInfo.hit && s.pickInfo.pickedMesh && s.pickInfo.pickedPoint && s.pickInfo.ray && (!b || s.pickInfo.aimTransform) && o(s.pickInfo.pickedMesh)) {
                    if (!i.allowMultiPointer && i.currentDraggingPointerIds.length > 0)
                        return;
                    i._pointerCamera && i._pointerCamera.cameraRigMode === Camera$1.RIG_MODE_NONE && !i._pointerCamera._isLeftCamera && !i._pointerCamera._isRightCamera && s.pickInfo.ray.origin.copyFrom(i._pointerCamera.globalPosition),
                    i._ownerNode.computeWorldMatrix(!0);
                    var k = i._virtualMeshesInfo[d];
                    b ? (i._dragging = s.pickInfo.originMesh ? i._dragType.NEAR_DRAG : i._dragType.DRAG_WITH_CONTROLLER,
                    k.originMesh.position.copyFrom(s.pickInfo.aimTransform.position),
                    i._dragging === i._dragType.NEAR_DRAG && s.pickInfo.gripTransform ? k.originMesh.rotationQuaternion.copyFrom(s.pickInfo.gripTransform.rotationQuaternion) : k.originMesh.rotationQuaternion.copyFrom(s.pickInfo.aimTransform.rotationQuaternion)) : (i._dragging = i._dragType.DRAG,
                    k.originMesh.position.copyFrom(s.pickInfo.ray.origin)),
                    k.lastOriginPosition.copyFrom(k.originMesh.position),
                    k.dragMesh.position.copyFrom(s.pickInfo.pickedPoint),
                    k.lastDragPosition.copyFrom(s.pickInfo.pickedPoint),
                    k.pivotMesh.position.copyFrom(i._ownerNode.getAbsolutePivotPoint()),
                    k.pivotMesh.rotationQuaternion.copyFrom(i._ownerNode.absoluteRotationQuaternion),
                    k.startingPosition.copyFrom(k.dragMesh.position),
                    k.startingPivotPosition.copyFrom(k.pivotMesh.position),
                    k.startingOrientation.copyFrom(k.dragMesh.rotationQuaternion),
                    k.startingPivotOrientation.copyFrom(k.pivotMesh.rotationQuaternion),
                    b ? (k.originMesh.addChild(k.dragMesh),
                    k.originMesh.addChild(k.pivotMesh)) : k.originMesh.lookAt(k.dragMesh.position),
                    k.dragging = !0,
                    i.currentDraggingPointerIds.indexOf(d) === -1 && i.currentDraggingPointerIds.push(d),
                    i.detachCameraControls && i._pointerCamera && !i._pointerCamera.leftCamera && (i._pointerCamera.inputs && i._pointerCamera.inputs.attachedToElement ? (i._pointerCamera.detachControl(),
                    i._attachedToElement = !0) : i._attachedToElement = !1),
                    i._targetDragStart(k.pivotMesh.position, k.pivotMesh.rotationQuaternion, d),
                    i.onDragStartObservable.notifyObservers({
                        position: k.pivotMesh.position
                    })
                }
            } else if (s.type == PointerEventTypes.POINTERUP || s.type == PointerEventTypes.POINTERDOUBLETAP) {
                var j = i.currentDraggingPointerIds.indexOf(d);
                _.dragging = !1,
                j !== -1 && (i.currentDraggingPointerIds.splice(j, 1),
                i.currentDraggingPointerIds.length === 0 && (i._moving = !1,
                i._dragging = i._dragType.NONE,
                i.detachCameraControls && i._attachedToElement && i._pointerCamera && !i._pointerCamera.leftCamera && (i._pointerCamera.attachControl(!0),
                i._attachedToElement = !1)),
                _.originMesh.removeChild(_.dragMesh),
                _.originMesh.removeChild(_.pivotMesh),
                i._targetDragEnd(d),
                i.onDragEndObservable.notifyObservers({}))
            } else if (s.type == PointerEventTypes.POINTERMOVE) {
                var j = i.currentDraggingPointerIds.indexOf(d);
                if (j !== -1 && _.dragging && s.pickInfo && (s.pickInfo.ray || s.pickInfo.aimTransform)) {
                    var $ = i.zDragFactor;
                    (i.currentDraggingPointerIds.length > 1 || s.pickInfo.originMesh) && ($ = 0),
                    i._ownerNode.computeWorldMatrix(!0),
                    b ? i._pointerUpdateXR(s.pickInfo.aimTransform, s.pickInfo.gripTransform, d, $) : i._pointerUpdate2D(s.pickInfo.ray, d, $),
                    i._tmpQuaternion.copyFrom(_.startingPivotOrientation),
                    i._tmpQuaternion.x = -i._tmpQuaternion.x,
                    i._tmpQuaternion.y = -i._tmpQuaternion.y,
                    i._tmpQuaternion.z = -i._tmpQuaternion.z,
                    _.pivotMesh.absoluteRotationQuaternion.multiplyToRef(i._tmpQuaternion, i._tmpQuaternion),
                    _.pivotMesh.absolutePosition.subtractToRef(_.startingPivotPosition, i._tmpVector),
                    i.onDragObservable.notifyObservers({
                        delta: i._tmpVector,
                        position: _.pivotMesh.position,
                        pickInfo: s.pickInfo
                    }),
                    i._targetDrag(i._tmpVector, i._tmpQuaternion, d),
                    _.lastDragPosition.copyFrom(_.dragMesh.absolutePosition),
                    i._moving = !0
                }
            }
        })
    }
    ,
    a.prototype._applyZOffset = function(e, i, o) {
        e.position.z -= e.position.z < 1 ? i * o : i * o * e.position.z,
        e.position.z < 0 && (e.position.z = 0)
    }
    ,
    a.prototype._targetDragStart = function(e, i, o) {}
    ,
    a.prototype._targetDrag = function(e, i, o) {}
    ,
    a.prototype._targetDragEnd = function(e) {}
    ,
    a.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()
    }
    ,
    a
}()
  , SixDofDragBehavior = function(a) {
    __extends(e, a);
    function e() {
        var i = a !== null && a.apply(this, arguments) || this;
        return i._sceneRenderObserver = null,
        i._targetPosition = new Vector3(0,0,0),
        i._targetOrientation = new Quaternion,
        i._targetScaling = new Vector3(1,1,1),
        i._startingPosition = new Vector3(0,0,0),
        i._startingOrientation = new Quaternion,
        i._startingScaling = new Vector3(1,1,1),
        i.onPositionChangedObservable = new Observable,
        i.dragDeltaRatio = .2,
        i.rotateDraggedObject = !0,
        i.rotateAroundYOnly = !1,
        i.rotateWithMotionController = !0,
        i.disableMovement = !1,
        i.faceCameraOnDragStart = !1,
        i
    }
    return Object.defineProperty(e.prototype, "name", {
        get: function() {
            return "SixDofDrag"
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.attach = function(i) {
        var o = this;
        a.prototype.attach.call(this, i),
        i.isNearGrabbable = !0,
        this._virtualTransformNode = new TransformNode("virtual_sixDof",BaseSixDofDragBehavior._virtualScene),
        this._virtualTransformNode.rotationQuaternion = Quaternion.Identity(),
        this._sceneRenderObserver = i.getScene().onBeforeRenderObservable.add(function() {
            if (o.currentDraggingPointerIds.length === 1 && o._moving && !o.disableMovement) {
                var s = i.parent;
                i.setParent(null),
                i.position.addInPlace(o._targetPosition.subtract(i.position).scale(o.dragDeltaRatio)),
                o.onPositionChangedObservable.notifyObservers({
                    position: i.absolutePosition
                }),
                (!s || s.scaling && !s.scaling.isNonUniformWithinEpsilon(.001)) && Quaternion.SlerpToRef(i.rotationQuaternion, o._targetOrientation, o.dragDeltaRatio, i.rotationQuaternion),
                i.setParent(s)
            }
        })
    }
    ,
    e.prototype._getPositionOffsetAround = function(i, o, s) {
        var c = TmpVectors.Matrix[0]
          , d = TmpVectors.Matrix[1]
          , _ = TmpVectors.Matrix[2]
          , b = TmpVectors.Matrix[3]
          , k = TmpVectors.Matrix[4];
        return Matrix.TranslationToRef(i.x, i.y, i.z, c),
        Matrix.TranslationToRef(-i.x, -i.y, -i.z, d),
        Matrix.FromQuaternionToRef(s, _),
        Matrix.ScalingToRef(o, o, o, b),
        d.multiplyToRef(_, k),
        k.multiplyToRef(b, k),
        k.multiplyToRef(c, k),
        k.getTranslation()
    }
    ,
    e.prototype._onePointerPositionUpdated = function(i, o) {
        var s = TmpVectors.Vector3[0];
        s.setAll(0),
        this._dragging === this._dragType.DRAG ? this.rotateDraggedObject && (this.rotateAroundYOnly ? Quaternion.RotationYawPitchRollToRef(o.toEulerAngles().y, 0, 0, TmpVectors.Quaternion[0]) : TmpVectors.Quaternion[0].copyFrom(o),
        TmpVectors.Quaternion[0].multiplyToRef(this._startingOrientation, this._targetOrientation)) : (this._dragging === this._dragType.NEAR_DRAG || this._dragging === this._dragType.DRAG_WITH_CONTROLLER && this.rotateWithMotionController) && o.multiplyToRef(this._startingOrientation, this._targetOrientation),
        this._targetPosition.copyFrom(this._startingPosition).addInPlace(i)
    }
    ,
    e.prototype._twoPointersPositionUpdated = function() {
        var i = this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition
          , o = this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition
          , s = TmpVectors.Vector3[0];
        i.addToRef(o, s),
        s.scaleInPlace(.5);
        var c = TmpVectors.Vector3[1];
        o.subtractToRef(i, c);
        var d = this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition
          , _ = this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition
          , b = TmpVectors.Vector3[2];
        d.addToRef(_, b),
        b.scaleInPlace(.5);
        var k = TmpVectors.Vector3[3];
        _.subtractToRef(d, k);
        var j = k.length() / c.length()
          , $ = b.subtract(s)
          , _e = Quaternion.FromEulerAngles(0, Vector3.GetAngleBetweenVectorsOnPlane(c.normalize(), k.normalize(), Vector3.UpReadOnly), 0)
          , et = this._ownerNode.parent;
        this._ownerNode.setParent(null);
        var tt = this._getPositionOffsetAround(s.subtract(this._virtualTransformNode.getAbsolutePivotPoint()), j, _e);
        this._virtualTransformNode.rotationQuaternion.multiplyToRef(_e, this._ownerNode.rotationQuaternion),
        this._virtualTransformNode.scaling.scaleToRef(j, this._ownerNode.scaling),
        this._virtualTransformNode.position.addToRef($.addInPlace(tt), this._ownerNode.position),
        this.onPositionChangedObservable.notifyObservers({
            position: this._ownerNode.position
        }),
        this._ownerNode.setParent(et)
    }
    ,
    e.prototype._targetDragStart = function() {
        var i = this.currentDraggingPointerIds.length
          , o = this._ownerNode.parent;
        this._ownerNode.rotationQuaternion || (this._ownerNode.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._ownerNode.rotation.y, this._ownerNode.rotation.x, this._ownerNode.rotation.z));
        var s = this._ownerNode.getAbsolutePivotPoint();
        if (this._ownerNode.setParent(null),
        i === 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 c = TmpVectors.Vector3[0];
                this._scene.activeCamera.position.subtractToRef(s, c),
                c.normalize();
                var d = TmpVectors.Quaternion[0];
                this._scene.useRightHandedSystem ? Quaternion.FromLookDirectionRHToRef(c, new Vector3(0,1,0), d) : Quaternion.FromLookDirectionLHToRef(c, new Vector3(0,1,0), d),
                d.normalize(),
                Quaternion.RotationYawPitchRollToRef(d.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
            i === 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(s, Space.WORLD),
            this._resetVirtualMeshesPosition());
        this._ownerNode.setParent(o)
    }
    ,
    e.prototype._targetDrag = function(i, o, s) {
        this.currentDraggingPointerIds.length === 1 ? this._onePointerPositionUpdated(i, o) : this.currentDraggingPointerIds.length === 2 && this._twoPointersPositionUpdated()
    }
    ,
    e.prototype._targetDragEnd = function() {
        if (this.currentDraggingPointerIds.length === 1) {
            this._resetVirtualMeshesPosition();
            var i = this.faceCameraOnDragStart;
            this.faceCameraOnDragStart = !1,
            this._targetDragStart(),
            this.faceCameraOnDragStart = i
        }
    }
    ,
    e.prototype.detach = function() {
        a.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 a(e) {
        var i = 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() {
            i._update()
        })
    }
    return Object.defineProperty(a.prototype, "scaleRatio", {
        get: function() {
            return this._scaleRatio
        },
        set: function(e) {
            this._scaleRatio = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isHovered", {
        get: function() {
            return this._isHovered
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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
    }),
    a.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(i) {
            i.dispose()
        }),
        e.parent = this._rootMesh,
        this._customMeshSet = !0
    }
    ,
    Object.defineProperty(a.prototype, "updateGizmoRotationToMatchAttachedMesh", {
        get: function() {
            return this._updateGizmoRotationToMatchAttachedMesh
        },
        set: function(e) {
            this._updateGizmoRotationToMatchAttachedMesh = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._attachedNodeChanged = function(e) {}
    ,
    Object.defineProperty(a.prototype, "customRotationQuaternion", {
        get: function() {
            return this._customRotationQuaternion
        },
        set: function(e) {
            this._customRotationQuaternion = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._update = function() {
        if (this.attachedNode) {
            var e = this.attachedNode;
            if (this.attachedMesh && (e = this.attachedMesh._effectiveMesh || this.attachedNode),
            this.updateGizmoPositionToMatchAttachedMesh) {
                var i = e.getWorldMatrix().getRow(3)
                  , o = i ? i.toVector3() : new Vector3(0,0,0);
                this._rootMesh.position.copyFrom(o)
            }
            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 s = this.gizmoLayer.utilityLayerScene.activeCamera
                  , c = s.globalPosition;
                s.devicePosition && (c = s.devicePosition),
                this._rootMesh.position.subtractToRef(c, this._tempVector);
                var d = this._tempVector.length() * this.scaleRatio;
                this._rootMesh.scaling.set(d, d, d),
                e._getWorldMatrixDeterminant() < 0 && (this._rootMesh.scaling.y *= -1)
            } else
                this._rootMesh.scaling.setAll(this.scaleRatio)
        }
    }
    ,
    a.prototype._handlePivot = function() {
        var e = this._attachedNode;
        e.isUsingPivotMatrix && e.isUsingPivotMatrix() && e.position && e.getWorldMatrix().setTranslation(e.position)
    }
    ,
    a.prototype._matrixChanged = function() {
        if (!!this._attachedNode)
            if (this._attachedNode._isCamera) {
                var e = this._attachedNode, i, o;
                if (e.parent) {
                    var s = this._tempMatrix2;
                    e.parent._worldMatrix.invertToRef(s),
                    this._attachedNode._worldMatrix.multiplyToRef(s, this._tempMatrix1),
                    i = this._tempMatrix1
                } else
                    i = this._attachedNode._worldMatrix;
                e.getScene().useRightHandedSystem ? (this._rightHandtoLeftHandMatrix.multiplyToRef(i, this._tempMatrix2),
                o = this._tempMatrix2) : o = i,
                o.decompose(this._tempVector2, this._tempQuaternion, this._tempVector);
                var c = 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 (c) {
                    var d = this._attachedNode;
                    d.rotation = this._tempQuaternion.toEulerAngles(),
                    d.rotationQuaternion && (d.rotationQuaternion.copyFrom(this._tempQuaternion),
                    d.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 _ = this._attachedNode;
                if (_.parent) {
                    var s = this._tempMatrix1
                      , b = this._tempMatrix2;
                    _.parent.getWorldMatrix().invertToRef(s),
                    this._attachedNode.getWorldMatrix().multiplyToRef(s, b),
                    b.decompose(_.scaling, this._tempQuaternion, _.position)
                } else
                    this._attachedNode._worldMatrix.decompose(_.scaling, this._tempQuaternion, _.position);
                _.billboardMode || (_.rotationQuaternion ? (_.rotationQuaternion.copyFrom(this._tempQuaternion),
                _.rotationQuaternion.normalize()) : _.rotation = this._tempQuaternion.toEulerAngles())
            } else if (this._attachedNode.getClassName() === "Bone") {
                var k = this._attachedNode
                  , j = k.getParent();
                if (j) {
                    var $ = this._tempMatrix1
                      , _e = this._tempMatrix2;
                    j.getWorldMatrix().invertToRef($),
                    k.getWorldMatrix().multiplyToRef($, _e);
                    var et = k.getLocalMatrix();
                    et.copyFrom(_e)
                } else {
                    var et = k.getLocalMatrix();
                    et.copyFrom(k.getWorldMatrix())
                }
                k.markAsDirty()
            } else {
                var tt = this._attachedNode;
                if (tt.getTypeID) {
                    var rt = tt.getTypeID();
                    if (rt === Light.LIGHTTYPEID_DIRECTIONALLIGHT || rt === Light.LIGHTTYPEID_SPOTLIGHT || rt === Light.LIGHTTYPEID_POINTLIGHT) {
                        var it = tt.parent;
                        if (it) {
                            var $ = this._tempMatrix1
                              , nt = this._tempMatrix2;
                            it.getWorldMatrix().invertToRef($),
                            tt.getWorldMatrix().multiplyToRef($, nt),
                            nt.decompose(void 0, this._tempQuaternion, this._tempVector)
                        } else
                            this._attachedNode._worldMatrix.decompose(void 0, this._tempQuaternion, this._tempVector);
                        tt.position = new Vector3(this._tempVector.x,this._tempVector.y,this._tempVector.z),
                        Vector3.Backward(!1).rotateByQuaternionToRef(this._tempQuaternion, this._tempVector),
                        tt.direction = new Vector3(this._tempVector.x,this._tempVector.y,this._tempVector.z)
                    }
                }
            }
    }
    ,
    a.prototype._setGizmoMeshMaterial = function(e, i) {
        e && e.forEach(function(o) {
            o.material = i,
            o.color && (o.color = i.diffuseColor)
        })
    }
    ,
    a.GizmoAxisPointerObserver = function(e, i) {
        var o = !1
          , s = e.utilityLayerScene.onPointerObservable.add(function(c) {
            var d, _;
            if (c.pickInfo) {
                if (c.type === PointerEventTypes.POINTERMOVE) {
                    if (o)
                        return;
                    i.forEach(function(k) {
                        var j, $;
                        if (k.colliderMeshes && k.gizmoMeshes) {
                            var _e = ((j = k.colliderMeshes) === null || j === void 0 ? void 0 : j.indexOf(($ = c == null ? void 0 : c.pickInfo) === null || $ === void 0 ? void 0 : $.pickedMesh)) != -1
                              , et = k.dragBehavior.enabled ? _e || k.active ? k.hoverMaterial : k.material : k.disableMaterial;
                            k.gizmoMeshes.forEach(function(tt) {
                                tt.material = et,
                                tt.color && (tt.color = et.diffuseColor)
                            })
                        }
                    })
                }
                if (c.type === PointerEventTypes.POINTERDOWN && i.has((d = c.pickInfo.pickedMesh) === null || d === void 0 ? void 0 : d.parent)) {
                    o = !0;
                    var b = i.get((_ = c.pickInfo.pickedMesh) === null || _ === void 0 ? void 0 : _.parent);
                    b.active = !0,
                    i.forEach(function(k) {
                        var j, $, _e = ((j = k.colliderMeshes) === null || j === void 0 ? void 0 : j.indexOf(($ = c == null ? void 0 : c.pickInfo) === null || $ === void 0 ? void 0 : $.pickedMesh)) != -1, et = (_e || k.active) && k.dragBehavior.enabled ? k.hoverMaterial : k.disableMaterial;
                        k.gizmoMeshes.forEach(function(tt) {
                            tt.material = et,
                            tt.color && (tt.color = et.diffuseColor)
                        })
                    })
                }
                c.type === PointerEventTypes.POINTERUP && i.forEach(function(k) {
                    k.active = !1,
                    o = !1,
                    k.gizmoMeshes.forEach(function(j) {
                        j.material = k.dragBehavior.enabled ? k.material : k.disableMaterial,
                        j.color && (j.color = k.material.diffuseColor)
                    })
                })
            }
        });
        return s
    }
    ,
    a.prototype.dispose = function() {
        this._rootMesh.dispose(),
        this._beforeRenderObserver && this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)
    }
    ,
    a
}()
  , PivotTools = function() {
    function a() {}
    return a._RemoveAndStorePivotPoint = function(e) {
        e && a._PivotCached === 0 && (e.getPivotPointToRef(a._OldPivotPoint),
        a._PivotPostMultiplyPivotMatrix = e._postMultiplyPivotMatrix,
        a._OldPivotPoint.equalsToFloats(0, 0, 0) || (e.setPivotMatrix(Matrix.IdentityReadOnly),
        a._OldPivotPoint.subtractToRef(e.getPivotPoint(), a._PivotTranslation),
        a._PivotTmpVector.copyFromFloats(1, 1, 1),
        a._PivotTmpVector.subtractInPlace(e.scaling),
        a._PivotTmpVector.multiplyInPlace(a._PivotTranslation),
        e.position.addInPlace(a._PivotTmpVector))),
        a._PivotCached++
    }
    ,
    a._RestorePivotPoint = function(e) {
        e && !a._OldPivotPoint.equalsToFloats(0, 0, 0) && a._PivotCached === 1 && (e.setPivotPoint(a._OldPivotPoint),
        e._postMultiplyPivotMatrix = a._PivotPostMultiplyPivotMatrix,
        a._PivotTmpVector.copyFromFloats(1, 1, 1),
        a._PivotTmpVector.subtractInPlace(e.scaling),
        a._PivotTmpVector.multiplyInPlace(a._PivotTranslation),
        e.position.subtractInPlace(a._PivotTmpVector)),
        this._PivotCached--
    }
    ,
    a._PivotCached = 0,
    a._OldPivotPoint = new Vector3,
    a._PivotTranslation = new Vector3,
    a._PivotTmpVector = new Vector3,
    a._PivotPostMultiplyPivotMatrix = !1,
    a
}()
  , PointerDragBehavior = function() {
    function a(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(o) {
            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 i = 0;
        if (this._options.dragAxis && i++,
        this._options.dragPlaneNormal && i++,
        i > 1)
            throw "Multiple drag modes specified in dragBehavior options. Only one expected"
    }
    return Object.defineProperty(a.prototype, "currentDraggingPointerID", {
        get: function() {
            return this.currentDraggingPointerId
        },
        set: function(e) {
            this.currentDraggingPointerId = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "options", {
        get: function() {
            return this._options
        },
        set: function(e) {
            this._options = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "name", {
        get: function() {
            return "PointerDrag"
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.init = function() {}
    ,
    a.prototype.attach = function(e, i) {
        var o = this;
        this._scene = e.getScene(),
        e.isNearGrabbable = !0,
        this.attachedNode = e,
        a._planeScene || (this._debugMode ? a._planeScene = this._scene : (a._planeScene = new Scene(this._scene.getEngine(),{
            virtual: !0
        }),
        a._planeScene.detachControl(),
        this._scene.onDisposeObservable.addOnce(function() {
            a._planeScene.dispose(),
            a._planeScene = null
        }))),
        this._dragPlane = CreatePlane("pointerDragPlane", {
            size: this._debugMode ? 1 : 1e4,
            updatable: !1,
            sideOrientation: Mesh.DOUBLESIDE
        }, a._planeScene),
        this.lastDragPosition = new Vector3(0,0,0);
        var s = i || function(c) {
            return o.attachedNode == c || c.isDescendantOf(o.attachedNode)
        }
        ;
        this._pointerObserver = this._scene.onPointerObservable.add(function(c, d) {
            if (!o.enabled) {
                o._attachedToElement && o.releaseDrag();
                return
            }
            if (c.type == PointerEventTypes.POINTERDOWN)
                o.startAndReleaseDragOnPointerEvents && !o.dragging && c.pickInfo && c.pickInfo.hit && c.pickInfo.pickedMesh && c.pickInfo.pickedPoint && c.pickInfo.ray && s(c.pickInfo.pickedMesh) && o._startDrag(c.event.pointerId, c.pickInfo.ray, c.pickInfo.pickedPoint);
            else if (c.type == PointerEventTypes.POINTERUP)
                o.startAndReleaseDragOnPointerEvents && o.currentDraggingPointerId == c.event.pointerId && o.releaseDrag();
            else if (c.type == PointerEventTypes.POINTERMOVE) {
                var _ = c.event.pointerId;
                if (o.currentDraggingPointerId === a._AnyMouseId && _ !== a._AnyMouseId) {
                    var b = c.event
                      , k = b.pointerType === "mouse" || !o._scene.getEngine().hostInformation.isMobile && b instanceof MouseEvent;
                    k && (o._lastPointerRay[o.currentDraggingPointerId] && (o._lastPointerRay[_] = o._lastPointerRay[o.currentDraggingPointerId],
                    delete o._lastPointerRay[o.currentDraggingPointerId]),
                    o.currentDraggingPointerId = _)
                }
                o._lastPointerRay[_] || (o._lastPointerRay[_] = new Ray(new Vector3,new Vector3)),
                c.pickInfo && c.pickInfo.ray && (o._lastPointerRay[_].origin.copyFrom(c.pickInfo.ray.origin),
                o._lastPointerRay[_].direction.copyFrom(c.pickInfo.ray.direction),
                o.currentDraggingPointerId == _ && o.dragging && o._moveDrag(c.pickInfo.ray))
            }
        }),
        this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function() {
            o._moving && o.moveAttached && (PivotTools._RemoveAndStorePivotPoint(o.attachedNode),
            o._targetPosition.subtractToRef(o.attachedNode.absolutePosition, o._tmpVector),
            o._tmpVector.scaleInPlace(o.dragDeltaRatio),
            o.attachedNode.getAbsolutePosition().addToRef(o._tmpVector, o._tmpVector),
            o.validateDrag(o._tmpVector) && o.attachedNode.setAbsolutePosition(o._tmpVector),
            PivotTools._RestorePivotPoint(o.attachedNode))
        })
    }
    ,
    a.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
        }
    }
    ,
    a.prototype.startDrag = function(e, i, o) {
        e === void 0 && (e = a._AnyMouseId),
        this._startDrag(e, i, o);
        var s = this._lastPointerRay[e];
        e === a._AnyMouseId && (s = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),
        s && this._moveDrag(s)
    }
    ,
    a.prototype._startDrag = function(e, i, o) {
        if (!(!this._scene.activeCamera || this.dragging || !this.attachedNode)) {
            PivotTools._RemoveAndStorePivotPoint(this.attachedNode),
            i ? (this._startDragRay.direction.copyFrom(i.direction),
            this._startDragRay.origin.copyFrom(i.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, o || this._tmpVector);
            var s = this._pickWithRayOnDragPlane(this._startDragRay);
            s && (this.dragging = !0,
            this.currentDraggingPointerId = e,
            this.lastDragPosition.copyFrom(s),
            this.onDragStartObservable.notifyObservers({
                dragPlanePoint: s,
                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)
        }
    }
    ,
    a.prototype._moveDrag = function(e) {
        this._moving = !0;
        var i = this._pickWithRayOnDragPlane(e);
        if (i) {
            this.updateDragPlane && this._updateDragPlanePosition(e, i);
            var o = 0;
            this._options.dragAxis ? (this.useObjectOrientationForDragging ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis) : this._worldDragAxis.copyFrom(this._options.dragAxis),
            i.subtractToRef(this.lastDragPosition, this._tmpVector),
            o = Vector3.Dot(this._tmpVector, this._worldDragAxis),
            this._worldDragAxis.scaleToRef(o, this._dragDelta)) : (o = this._dragDelta.length(),
            i.subtractToRef(this.lastDragPosition, this._dragDelta)),
            this._targetPosition.addInPlace(this._dragDelta),
            this.onDragObservable.notifyObservers({
                dragDistance: o,
                delta: this._dragDelta,
                dragPlanePoint: i,
                dragPlaneNormal: this._dragPlane.forward,
                pointerId: this.currentDraggingPointerId
            }),
            this.lastDragPosition.copyFrom(i)
        }
    }
    ,
    a.prototype._pickWithRayOnDragPlane = function(e) {
        var i = this;
        if (!e)
            return null;
        var o = Math.acos(Vector3.Dot(this._dragPlane.forward, e.direction));
        if (o > Math.PI / 2 && (o = Math.PI - o),
        this.maxDragAngle > 0 && o > 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 s = Vector3.Dot(this._dragPlane.forward, this._tmpVector);
                return this._dragPlane.forward.scaleToRef(-s, this._alternatePickedPoint),
                this._alternatePickedPoint.addInPlace(this._tmpVector),
                this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),
                this._alternatePickedPoint
            } else
                return null;
        var c = a._planeScene.pickWithRay(e, function(d) {
            return d == i._dragPlane
        });
        return c && c.hit && c.pickedMesh && c.pickedPoint ? c.pickedPoint : null
    }
    ,
    a.prototype._updateDragPlanePosition = function(e, i) {
        this._pointA.copyFrom(i),
        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)
    }
    ,
    a.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()
    }
    ,
    a._AnyMouseId = -2,
    a
}()
  , PlaneRotationGizmo = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b) {
        o === void 0 && (o = Color3.Gray()),
        s === void 0 && (s = UtilityLayerRenderer.DefaultUtilityLayer),
        c === void 0 && (c = 32),
        d === void 0 && (d = null),
        b === void 0 && (b = 1);
        var k, j = a.call(this, s) || this;
        j._pointerObserver = null,
        j.snapDistance = 0,
        j.onSnapObservable = new Observable,
        j.angle = 0,
        j._isEnabled = !0,
        j._parent = null,
        j._dragging = !1,
        j._angles = new Vector3,
        j._parent = d,
        j._coloredMaterial = new StandardMaterial("",s.utilityLayerScene),
        j._coloredMaterial.diffuseColor = o,
        j._coloredMaterial.specularColor = o.subtract(new Color3(.1,.1,.1)),
        j._hoverMaterial = new StandardMaterial("",s.utilityLayerScene),
        j._hoverMaterial.diffuseColor = Color3.Yellow(),
        j._disableMaterial = new StandardMaterial("",s.utilityLayerScene),
        j._disableMaterial.diffuseColor = Color3.Gray(),
        j._disableMaterial.alpha = .4,
        j._gizmoMesh = new Mesh("",s.utilityLayerScene);
        var $ = j._createGizmoMesh(j._gizmoMesh, b, c)
          , _e = $.rotationMesh
          , et = $.collider;
        j._rotationDisplayPlane = CreatePlane("rotationDisplay", {
            size: .6,
            updatable: !1
        }, j.gizmoLayer.utilityLayerScene),
        j._rotationDisplayPlane.rotation.z = Math.PI * .5,
        j._rotationDisplayPlane.parent = j._gizmoMesh,
        j._rotationDisplayPlane.setEnabled(!1),
        Effect.ShadersStore.rotationGizmoVertexShader = e._rotationGizmoVertexShader,
        Effect.ShadersStore.rotationGizmoFragmentShader = e._rotationGizmoFragmentShader,
        j._rotationShaderMaterial = new ShaderMaterial("shader",j.gizmoLayer.utilityLayerScene,{
            vertex: "rotationGizmo",
            fragment: "rotationGizmo"
        },{
            attributes: ["position", "uv"],
            uniforms: ["worldViewProjection", "angles"]
        }),
        j._rotationShaderMaterial.backFaceCulling = !1,
        j._rotationDisplayPlane.material = j._rotationShaderMaterial,
        j._rotationDisplayPlane.visibility = .999,
        j._gizmoMesh.lookAt(j._rootMesh.position.add(i)),
        j._rootMesh.addChild(j._gizmoMesh),
        j._gizmoMesh.scaling.scaleInPlace(1 / 3),
        j.dragBehavior = new PointerDragBehavior({
            dragPlaneNormal: i
        }),
        j.dragBehavior.moveAttached = !1,
        j.dragBehavior.maxDragAngle = e.MaxDragAngle,
        j.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = !0,
        j._rootMesh.addBehavior(j.dragBehavior);
        var tt = new Vector3
          , rt = new Matrix
          , it = new Vector3
          , nt = new Vector3;
        j.dragBehavior.onDragStartObservable.add(function(ft) {
            j.attachedNode && (tt.copyFrom(ft.dragPlanePoint),
            j._rotationDisplayPlane.setEnabled(!0),
            j._rotationDisplayPlane.getWorldMatrix().invertToRef(rt),
            Vector3.TransformCoordinatesToRef(ft.dragPlanePoint, rt, tt),
            j._angles.x = Math.atan2(tt.y, tt.x) + Math.PI,
            j._angles.y = 0,
            j._angles.z = j.updateGizmoRotationToMatchAttachedMesh ? 1 : 0,
            j._dragging = !0,
            tt.copyFrom(ft.dragPlanePoint),
            j._rotationShaderMaterial.setVector3("angles", j._angles),
            j.angle = 0)
        }),
        j.dragBehavior.onDragEndObservable.add(function() {
            j._dragging = !1,
            j._rotationDisplayPlane.setEnabled(!1)
        });
        var ot = {
            snapDistance: 0
        }
          , at = 0
          , st = new Matrix
          , ut = new Quaternion;
        j.dragBehavior.onDragObservable.add(function(ft) {
            if (j.attachedNode) {
                var ht = new Vector3(1,1,1)
                  , pt = new Quaternion(0,0,0,1)
                  , dt = new Vector3(0,0,0);
                j._handlePivot(),
                j.attachedNode.getWorldMatrix().decompose(ht, pt, dt);
                var _t = ft.dragPlanePoint.subtract(dt).normalize()
                  , mt = tt.subtract(dt).normalize()
                  , vt = Vector3.Cross(_t, mt)
                  , yt = Vector3.Dot(_t, mt)
                  , Et = Math.atan2(vt.length(), yt);
                it.copyFrom(i),
                nt.copyFrom(i),
                j.updateGizmoRotationToMatchAttachedMesh && (pt.toRotationMatrix(rt),
                nt = Vector3.TransformCoordinates(it, rt));
                var At = !1;
                if (s.utilityLayerScene.activeCamera) {
                    var gt = s.utilityLayerScene.activeCamera.position.subtract(dt).normalize();
                    Vector3.Dot(gt, nt) > 0 && (it.scaleInPlace(-1),
                    nt.scaleInPlace(-1),
                    At = !0)
                }
                var St = Vector3.Dot(nt, vt) > 0;
                St && (Et = -Et);
                var xt = !1;
                if (j.snapDistance != 0)
                    if (at += Et,
                    Math.abs(at) > j.snapDistance) {
                        var bt = Math.floor(Math.abs(at) / j.snapDistance);
                        at < 0 && (bt *= -1),
                        at = at % j.snapDistance,
                        Et = j.snapDistance * bt,
                        xt = !0
                    } else
                        Et = 0;
                var Rt = Math.sin(Et / 2);
                if (ut.set(it.x * Rt, it.y * Rt, it.z * Rt, Math.cos(Et / 2)),
                st.determinant() > 0) {
                    var Mt = new Vector3;
                    ut.toEulerAnglesToRef(Mt),
                    Quaternion.RotationYawPitchRollToRef(Mt.y, -Mt.x, -Mt.z, ut)
                }
                j.updateGizmoRotationToMatchAttachedMesh ? pt.multiplyToRef(ut, pt) : ut.multiplyToRef(pt, pt),
                j.attachedNode.getWorldMatrix().copyFrom(Matrix.Compose(ht, pt, dt)),
                tt.copyFrom(ft.dragPlanePoint),
                xt && (ot.snapDistance = Et,
                j.onSnapObservable.notifyObservers(ot)),
                j._angles.y += Et,
                j.angle += At ? -Et : Et,
                j._rotationShaderMaterial.setVector3("angles", j._angles),
                j._matrixChanged()
            }
        });
        var ct = s._getSharedGizmoLight();
        ct.includedOnlyMeshes = ct.includedOnlyMeshes.concat(j._rootMesh.getChildMeshes(!1));
        var lt = {
            colliderMeshes: [et],
            gizmoMeshes: [_e],
            material: j._coloredMaterial,
            hoverMaterial: j._hoverMaterial,
            disableMaterial: j._disableMaterial,
            active: !1,
            dragBehavior: j.dragBehavior
        };
        return (k = j._parent) === null || k === void 0 || k.addToAxisCache(j._gizmoMesh, lt),
        j._pointerObserver = s.utilityLayerScene.onPointerObservable.add(function(ft) {
            var ht;
            if (!j._customMeshSet && (j.dragBehavior.maxDragAngle = e.MaxDragAngle,
            j._isHovered = lt.colliderMeshes.indexOf((ht = ft == null ? void 0 : ft.pickInfo) === null || ht === void 0 ? void 0 : ht.pickedMesh) != -1,
            !j._parent)) {
                var pt = lt.dragBehavior.enabled ? j._isHovered || j._dragging ? j._hoverMaterial : j._coloredMaterial : j._disableMaterial;
                j._setGizmoMeshMaterial(lt.gizmoMeshes, pt)
            }
        }),
        j.dragBehavior.onEnabledObservable.add(function(ft) {
            j._setGizmoMeshMaterial(lt.gizmoMeshes, ft ? j._coloredMaterial : j._disableMaterial)
        }),
        j
    }
    return e.prototype._createGizmoMesh = function(i, o, s) {
        var c = CreateTorus("ignore", {
            diameter: .6,
            thickness: .03 * o,
            tessellation: s
        }, this.gizmoLayer.utilityLayerScene);
        c.visibility = 0;
        var d = CreateTorus("", {
            diameter: .6,
            thickness: .005 * o,
            tessellation: s
        }, this.gizmoLayer.utilityLayerScene);
        return d.material = this._coloredMaterial,
        d.rotation.x = Math.PI / 2,
        c.rotation.x = Math.PI / 2,
        i.addChild(d),
        i.addChild(c),
        {
            rotationMesh: d,
            collider: c
        }
    }
    ,
    e.prototype._attachedNodeChanged = function(i) {
        this.dragBehavior && (this.dragBehavior.enabled = !!i)
    }
    ,
    Object.defineProperty(e.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(i) {
            this._isEnabled = i,
            i ? 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(i) {
            i && i.dispose()
        }),
        a.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(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _) {
        i === void 0 && (i = UtilityLayerRenderer.DefaultUtilityLayer),
        o === void 0 && (o = 32),
        s === void 0 && (s = !1),
        c === void 0 && (c = 1);
        var b = a.call(this, i) || this;
        b.onDragStartObservable = new Observable,
        b.onDragEndObservable = new Observable,
        b._observables = [],
        b._gizmoAxisCache = new Map;
        var k = _ && _.xOptions && _.xOptions.color ? _.xOptions.color : Color3.Red().scale(.5)
          , j = _ && _.yOptions && _.yOptions.color ? _.yOptions.color : Color3.Green().scale(.5)
          , $ = _ && _.zOptions && _.zOptions.color ? _.zOptions.color : Color3.Blue().scale(.5);
        return b.xGizmo = new PlaneRotationGizmo(new Vector3(1,0,0),k,i,o,b,s,c),
        b.yGizmo = new PlaneRotationGizmo(new Vector3(0,1,0),j,i,o,b,s,c),
        b.zGizmo = new PlaneRotationGizmo(new Vector3(0,0,1),$,i,o,b,s,c),
        [b.xGizmo, b.yGizmo, b.zGizmo].forEach(function(_e) {
            _ && _.updateScale != null && (_e.updateScale = _.updateScale),
            _e.dragBehavior.onDragStartObservable.add(function() {
                b.onDragStartObservable.notifyObservers({})
            }),
            _e.dragBehavior.onDragEndObservable.add(function() {
                b.onDragEndObservable.notifyObservers({})
            })
        }),
        b.attachedMesh = null,
        b.attachedNode = null,
        d ? d.addToAxisCache(b._gizmoAxisCache) : Gizmo.GizmoAxisPointerObserver(i, b._gizmoAxisCache),
        b
    }
    return Object.defineProperty(e.prototype, "attachedMesh", {
        get: function() {
            return this._meshAttached
        },
        set: function(i) {
            this._meshAttached = i,
            this._nodeAttached = i,
            this._checkBillboardTransform(),
            [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function(o) {
                o.isEnabled ? o.attachedMesh = i : o.attachedMesh = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "attachedNode", {
        get: function() {
            return this._nodeAttached
        },
        set: function(i) {
            this._meshAttached = null,
            this._nodeAttached = i,
            this._checkBillboardTransform(),
            [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function(o) {
                o.isEnabled ? o.attachedNode = i : o.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 i = !1;
            return [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function(o) {
                i = i || o.isHovered
            }),
            i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "updateGizmoRotationToMatchAttachedMesh", {
        get: function() {
            return this.xGizmo.updateGizmoRotationToMatchAttachedMesh
        },
        set: function(i) {
            this.xGizmo && (this.xGizmo.updateGizmoRotationToMatchAttachedMesh = i,
            this.yGizmo.updateGizmoRotationToMatchAttachedMesh = i,
            this.zGizmo.updateGizmoRotationToMatchAttachedMesh = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "snapDistance", {
        get: function() {
            return this.xGizmo.snapDistance
        },
        set: function(i) {
            this.xGizmo && (this.xGizmo.snapDistance = i,
            this.yGizmo.snapDistance = i,
            this.zGizmo.snapDistance = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaleRatio", {
        get: function() {
            return this.xGizmo.scaleRatio
        },
        set: function(i) {
            this.xGizmo && (this.xGizmo.scaleRatio = i,
            this.yGizmo.scaleRatio = i,
            this.zGizmo.scaleRatio = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addToAxisCache = function(i, o) {
        this._gizmoAxisCache.set(i, o)
    }
    ,
    e.prototype.dispose = function() {
        var i = this;
        this.xGizmo.dispose(),
        this.yGizmo.dispose(),
        this.zGizmo.dispose(),
        this.onDragStartObservable.clear(),
        this.onDragEndObservable.clear(),
        this._observables.forEach(function(o) {
            i.gizmoLayer.utilityLayerScene.onPointerObservable.remove(o)
        })
    }
    ,
    e.prototype.setCustomMesh = function(i) {
        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(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        o === void 0 && (o = Color3.Gray()),
        s === void 0 && (s = UtilityLayerRenderer.DefaultUtilityLayer),
        c === void 0 && (c = null),
        d === void 0 && (d = 1);
        var _, b = a.call(this, s) || this;
        b._pointerObserver = null,
        b.snapDistance = 0,
        b.onSnapObservable = new Observable,
        b._isEnabled = !0,
        b._parent = null,
        b._dragging = !1,
        b._parent = c,
        b._coloredMaterial = new StandardMaterial("",s.utilityLayerScene),
        b._coloredMaterial.diffuseColor = o,
        b._coloredMaterial.specularColor = o.subtract(new Color3(.1,.1,.1)),
        b._hoverMaterial = new StandardMaterial("",s.utilityLayerScene),
        b._hoverMaterial.diffuseColor = Color3.Yellow(),
        b._disableMaterial = new StandardMaterial("",s.utilityLayerScene),
        b._disableMaterial.diffuseColor = Color3.Gray(),
        b._disableMaterial.alpha = .4;
        var k = e._CreateArrow(s.utilityLayerScene, b._coloredMaterial, d)
          , j = e._CreateArrow(s.utilityLayerScene, b._coloredMaterial, d + 4, !0);
        b._gizmoMesh = new Mesh("",s.utilityLayerScene),
        b._gizmoMesh.addChild(k),
        b._gizmoMesh.addChild(j),
        b._gizmoMesh.lookAt(b._rootMesh.position.add(i)),
        b._gizmoMesh.scaling.scaleInPlace(1 / 3),
        b._gizmoMesh.parent = b._rootMesh;
        var $ = 0
          , _e = new Vector3
          , et = new Vector3
          , tt = {
            snapDistance: 0
        };
        b.dragBehavior = new PointerDragBehavior({
            dragAxis: i
        }),
        b.dragBehavior.moveAttached = !1,
        b._rootMesh.addBehavior(b.dragBehavior),
        b.dragBehavior.onDragObservable.add(function(nt) {
            if (b.attachedNode) {
                b._handlePivot();
                var ot = !1;
                if (b.snapDistance == 0)
                    b.attachedNode.getWorldMatrix().getTranslationToRef(et),
                    et.addInPlace(nt.delta),
                    b.dragBehavior.validateDrag(et) && (b.attachedNode.position && b.attachedNode.position.addInPlaceFromFloats(nt.delta.x, nt.delta.y, nt.delta.z),
                    b.attachedNode.getWorldMatrix().addTranslationFromFloats(nt.delta.x, nt.delta.y, nt.delta.z),
                    b.attachedNode.updateCache(),
                    ot = !0);
                else if ($ += nt.dragDistance,
                Math.abs($) > b.snapDistance) {
                    var at = Math.floor(Math.abs($) / b.snapDistance);
                    $ = $ % b.snapDistance,
                    nt.delta.normalizeToRef(_e),
                    _e.scaleInPlace(b.snapDistance * at),
                    b.attachedNode.getWorldMatrix().getTranslationToRef(et),
                    et.addInPlace(_e),
                    b.dragBehavior.validateDrag(et) && (b.attachedNode.getWorldMatrix().addTranslationFromFloats(_e.x, _e.y, _e.z),
                    b.attachedNode.updateCache(),
                    tt.snapDistance = b.snapDistance * at,
                    b.onSnapObservable.notifyObservers(tt),
                    ot = !0)
                }
                ot && b._matrixChanged()
            }
        }),
        b.dragBehavior.onDragStartObservable.add(function() {
            b._dragging = !0
        }),
        b.dragBehavior.onDragEndObservable.add(function() {
            b._dragging = !1
        });
        var rt = s._getSharedGizmoLight();
        rt.includedOnlyMeshes = rt.includedOnlyMeshes.concat(b._rootMesh.getChildMeshes(!1));
        var it = {
            gizmoMeshes: k.getChildMeshes(),
            colliderMeshes: j.getChildMeshes(),
            material: b._coloredMaterial,
            hoverMaterial: b._hoverMaterial,
            disableMaterial: b._disableMaterial,
            active: !1,
            dragBehavior: b.dragBehavior
        };
        return (_ = b._parent) === null || _ === void 0 || _.addToAxisCache(j, it),
        b._pointerObserver = s.utilityLayerScene.onPointerObservable.add(function(nt) {
            var ot;
            if (!b._customMeshSet && (b._isHovered = it.colliderMeshes.indexOf((ot = nt == null ? void 0 : nt.pickInfo) === null || ot === void 0 ? void 0 : ot.pickedMesh) != -1,
            !b._parent)) {
                var at = b.dragBehavior.enabled ? b._isHovered || b._dragging ? b._hoverMaterial : b._coloredMaterial : b._disableMaterial;
                b._setGizmoMeshMaterial(it.gizmoMeshes, at)
            }
        }),
        b.dragBehavior.onEnabledObservable.add(function(nt) {
            b._setGizmoMeshMaterial(it.gizmoMeshes, nt ? it.material : it.disableMaterial)
        }),
        b
    }
    return e._CreateArrow = function(i, o, s, c) {
        s === void 0 && (s = 1),
        c === void 0 && (c = !1);
        var d = new TransformNode("arrow",i)
          , _ = CreateCylinder("cylinder", {
            diameterTop: 0,
            height: .075,
            diameterBottom: .0375 * (1 + (s - 1) / 4),
            tessellation: 96
        }, i)
          , b = CreateCylinder("cylinder", {
            diameterTop: .005 * s,
            height: .275,
            diameterBottom: .005 * s,
            tessellation: 96
        }, i);
        return _.parent = d,
        _.material = o,
        _.rotation.x = Math.PI / 2,
        _.position.z += .3,
        b.parent = d,
        b.material = o,
        b.position.z += .275 / 2,
        b.rotation.x = Math.PI / 2,
        c && (b.visibility = 0,
        _.visibility = 0),
        d
    }
    ,
    e._CreateArrowInstance = function(i, o) {
        for (var s = new TransformNode("arrow",i), c = 0, d = o.getChildMeshes(); c < d.length; c++) {
            var _ = d[c]
              , b = _.createInstance(_.name);
            b.parent = s
        }
        return s
    }
    ,
    e.prototype._attachedNodeChanged = function(i) {
        this.dragBehavior && (this.dragBehavior.enabled = !!i)
    }
    ,
    Object.defineProperty(e.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(i) {
            this._isEnabled = i,
            i ? 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(i) {
            i && i.dispose()
        }),
        a.prototype.dispose.call(this)
    }
    ,
    e
}(Gizmo)
  , PlaneDragGizmo = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        o === void 0 && (o = Color3.Gray()),
        s === void 0 && (s = UtilityLayerRenderer.DefaultUtilityLayer),
        c === void 0 && (c = null);
        var d, _ = a.call(this, s) || this;
        _._pointerObserver = null,
        _.snapDistance = 0,
        _.onSnapObservable = new Observable,
        _._isEnabled = !1,
        _._parent = null,
        _._dragging = !1,
        _._parent = c,
        _._coloredMaterial = new StandardMaterial("",s.utilityLayerScene),
        _._coloredMaterial.diffuseColor = o,
        _._coloredMaterial.specularColor = o.subtract(new Color3(.1,.1,.1)),
        _._hoverMaterial = new StandardMaterial("",s.utilityLayerScene),
        _._hoverMaterial.diffuseColor = Color3.Yellow(),
        _._disableMaterial = new StandardMaterial("",s.utilityLayerScene),
        _._disableMaterial.diffuseColor = Color3.Gray(),
        _._disableMaterial.alpha = .4,
        _._gizmoMesh = e._CreatePlane(s.utilityLayerScene, _._coloredMaterial),
        _._gizmoMesh.lookAt(_._rootMesh.position.add(i)),
        _._gizmoMesh.scaling.scaleInPlace(1 / 3),
        _._gizmoMesh.parent = _._rootMesh;
        var b = 0
          , k = new Vector3
          , j = {
            snapDistance: 0
        };
        _.dragBehavior = new PointerDragBehavior({
            dragPlaneNormal: i
        }),
        _.dragBehavior.moveAttached = !1,
        _._rootMesh.addBehavior(_.dragBehavior),
        _.dragBehavior.onDragObservable.add(function(et) {
            if (_.attachedNode) {
                if (_._handlePivot(),
                _.snapDistance == 0)
                    _.attachedNode.getWorldMatrix().addTranslationFromFloats(et.delta.x, et.delta.y, et.delta.z);
                else if (b += et.dragDistance,
                Math.abs(b) > _.snapDistance) {
                    var tt = Math.floor(Math.abs(b) / _.snapDistance);
                    b = b % _.snapDistance,
                    et.delta.normalizeToRef(k),
                    k.scaleInPlace(_.snapDistance * tt),
                    _.attachedNode.getWorldMatrix().addTranslationFromFloats(k.x, k.y, k.z),
                    j.snapDistance = _.snapDistance * tt,
                    _.onSnapObservable.notifyObservers(j)
                }
                _._matrixChanged()
            }
        }),
        _.dragBehavior.onDragStartObservable.add(function() {
            _._dragging = !0
        }),
        _.dragBehavior.onDragEndObservable.add(function() {
            _._dragging = !1
        });
        var $ = s._getSharedGizmoLight();
        $.includedOnlyMeshes = $.includedOnlyMeshes.concat(_._rootMesh.getChildMeshes(!1));
        var _e = {
            gizmoMeshes: _._gizmoMesh.getChildMeshes(),
            colliderMeshes: _._gizmoMesh.getChildMeshes(),
            material: _._coloredMaterial,
            hoverMaterial: _._hoverMaterial,
            disableMaterial: _._disableMaterial,
            active: !1,
            dragBehavior: _.dragBehavior
        };
        return (d = _._parent) === null || d === void 0 || d.addToAxisCache(_._gizmoMesh, _e),
        _._pointerObserver = s.utilityLayerScene.onPointerObservable.add(function(et) {
            var tt;
            if (!_._customMeshSet && (_._isHovered = _e.colliderMeshes.indexOf((tt = et == null ? void 0 : et.pickInfo) === null || tt === void 0 ? void 0 : tt.pickedMesh) != -1,
            !_._parent)) {
                var rt = _e.dragBehavior.enabled ? _._isHovered || _._dragging ? _._hoverMaterial : _._coloredMaterial : _._disableMaterial;
                _._setGizmoMeshMaterial(_e.gizmoMeshes, rt)
            }
        }),
        _.dragBehavior.onEnabledObservable.add(function(et) {
            _._setGizmoMeshMaterial(_e.gizmoMeshes, et ? _._coloredMaterial : _._disableMaterial)
        }),
        _
    }
    return e._CreatePlane = function(i, o) {
        var s = new TransformNode("plane",i)
          , c = CreatePlane("dragPlane", {
            width: .1375,
            height: .1375,
            sideOrientation: 2
        }, i);
        return c.material = o,
        c.parent = s,
        s
    }
    ,
    e.prototype._attachedNodeChanged = function(i) {
        this.dragBehavior && (this.dragBehavior.enabled = !!i)
    }
    ,
    Object.defineProperty(e.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(i) {
            this._isEnabled = i,
            i ? 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(),
        a.prototype.dispose.call(this),
        this._gizmoMesh && this._gizmoMesh.dispose(),
        [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach(function(i) {
            i && i.dispose()
        })
    }
    ,
    e
}(Gizmo)
  , PositionGizmo = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        i === void 0 && (i = UtilityLayerRenderer.DefaultUtilityLayer),
        o === void 0 && (o = 1);
        var c = a.call(this, i) || this;
        return c._meshAttached = null,
        c._nodeAttached = null,
        c._observables = [],
        c._gizmoAxisCache = new Map,
        c.onDragStartObservable = new Observable,
        c.onDragEndObservable = new Observable,
        c._planarGizmoEnabled = !1,
        c.xGizmo = new AxisDragGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),i,c,o),
        c.yGizmo = new AxisDragGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),i,c,o),
        c.zGizmo = new AxisDragGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),i,c,o),
        c.xPlaneGizmo = new PlaneDragGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),c.gizmoLayer,c),
        c.yPlaneGizmo = new PlaneDragGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),c.gizmoLayer,c),
        c.zPlaneGizmo = new PlaneDragGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),c.gizmoLayer,c),
        [c.xGizmo, c.yGizmo, c.zGizmo, c.xPlaneGizmo, c.yPlaneGizmo, c.zPlaneGizmo].forEach(function(d) {
            d.dragBehavior.onDragStartObservable.add(function() {
                c.onDragStartObservable.notifyObservers({})
            }),
            d.dragBehavior.onDragEndObservable.add(function() {
                c.onDragEndObservable.notifyObservers({})
            })
        }),
        c.attachedMesh = null,
        s ? s.addToAxisCache(c._gizmoAxisCache) : Gizmo.GizmoAxisPointerObserver(i, c._gizmoAxisCache),
        c
    }
    return Object.defineProperty(e.prototype, "attachedMesh", {
        get: function() {
            return this._meshAttached
        },
        set: function(i) {
            this._meshAttached = i,
            this._nodeAttached = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(o) {
                o.isEnabled ? o.attachedMesh = i : o.attachedMesh = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "attachedNode", {
        get: function() {
            return this._nodeAttached
        },
        set: function(i) {
            this._meshAttached = null,
            this._nodeAttached = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(o) {
                o.isEnabled ? o.attachedNode = i : o.attachedNode = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isHovered", {
        get: function() {
            var i = !1;
            return [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(o) {
                i = i || o.isHovered
            }),
            i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "planarGizmoEnabled", {
        get: function() {
            return this._planarGizmoEnabled
        },
        set: function(i) {
            var o = this;
            this._planarGizmoEnabled = i,
            [this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(s) {
                s && (s.isEnabled = i,
                i && (s.attachedMesh ? s.attachedMesh = o.attachedMesh : s.attachedNode = o.attachedNode))
            }, this)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "updateGizmoRotationToMatchAttachedMesh", {
        get: function() {
            return this._updateGizmoRotationToMatchAttachedMesh
        },
        set: function(i) {
            this._updateGizmoRotationToMatchAttachedMesh = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(o) {
                o && (o.updateGizmoRotationToMatchAttachedMesh = i)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "snapDistance", {
        get: function() {
            return this._snapDistance
        },
        set: function(i) {
            this._snapDistance = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(o) {
                o && (o.snapDistance = i)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaleRatio", {
        get: function() {
            return this._scaleRatio
        },
        set: function(i) {
            this._scaleRatio = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(o) {
                o && (o.scaleRatio = i)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addToAxisCache = function(i, o) {
        this._gizmoAxisCache.set(i, o)
    }
    ,
    e.prototype.dispose = function() {
        var i = this;
        [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(o) {
            o && o.dispose()
        }),
        this._observables.forEach(function(o) {
            i.gizmoLayer.utilityLayerScene.onPointerObservable.remove(o)
        }),
        this.onDragStartObservable.clear(),
        this.onDragEndObservable.clear()
    }
    ,
    e.prototype.setCustomMesh = function(i) {
        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(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        o === void 0 && (o = Color3.Gray()),
        s === void 0 && (s = UtilityLayerRenderer.DefaultUtilityLayer),
        c === void 0 && (c = null),
        d === void 0 && (d = 1);
        var _, b, k, j, $, _e, et, tt = a.call(this, s) || this;
        tt._pointerObserver = null,
        tt.snapDistance = 0,
        tt.onSnapObservable = new Observable,
        tt.uniformScaling = !1,
        tt.sensitivity = 1,
        tt.dragScale = 1,
        tt._isEnabled = !0,
        tt._parent = null,
        tt._dragging = !1,
        tt._tmpVector = new Vector3,
        tt._tmpMatrix = new Matrix,
        tt._tmpMatrix2 = new Matrix,
        tt._parent = c,
        tt._coloredMaterial = new StandardMaterial("",s.utilityLayerScene),
        tt._coloredMaterial.diffuseColor = o,
        tt._coloredMaterial.specularColor = o.subtract(new Color3(.1,.1,.1)),
        tt._hoverMaterial = new StandardMaterial("",s.utilityLayerScene),
        tt._hoverMaterial.diffuseColor = Color3.Yellow(),
        tt._disableMaterial = new StandardMaterial("",s.utilityLayerScene),
        tt._disableMaterial.diffuseColor = Color3.Gray(),
        tt._disableMaterial.alpha = .4,
        tt._gizmoMesh = new Mesh("axis",s.utilityLayerScene);
        var rt = tt._createGizmoMesh(tt._gizmoMesh, d)
          , it = rt.arrowMesh
          , nt = rt.arrowTail
          , ot = tt._createGizmoMesh(tt._gizmoMesh, d + 4, !0);
        tt._gizmoMesh.lookAt(tt._rootMesh.position.add(i)),
        tt._rootMesh.addChild(tt._gizmoMesh),
        tt._gizmoMesh.scaling.scaleInPlace(1 / 3);
        var at = it.position.clone()
          , st = nt.position.clone()
          , ut = nt.scaling.clone()
          , ct = function(mt) {
            var vt = mt * (3 / tt._rootMesh.scaling.length()) * 6;
            it.position.z += vt / 3.5,
            nt.scaling.y += vt,
            tt.dragScale = nt.scaling.y,
            nt.position.z = it.position.z / 2
        }
          , lt = function() {
            it.position.set(at.x, at.y, at.z),
            nt.position.set(st.x, st.y, st.z),
            nt.scaling.set(ut.x, ut.y, ut.z),
            tt.dragScale = nt.scaling.y,
            tt._dragging = !1
        };
        tt.dragBehavior = new PointerDragBehavior({
            dragAxis: i
        }),
        tt.dragBehavior.moveAttached = !1,
        tt._rootMesh.addBehavior(tt.dragBehavior);
        var ft = 0
          , ht = new Vector3
          , pt = {
            snapDistance: 0
        };
        tt.dragBehavior.onDragObservable.add(function(mt) {
            if (tt.attachedNode) {
                tt._handlePivot();
                var vt = tt.sensitivity * mt.dragDistance * (tt.scaleRatio * 3 / tt._rootMesh.scaling.length())
                  , yt = !1
                  , Et = 0;
                tt.uniformScaling ? ht.setAll(.57735) : ht.copyFrom(i),
                tt.snapDistance == 0 ? ht.scaleToRef(vt, ht) : (ft += vt,
                Math.abs(ft) > tt.snapDistance ? (Et = Math.floor(Math.abs(ft) / tt.snapDistance),
                ft < 0 && (Et *= -1),
                ft = ft % tt.snapDistance,
                ht.scaleToRef(tt.snapDistance * Et, ht),
                yt = !0) : ht.scaleInPlace(0)),
                Matrix.ScalingToRef(1 + ht.x, 1 + ht.y, 1 + ht.z, tt._tmpMatrix2),
                tt._tmpMatrix2.multiplyToRef(tt.attachedNode.getWorldMatrix(), tt._tmpMatrix),
                tt._tmpMatrix.decompose(tt._tmpVector);
                var At = 1e5;
                Math.abs(tt._tmpVector.x) < At && Math.abs(tt._tmpVector.y) < At && Math.abs(tt._tmpVector.z) < At && tt.attachedNode.getWorldMatrix().copyFrom(tt._tmpMatrix),
                yt && (pt.snapDistance = tt.snapDistance * Et,
                tt.onSnapObservable.notifyObservers(pt)),
                tt._matrixChanged()
            }
        }),
        tt.dragBehavior.onDragStartObservable.add(function() {
            tt._dragging = !0
        }),
        tt.dragBehavior.onDragObservable.add(function(mt) {
            return ct(mt.dragDistance)
        }),
        tt.dragBehavior.onDragEndObservable.add(lt),
        (k = (b = (_ = c == null ? void 0 : c.uniformScaleGizmo) === null || _ === void 0 ? void 0 : _.dragBehavior) === null || b === void 0 ? void 0 : b.onDragObservable) === null || k === void 0 || k.add(function(mt) {
            return ct(mt.delta.y)
        }),
        (_e = ($ = (j = c == null ? void 0 : c.uniformScaleGizmo) === null || j === void 0 ? void 0 : j.dragBehavior) === null || $ === void 0 ? void 0 : $.onDragEndObservable) === null || _e === void 0 || _e.add(lt);
        var dt = {
            gizmoMeshes: [it, nt],
            colliderMeshes: [ot.arrowMesh, ot.arrowTail],
            material: tt._coloredMaterial,
            hoverMaterial: tt._hoverMaterial,
            disableMaterial: tt._disableMaterial,
            active: !1,
            dragBehavior: tt.dragBehavior
        };
        (et = tt._parent) === null || et === void 0 || et.addToAxisCache(tt._gizmoMesh, dt),
        tt._pointerObserver = s.utilityLayerScene.onPointerObservable.add(function(mt) {
            var vt;
            if (!tt._customMeshSet && (tt._isHovered = dt.colliderMeshes.indexOf((vt = mt == null ? void 0 : mt.pickInfo) === null || vt === void 0 ? void 0 : vt.pickedMesh) != -1,
            !tt._parent)) {
                var yt = tt.dragBehavior.enabled ? tt._isHovered || tt._dragging ? tt._hoverMaterial : tt._coloredMaterial : tt._disableMaterial;
                tt._setGizmoMeshMaterial(dt.gizmoMeshes, yt)
            }
        }),
        tt.dragBehavior.onEnabledObservable.add(function(mt) {
            tt._setGizmoMeshMaterial(dt.gizmoMeshes, mt ? tt._coloredMaterial : tt._disableMaterial)
        });
        var _t = s._getSharedGizmoLight();
        return _t.includedOnlyMeshes = _t.includedOnlyMeshes.concat(tt._rootMesh.getChildMeshes()),
        tt
    }
    return e.prototype._createGizmoMesh = function(i, o, s) {
        s === void 0 && (s = !1);
        var c = CreateBox("yPosMesh", {
            size: .4 * (1 + (o - 1) / 4)
        }, this.gizmoLayer.utilityLayerScene)
          , d = CreateCylinder("cylinder", {
            diameterTop: .005 * o,
            height: .275,
            diameterBottom: .005 * o,
            tessellation: 96
        }, this.gizmoLayer.utilityLayerScene);
        return c.scaling.scaleInPlace(.1),
        c.material = this._coloredMaterial,
        c.rotation.x = Math.PI / 2,
        c.position.z += .3,
        d.material = this._coloredMaterial,
        d.position.z += .275 / 2,
        d.rotation.x = Math.PI / 2,
        s && (c.visibility = 0,
        d.visibility = 0),
        i.addChild(c),
        i.addChild(d),
        {
            arrowMesh: c,
            arrowTail: d
        }
    }
    ,
    e.prototype._attachedNodeChanged = function(i) {
        this.dragBehavior && (this.dragBehavior.enabled = !!i)
    }
    ,
    Object.defineProperty(e.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(i) {
            this._isEnabled = i,
            i ? 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(i) {
            i && i.dispose()
        }),
        a.prototype.dispose.call(this)
    }
    ,
    e.prototype.setCustomMesh = function(i, o) {
        var s = this;
        o === void 0 && (o = !1),
        a.prototype.setCustomMesh.call(this, i),
        o && (this._rootMesh.getChildMeshes().forEach(function(c) {
            c.material = s._coloredMaterial,
            c.color && (c.color = s._coloredMaterial.diffuseColor)
        }),
        this._customMeshSet = !1)
    }
    ,
    e
}(Gizmo)
  , ScaleGizmo = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        i === void 0 && (i = UtilityLayerRenderer.DefaultUtilityLayer),
        o === void 0 && (o = 1);
        var c = a.call(this, i) || this;
        return c._meshAttached = null,
        c._nodeAttached = null,
        c._sensitivity = 1,
        c._observables = [],
        c._gizmoAxisCache = new Map,
        c.onDragStartObservable = new Observable,
        c.onDragEndObservable = new Observable,
        c.uniformScaleGizmo = c._createUniformScaleMesh(),
        c.xGizmo = new AxisScaleGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),i,c,o),
        c.yGizmo = new AxisScaleGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),i,c,o),
        c.zGizmo = new AxisScaleGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),i,c,o),
        [c.xGizmo, c.yGizmo, c.zGizmo, c.uniformScaleGizmo].forEach(function(d) {
            d.dragBehavior.onDragStartObservable.add(function() {
                c.onDragStartObservable.notifyObservers({})
            }),
            d.dragBehavior.onDragEndObservable.add(function() {
                c.onDragEndObservable.notifyObservers({})
            })
        }),
        c.attachedMesh = null,
        c.attachedNode = null,
        s ? s.addToAxisCache(c._gizmoAxisCache) : Gizmo.GizmoAxisPointerObserver(i, c._gizmoAxisCache),
        c
    }
    return Object.defineProperty(e.prototype, "attachedMesh", {
        get: function() {
            return this._meshAttached
        },
        set: function(i) {
            this._meshAttached = i,
            this._nodeAttached = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(o) {
                o.isEnabled ? o.attachedMesh = i : o.attachedMesh = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "attachedNode", {
        get: function() {
            return this._nodeAttached
        },
        set: function(i) {
            this._meshAttached = null,
            this._nodeAttached = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(o) {
                o.isEnabled ? o.attachedNode = i : o.attachedNode = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isHovered", {
        get: function() {
            var i = !1;
            return [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function(o) {
                i = i || o.isHovered
            }),
            i
        },
        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 i = new AxisScaleGizmo(new Vector3(0,1,0),Color3.Gray().scale(.5),this.gizmoLayer,this);
        i.updateGizmoRotationToMatchAttachedMesh = !1,
        i.uniformScaling = !0,
        this._uniformScalingMesh = CreatePolyhedron("uniform", {
            type: 1
        }, i.gizmoLayer.utilityLayerScene),
        this._uniformScalingMesh.scaling.scaleInPlace(.01),
        this._uniformScalingMesh.visibility = 0,
        this._octahedron = CreatePolyhedron("", {
            type: 1
        }, i.gizmoLayer.utilityLayerScene),
        this._octahedron.scaling.scaleInPlace(.007),
        this._uniformScalingMesh.addChild(this._octahedron),
        i.setCustomMesh(this._uniformScalingMesh, !0);
        var o = this.gizmoLayer._getSharedGizmoLight();
        o.includedOnlyMeshes = o.includedOnlyMeshes.concat(this._octahedron);
        var s = {
            gizmoMeshes: [this._octahedron, this._uniformScalingMesh],
            colliderMeshes: [this._uniformScalingMesh],
            material: this._coloredMaterial,
            hoverMaterial: this._hoverMaterial,
            disableMaterial: this._disableMaterial,
            active: !1,
            dragBehavior: i.dragBehavior
        };
        return this.addToAxisCache(i._rootMesh, s),
        i
    }
    ,
    Object.defineProperty(e.prototype, "updateGizmoRotationToMatchAttachedMesh", {
        get: function() {
            return this._updateGizmoRotationToMatchAttachedMesh
        },
        set: function(i) {
            i ? (this._updateGizmoRotationToMatchAttachedMesh = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(o) {
                o && (o.updateGizmoRotationToMatchAttachedMesh = i)
            })) : 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(i) {
            this._snapDistance = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(o) {
                o && (o.snapDistance = i)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaleRatio", {
        get: function() {
            return this._scaleRatio
        },
        set: function(i) {
            this._scaleRatio = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(o) {
                o && (o.scaleRatio = i)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sensitivity", {
        get: function() {
            return this._sensitivity
        },
        set: function(i) {
            this._sensitivity = i,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(o) {
                o && (o.sensitivity = i)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addToAxisCache = function(i, o) {
        this._gizmoAxisCache.set(i, o)
    }
    ,
    e.prototype.dispose = function() {
        var i = this;
        [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(o) {
            o && o.dispose()
        }),
        this._observables.forEach(function(o) {
            i.gizmoLayer.utilityLayerScene.onPointerObservable.remove(o)
        }),
        this.onDragStartObservable.clear(),
        this.onDragEndObservable.clear(),
        [this._uniformScalingMesh, this._octahedron].forEach(function(o) {
            o && o.dispose()
        }),
        [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach(function(o) {
            o && o.dispose()
        })
    }
    ,
    e
}(Gizmo)
  , BoundingBoxGizmo = function(a) {
    __extends(e, a);
    function e(i, o) {
        i === void 0 && (i = Color3.Gray()),
        o === void 0 && (o = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer);
        var s = a.call(this, o) || this;
        s._boundingDimensions = new Vector3(1,1,1),
        s._renderObserver = null,
        s._pointerObserver = null,
        s._scaleDragSpeed = .2,
        s._tmpQuaternion = new Quaternion,
        s._tmpVector = new Vector3(0,0,0),
        s._tmpRotationMatrix = new Matrix,
        s.ignoreChildren = !1,
        s.includeChildPredicate = null,
        s.rotationSphereSize = .1,
        s.scaleBoxSize = .1,
        s.fixedDragMeshScreenSize = !1,
        s.fixedDragMeshBoundsSize = !1,
        s.fixedDragMeshScreenSizeDistanceFactor = 10,
        s.onDragStartObservable = new Observable,
        s.onScaleBoxDragObservable = new Observable,
        s.onScaleBoxDragEndObservable = new Observable,
        s.onRotationSphereDragObservable = new Observable,
        s.onRotationSphereDragEndObservable = new Observable,
        s.scalePivot = null,
        s._axisFactor = new Vector3(1,1,1),
        s._existingMeshScale = new Vector3,
        s._dragMesh = null,
        s.pointerDragBehavior = new PointerDragBehavior,
        s.updateScale = !1,
        s._anchorMesh = new AbstractMesh("anchor",o.utilityLayerScene),
        s.coloredMaterial = new StandardMaterial("",o.utilityLayerScene),
        s.coloredMaterial.disableLighting = !0,
        s.hoverColoredMaterial = new StandardMaterial("",o.utilityLayerScene),
        s.hoverColoredMaterial.disableLighting = !0,
        s._lineBoundingBox = new AbstractMesh("",o.utilityLayerScene),
        s._lineBoundingBox.rotationQuaternion = new Quaternion;
        var c = [];
        c.push(CreateLines("lines", {
            points: [new Vector3(0,0,0), new Vector3(s._boundingDimensions.x,0,0)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(0,0,0), new Vector3(0,s._boundingDimensions.y,0)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(0,0,0), new Vector3(0,0,s._boundingDimensions.z)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(s._boundingDimensions.x,0,0), new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,0)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(s._boundingDimensions.x,0,0), new Vector3(s._boundingDimensions.x,0,s._boundingDimensions.z)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(0,s._boundingDimensions.y,0), new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,0)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(0,s._boundingDimensions.y,0), new Vector3(0,s._boundingDimensions.y,s._boundingDimensions.z)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(0,0,s._boundingDimensions.z), new Vector3(s._boundingDimensions.x,0,s._boundingDimensions.z)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(0,0,s._boundingDimensions.z), new Vector3(0,s._boundingDimensions.y,s._boundingDimensions.z)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,s._boundingDimensions.z), new Vector3(0,s._boundingDimensions.y,s._boundingDimensions.z)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,s._boundingDimensions.z), new Vector3(s._boundingDimensions.x,0,s._boundingDimensions.z)]
        }, o.utilityLayerScene)),
        c.push(CreateLines("lines", {
            points: [new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,s._boundingDimensions.z), new Vector3(s._boundingDimensions.x,s._boundingDimensions.y,0)]
        }, o.utilityLayerScene)),
        c.forEach(function(it) {
            it.color = i,
            it.position.addInPlace(new Vector3(-s._boundingDimensions.x / 2,-s._boundingDimensions.y / 2,-s._boundingDimensions.z / 2)),
            it.isPickable = !1,
            s._lineBoundingBox.addChild(it)
        }),
        s._rootMesh.addChild(s._lineBoundingBox),
        s.setColor(i),
        s._rotateSpheresParent = new AbstractMesh("",o.utilityLayerScene),
        s._rotateSpheresParent.rotationQuaternion = new Quaternion;
        for (var d = function(it) {
            var nt = CreateSphere("", {
                diameter: 1
            }, o.utilityLayerScene);
            nt.rotationQuaternion = new Quaternion,
            nt.material = _.coloredMaterial,
            nt.isNearGrabbable = !0,
            b = new PointerDragBehavior({}),
            b.moveAttached = !1,
            b.updateDragPlane = !1,
            nt.addBehavior(b);
            var ot = new Vector3(1,0,0)
              , at = 0;
            b.onDragStartObservable.add(function() {
                ot.copyFrom(nt.forward),
                at = 0
            }),
            b.onDragObservable.add(function(st) {
                if (s.onRotationSphereDragObservable.notifyObservers({}),
                s.attachedMesh) {
                    var ut = s.attachedMesh.parent;
                    if (ut && ut.scaling && ut.scaling.isNonUniformWithinEpsilon(.001)) {
                        Logger$2.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");
                        return
                    }
                    PivotTools._RemoveAndStorePivotPoint(s.attachedMesh);
                    var ct = ot
                      , lt = st.dragPlaneNormal.scale(Vector3.Dot(st.dragPlaneNormal, ct))
                      , ft = ct.subtract(lt).normalizeToNew()
                      , ht = Vector3.Dot(ft, st.delta) < 0 ? Math.abs(st.delta.length()) : -Math.abs(st.delta.length());
                    ht = ht / s._boundingDimensions.length() * s._anchorMesh.scaling.length(),
                    s.attachedMesh.rotationQuaternion || (s.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(s.attachedMesh.rotation.y, s.attachedMesh.rotation.x, s.attachedMesh.rotation.z)),
                    s._anchorMesh.rotationQuaternion || (s._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(s._anchorMesh.rotation.y, s._anchorMesh.rotation.x, s._anchorMesh.rotation.z)),
                    at += ht,
                    Math.abs(at) <= 2 * Math.PI && (it >= 8 ? Quaternion.RotationYawPitchRollToRef(0, 0, ht, s._tmpQuaternion) : it >= 4 ? Quaternion.RotationYawPitchRollToRef(ht, 0, 0, s._tmpQuaternion) : Quaternion.RotationYawPitchRollToRef(0, ht, 0, s._tmpQuaternion),
                    s._anchorMesh.addChild(s.attachedMesh),
                    s._anchorMesh.rotationQuaternion.multiplyToRef(s._tmpQuaternion, s._anchorMesh.rotationQuaternion),
                    s._anchorMesh.removeChild(s.attachedMesh),
                    s.attachedMesh.setParent(ut)),
                    s.updateBoundingBox(),
                    PivotTools._RestorePivotPoint(s.attachedMesh)
                }
                s._updateDummy()
            }),
            b.onDragStartObservable.add(function() {
                s.onDragStartObservable.notifyObservers({}),
                s._selectNode(nt)
            }),
            b.onDragEndObservable.add(function() {
                s.onRotationSphereDragEndObservable.notifyObservers({}),
                s._selectNode(null),
                s._updateDummy()
            }),
            _._rotateSpheresParent.addChild(nt)
        }, _ = this, b, k = 0; k < 12; k++)
            d(k);
        s._rootMesh.addChild(s._rotateSpheresParent),
        s._scaleBoxesParent = new AbstractMesh("",o.utilityLayerScene),
        s._scaleBoxesParent.rotationQuaternion = new Quaternion;
        for (var j = 0; j < 3; j++)
            for (var $ = 0; $ < 3; $++)
                for (var _e = function() {
                    var nt = (j === 1 ? 1 : 0) + ($ === 1 ? 1 : 0) + (tt === 1 ? 1 : 0);
                    if (nt === 1 || nt === 3)
                        return "continue";
                    var ot = CreateBox("", {
                        size: 1
                    }, o.utilityLayerScene);
                    ot.material = et.coloredMaterial,
                    ot.metadata = nt === 2,
                    ot.isNearGrabbable = !0;
                    var at = new Vector3(j - 1,$ - 1,tt - 1).normalize();
                    b = new PointerDragBehavior({
                        dragAxis: at
                    }),
                    b.updateDragPlane = !1,
                    b.moveAttached = !1,
                    ot.addBehavior(b),
                    b.onDragObservable.add(function(st) {
                        if (s.onScaleBoxDragObservable.notifyObservers({}),
                        s.attachedMesh) {
                            var ut = s.attachedMesh.parent;
                            if (ut && ut.scaling && ut.scaling.isNonUniformWithinEpsilon(.001)) {
                                Logger$2.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");
                                return
                            }
                            PivotTools._RemoveAndStorePivotPoint(s.attachedMesh);
                            var ct = st.dragDistance / s._boundingDimensions.length() * s._anchorMesh.scaling.length()
                              , lt = new Vector3(ct,ct,ct);
                            nt === 2 && (lt.x *= Math.abs(at.x),
                            lt.y *= Math.abs(at.y),
                            lt.z *= Math.abs(at.z)),
                            lt.scaleInPlace(s._scaleDragSpeed),
                            lt.multiplyInPlace(s._axisFactor),
                            s.updateBoundingBox(),
                            s.scalePivot ? (s.attachedMesh.getWorldMatrix().getRotationMatrixToRef(s._tmpRotationMatrix),
                            s._boundingDimensions.scaleToRef(.5, s._tmpVector),
                            Vector3.TransformCoordinatesToRef(s._tmpVector, s._tmpRotationMatrix, s._tmpVector),
                            s._anchorMesh.position.subtractInPlace(s._tmpVector),
                            s._boundingDimensions.multiplyToRef(s.scalePivot, s._tmpVector),
                            Vector3.TransformCoordinatesToRef(s._tmpVector, s._tmpRotationMatrix, s._tmpVector),
                            s._anchorMesh.position.addInPlace(s._tmpVector)) : (ot.absolutePosition.subtractToRef(s._anchorMesh.position, s._tmpVector),
                            s._anchorMesh.position.subtractInPlace(s._tmpVector)),
                            s._anchorMesh.addChild(s.attachedMesh),
                            s._anchorMesh.scaling.addInPlace(lt),
                            (s._anchorMesh.scaling.x < 0 || s._anchorMesh.scaling.y < 0 || s._anchorMesh.scaling.z < 0) && s._anchorMesh.scaling.subtractInPlace(lt),
                            s._anchorMesh.removeChild(s.attachedMesh),
                            s.attachedMesh.setParent(ut),
                            PivotTools._RestorePivotPoint(s.attachedMesh)
                        }
                        s._updateDummy()
                    }),
                    b.onDragStartObservable.add(function() {
                        s.onDragStartObservable.notifyObservers({}),
                        s._selectNode(ot)
                    }),
                    b.onDragEndObservable.add(function() {
                        s.onScaleBoxDragEndObservable.notifyObservers({}),
                        s._selectNode(null),
                        s._updateDummy()
                    }),
                    et._scaleBoxesParent.addChild(ot)
                }, et = this, b, tt = 0; tt < 3; tt++)
                    _e();
        s._rootMesh.addChild(s._scaleBoxesParent);
        var rt = new Array;
        return s._pointerObserver = o.utilityLayerScene.onPointerObservable.add(function(it) {
            rt[it.event.pointerId] ? it.pickInfo && it.pickInfo.pickedMesh != rt[it.event.pointerId] && (rt[it.event.pointerId].material = s.coloredMaterial,
            delete rt[it.event.pointerId]) : s._rotateSpheresParent.getChildMeshes().concat(s._scaleBoxesParent.getChildMeshes()).forEach(function(nt) {
                it.pickInfo && it.pickInfo.pickedMesh == nt && (rt[it.event.pointerId] = nt,
                nt.material = s.hoverColoredMaterial)
            })
        }),
        s._renderObserver = s.gizmoLayer.originalScene.onBeforeRenderObservable.add(function() {
            s.attachedMesh && !s._existingMeshScale.equals(s.attachedMesh.scaling) ? s.updateBoundingBox() : (s.fixedDragMeshScreenSize || s.fixedDragMeshBoundsSize) && (s._updateRotationSpheres(),
            s._updateScaleBoxes()),
            s._dragMesh && s.attachedMesh && s.pointerDragBehavior.dragging && (s._lineBoundingBox.position.rotateByQuaternionToRef(s._rootMesh.rotationQuaternion, s._tmpVector),
            s.attachedMesh.setAbsolutePosition(s._dragMesh.position.add(s._tmpVector.scale(-1))))
        }),
        s.updateBoundingBox(),
        s
    }
    return Object.defineProperty(e.prototype, "axisFactor", {
        get: function() {
            return this._axisFactor
        },
        set: function(i) {
            this._axisFactor = i;
            for (var o = this._scaleBoxesParent.getChildMeshes(), s = 0, c = 0; c < 3; c++)
                for (var d = 0; d < 3; d++)
                    for (var _ = 0; _ < 3; _++) {
                        var b = (c === 1 ? 1 : 0) + (d === 1 ? 1 : 0) + (_ === 1 ? 1 : 0);
                        if (!(b === 1 || b === 3)) {
                            if (o[s]) {
                                var k = new Vector3(c - 1,d - 1,_ - 1);
                                k.multiplyInPlace(this._axisFactor),
                                o[s].setEnabled(k.lengthSquared() > Epsilon)
                            }
                            s++
                        }
                    }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaleDragSpeed", {
        get: function() {
            return this._scaleDragSpeed
        },
        set: function(i) {
            this._scaleDragSpeed = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setColor = function(i) {
        this.coloredMaterial.emissiveColor = i,
        this.hoverColoredMaterial.emissiveColor = i.clone().add(new Color3(.3,.3,.3)),
        this._lineBoundingBox.getChildren().forEach(function(o) {
            o.color && (o.color = i)
        })
    }
    ,
    e.prototype._attachedNodeChanged = function(i) {
        var o = this;
        if (i) {
            this._anchorMesh.scaling.setAll(1),
            PivotTools._RemoveAndStorePivotPoint(i);
            var s = i.parent;
            this._anchorMesh.addChild(i),
            this._anchorMesh.removeChild(i),
            i.setParent(s),
            PivotTools._RestorePivotPoint(i),
            this.updateBoundingBox(),
            i.getChildMeshes(!1).forEach(function(c) {
                c.markAsDirty("scaling")
            }),
            this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function() {
                o._updateDummy()
            })
        }
    }
    ,
    e.prototype._selectNode = function(i) {
        this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(function(o) {
            o.isVisible = !i || o == i
        })
    }
    ,
    e.prototype.updateBoundingBox = function() {
        if (this.attachedMesh) {
            PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);
            var i = this.attachedMesh.parent;
            this.attachedMesh.setParent(null);
            var o = null;
            this.attachedMesh.skeleton && (o = 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 s = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
            s.max.subtractToRef(s.min, this._boundingDimensions),
            this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),
            this._lineBoundingBox.position.set((s.max.x + s.min.x) / 2, (s.max.y + s.min.y) / 2, (s.max.z + s.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(i),
            this.attachedMesh.skeleton && (this.attachedMesh.skeleton.overrideMesh = o)
        }
        this._updateRotationSpheres(),
        this._updateScaleBoxes(),
        this.attachedMesh && (this._existingMeshScale.copyFrom(this.attachedMesh.scaling),
        PivotTools._RestorePivotPoint(this.attachedMesh))
    }
    ,
    e.prototype._updateRotationSpheres = function() {
        for (var i = this._rotateSpheresParent.getChildMeshes(), o = 0; o < 3; o++)
            for (var s = 0; s < 2; s++)
                for (var c = 0; c < 2; c++) {
                    var d = o * 4 + s * 2 + c;
                    if (o == 0 && (i[d].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * s, this._boundingDimensions.z * c),
                    i[d].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2,-this._boundingDimensions.y / 2,-this._boundingDimensions.z / 2)),
                    i[d].lookAt(Vector3.Cross(i[d].position.normalizeToNew(), Vector3.Right()).normalizeToNew().add(i[d].position))),
                    o == 1 && (i[d].position.set(this._boundingDimensions.x * s, this._boundingDimensions.y / 2, this._boundingDimensions.z * c),
                    i[d].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2,-this._boundingDimensions.y / 2,-this._boundingDimensions.z / 2)),
                    i[d].lookAt(Vector3.Cross(i[d].position.normalizeToNew(), Vector3.Up()).normalizeToNew().add(i[d].position))),
                    o == 2 && (i[d].position.set(this._boundingDimensions.x * s, this._boundingDimensions.y * c, this._boundingDimensions.z / 2),
                    i[d].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2,-this._boundingDimensions.y / 2,-this._boundingDimensions.z / 2)),
                    i[d].lookAt(Vector3.Cross(i[d].position.normalizeToNew(), Vector3.Forward()).normalizeToNew().add(i[d].position))),
                    this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {
                        i[d].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
                        var _ = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
                        i[d].scaling.set(_, _, _)
                    } else
                        this.fixedDragMeshBoundsSize ? i[d].scaling.set(this.rotationSphereSize * this._boundingDimensions.x, this.rotationSphereSize * this._boundingDimensions.y, this.rotationSphereSize * this._boundingDimensions.z) : i[d].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize)
                }
    }
    ,
    e.prototype._updateScaleBoxes = function() {
        for (var i = this._scaleBoxesParent.getChildMeshes(), o = 0, s = 0; s < 3; s++)
            for (var c = 0; c < 3; c++)
                for (var d = 0; d < 3; d++) {
                    var _ = (s === 1 ? 1 : 0) + (c === 1 ? 1 : 0) + (d === 1 ? 1 : 0);
                    if (!(_ === 1 || _ === 3)) {
                        if (i[o])
                            if (i[o].position.set(this._boundingDimensions.x * (s / 2), this._boundingDimensions.y * (c / 2), this._boundingDimensions.z * (d / 2)),
                            i[o].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2,-this._boundingDimensions.y / 2,-this._boundingDimensions.z / 2)),
                            this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {
                                i[o].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
                                var b = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
                                i[o].scaling.set(b, b, b)
                            } else
                                this.fixedDragMeshBoundsSize ? i[o].scaling.set(this.scaleBoxSize * this._boundingDimensions.x, this.scaleBoxSize * this._boundingDimensions.y, this.scaleBoxSize * this._boundingDimensions.z) : i[o].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
                        o++
                    }
                }
    }
    ,
    e.prototype.setEnabledRotationAxis = function(i) {
        this._rotateSpheresParent.getChildMeshes().forEach(function(o, s) {
            s < 4 ? o.setEnabled(i.indexOf("x") != -1) : s < 8 ? o.setEnabled(i.indexOf("y") != -1) : o.setEnabled(i.indexOf("z") != -1)
        })
    }
    ,
    e.prototype.setEnabledScaling = function(i, o) {
        o === void 0 && (o = !1),
        this._scaleBoxesParent.getChildMeshes().forEach(function(s, c) {
            var d = i;
            o && s.metadata === !0 && (d = !1),
            s.setEnabled(d)
        })
    }
    ,
    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(),
        a.prototype.dispose.call(this)
    }
    ,
    e.MakeNotPickableAndWrapInBoundingBox = function(i) {
        var o = function(b) {
            b.isPickable = !1,
            b.getChildMeshes().forEach(function(k) {
                o(k)
            })
        };
        o(i),
        i.rotationQuaternion || (i.rotationQuaternion = Quaternion.RotationYawPitchRoll(i.rotation.y, i.rotation.x, i.rotation.z));
        var s = i.position.clone()
          , c = i.rotationQuaternion.clone();
        i.rotationQuaternion.set(0, 0, 0, 1),
        i.position.set(0, 0, 0);
        var d = CreateBox("box", {
            size: 1
        }, i.getScene())
          , _ = i.getHierarchyBoundingVectors();
        return _.max.subtractToRef(_.min, d.scaling),
        d.scaling.y === 0 && (d.scaling.y = Epsilon),
        d.scaling.x === 0 && (d.scaling.x = Epsilon),
        d.scaling.z === 0 && (d.scaling.z = Epsilon),
        d.position.set((_.max.x + _.min.x) / 2, (_.max.y + _.min.y) / 2, (_.max.z + _.min.z) / 2),
        i.addChild(d),
        i.rotationQuaternion.copyFrom(c),
        i.position.copyFrom(s),
        i.removeChild(d),
        d.addChild(i),
        d.visibility = 0,
        d
    }
    ,
    e.prototype.setCustomMesh = function(i) {
        Logger$2.Error("Custom meshes are not supported on this gizmo")
    }
    ,
    e
}(Gizmo);
(function() {
    function a(e, i, o, s) {
        i === void 0 && (i = 1),
        o === void 0 && (o = UtilityLayerRenderer.DefaultUtilityLayer),
        s === void 0 && (s = 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 = o,
        this._defaultKeepDepthUtilityLayer = s,
        this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = !1,
        this._thickness = i,
        this.gizmos = {
            positionGizmo: null,
            rotationGizmo: null,
            scaleGizmo: null,
            boundingBoxGizmo: null
        };
        var c = this._attachToMeshPointerObserver(e)
          , d = Gizmo.GizmoAxisPointerObserver(this._defaultUtilityLayer, this._gizmoAxisCache);
        this._pointerObservers = [c, d]
    }
    return Object.defineProperty(a.prototype, "keepDepthUtilityLayer", {
        get: function() {
            return this._defaultKeepDepthUtilityLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "utilityLayer", {
        get: function() {
            return this._defaultUtilityLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isHovered", {
        get: function() {
            var e = !1;
            for (var i in this.gizmos) {
                var o = this.gizmos[i];
                if (o && o.isHovered) {
                    e = !0;
                    break
                }
            }
            return e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "scaleRatio", {
        get: function() {
            return this._scaleRatio
        },
        set: function(e) {
            this._scaleRatio = e,
            [this.gizmos.positionGizmo, this.gizmos.rotationGizmo, this.gizmos.scaleGizmo].forEach(function(i) {
                i && (i.scaleRatio = e)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._attachToMeshPointerObserver = function(e) {
        var i = this
          , o = e.onPointerObservable.add(function(s) {
            if (!!i.usePointerToAttachGizmos && s.type == PointerEventTypes.POINTERDOWN)
                if (s.pickInfo && s.pickInfo.pickedMesh) {
                    var c = s.pickInfo.pickedMesh;
                    if (i.attachableMeshes == null)
                        for (; c && c.parent != null; )
                            c = c.parent;
                    else {
                        var d = !1;
                        i.attachableMeshes.forEach(function(_) {
                            c && (c == _ || c.isDescendantOf(_)) && (c = _,
                            d = !0)
                        }),
                        d || (c = null)
                    }
                    c instanceof AbstractMesh ? i._attachedMesh != c && i.attachToMesh(c) : i.clearGizmoOnEmptyPointerEvent && i.attachToMesh(null)
                } else
                    i.clearGizmoOnEmptyPointerEvent && i.attachToMesh(null)
        });
        return o
    }
    ,
    a.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 i in this.gizmos) {
            var o = this.gizmos[i];
            o && this._gizmosEnabled[i] && (o.attachedMesh = e)
        }
        this.boundingBoxGizmoEnabled && this._attachedMesh && this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),
        this.onAttachedToMeshObservable.notifyObservers(e)
    }
    ,
    a.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 i in this.gizmos) {
            var o = this.gizmos[i];
            o && this._gizmosEnabled[i] && (o.attachedNode = e)
        }
        this.boundingBoxGizmoEnabled && this._attachedNode && this._attachedNode.addBehavior(this.boundingBoxDragBehavior),
        this.onAttachedToNodeObservable.notifyObservers(e)
    }
    ,
    Object.defineProperty(a.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(a.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(a.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(a.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
    }),
    a.prototype.addToAxisCache = function(e) {
        var i = this;
        e.size > 0 && e.forEach(function(o, s) {
            i._gizmoAxisCache.set(s, o)
        })
    }
    ,
    a.prototype.dispose = function() {
        var e = this, i, o;
        this._pointerObservers.forEach(function(d) {
            e.scene.onPointerObservable.remove(d)
        });
        for (var s in this.gizmos) {
            var c = this.gizmos[s];
            c && c.dispose()
        }
        this._defaultKeepDepthUtilityLayer !== UtilityLayerRenderer._DefaultKeepDepthUtilityLayer && ((i = this._defaultKeepDepthUtilityLayer) === null || i === void 0 || i.dispose()),
        this._defaultUtilityLayer !== UtilityLayerRenderer._DefaultUtilityLayer && ((o = this._defaultUtilityLayer) === null || o === void 0 || o.dispose()),
        this.boundingBoxDragBehavior.detach(),
        this.onAttachedToMeshObservable.clear()
    }
    ,
    a
}
)();
var LayerSceneComponent = function() {
    function a(e) {
        this.name = SceneComponentConstants.NAME_LAYER,
        this.scene = e,
        this._engine = e.getEngine(),
        e.layers = new Array
    }
    return a.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)
    }
    ,
    a.prototype.rebuild = function() {
        for (var e = this.scene.layers, i = 0, o = e; i < o.length; i++) {
            var s = o[i];
            s._rebuild()
        }
    }
    ,
    a.prototype.dispose = function() {
        for (var e = this.scene.layers; e.length; )
            e[0].dispose()
    }
    ,
    a.prototype._draw = function(e) {
        var i = this.scene.layers;
        if (i.length) {
            this._engine.setDepthBuffer(!1);
            for (var o = 0, s = i; o < s.length; o++) {
                var c = s[o];
                e(c) && c.render()
            }
            this._engine.setDepthBuffer(!0)
        }
    }
    ,
    a.prototype._drawCameraPredicate = function(e, i, o) {
        return !e.renderOnlyInRenderTargetTextures && e.isBackground === i && (e.layerMask & o) !== 0
    }
    ,
    a.prototype._drawCameraBackground = function(e) {
        var i = this;
        this._draw(function(o) {
            return i._drawCameraPredicate(o, !0, e.layerMask)
        })
    }
    ,
    a.prototype._drawCameraForeground = function(e) {
        var i = this;
        this._draw(function(o) {
            return i._drawCameraPredicate(o, !1, e.layerMask)
        })
    }
    ,
    a.prototype._drawRenderTargetPredicate = function(e, i, o, s) {
        return e.renderTargetTextures.length > 0 && e.isBackground === i && e.renderTargetTextures.indexOf(s) > -1 && (e.layerMask & o) !== 0
    }
    ,
    a.prototype._drawRenderTargetBackground = function(e) {
        var i = this;
        this._draw(function(o) {
            return i._drawRenderTargetPredicate(o, !0, i.scene.activeCamera.layerMask, e)
        })
    }
    ,
    a.prototype._drawRenderTargetForeground = function(e) {
        var i = this;
        this._draw(function(o) {
            return i._drawRenderTargetPredicate(o, !1, i.scene.activeCamera.layerMask, e)
        })
    }
    ,
    a.prototype.addFromContainer = function(e) {
        var i = this;
        !e.layers || e.layers.forEach(function(o) {
            i.scene.layers.push(o)
        })
    }
    ,
    a.prototype.removeFromContainer = function(e, i) {
        var o = this;
        i === void 0 && (i = !1),
        e.layers && e.layers.forEach(function(s) {
            var c = o.scene.layers.indexOf(s);
            c !== -1 && o.scene.layers.splice(c, 1),
            i && s.dispose()
        })
    }
    ,
    a
}()
  , name$j = "layerPixelShader"
  , shader$j = `
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$j] = shader$j;
var name$i = "layerVertexShader"
  , shader$i = `
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$i] = shader$i;
var Layer = function() {
    function a(e, i, o, s, c) {
        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 = i ? new Texture(i,o,!0) : null,
        this.isBackground = s === void 0 ? !0 : s,
        this.color = c === void 0 ? new Color4(1,1,1,1) : c,
        this._scene = o || EngineStore.LastCreatedScene;
        var d = this._scene._getComponent(SceneComponentConstants.NAME_LAYER);
        d || (d = new LayerSceneComponent(this._scene),
        this._scene._addComponent(d)),
        this._scene.layers.push(this);
        var _ = this._scene.getEngine();
        this._drawWrapper = new DrawWrapper(_);
        var b = [];
        b.push(1, 1),
        b.push(-1, 1),
        b.push(-1, -1),
        b.push(1, -1);
        var k = new VertexBuffer(_,b,VertexBuffer.PositionKind,!1,!1,2);
        this._vertexBuffers[VertexBuffer.PositionKind] = k,
        this._createIndexBuffer()
    }
    return Object.defineProperty(a.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onBeforeRender", {
        set: function(e) {
            this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),
            this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onAfterRender", {
        set: function(e) {
            this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver),
            this._onAfterRenderObserver = this.onAfterRenderObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._createIndexBuffer = function() {
        var e = this._scene.getEngine()
          , i = [];
        i.push(0),
        i.push(1),
        i.push(2),
        i.push(0),
        i.push(2),
        i.push(3),
        this._indexBuffer = e.createIndexBuffer(i)
    }
    ,
    a.prototype._rebuild = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && e._rebuild(),
        this._createIndexBuffer()
    }
    ,
    a.prototype.render = function() {
        if (!!this.isEnabled) {
            var o = 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 = o.createEffect("layer", [VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], e));
            var i = this._drawWrapper.effect;
            if (!(!i || !i.isReady() || !this.texture || !this.texture.isReady())) {
                var o = this._scene.getEngine();
                this.onBeforeRenderObservable.notifyObservers(this),
                o.enableEffect(this._drawWrapper),
                o.setState(!1),
                i.setTexture("textureSampler", this.texture),
                i.setMatrix("textureMatrix", this.texture.getTextureMatrix()),
                i.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a),
                i.setVector2("offset", this.offset),
                i.setVector2("scale", this.scale),
                o.bindBuffers(this._vertexBuffers, this._indexBuffer, i),
                this.alphaTest ? o.drawElementsType(Material.TriangleFillMode, 0, 6) : (o.setAlphaMode(this.alphaBlendingMode),
                o.drawElementsType(Material.TriangleFillMode, 0, 6),
                o.setAlphaMode(0)),
                this.onAfterRenderObservable.notifyObservers(this)
            }
        }
    }
    ,
    a.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 i = this._scene.layers.indexOf(this);
        this._scene.layers.splice(i, 1),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.onAfterRenderObservable.clear(),
        this.onBeforeRenderObservable.clear()
    }
    ,
    a
}()
  , name$h = "boundingBoxRendererFragmentDeclaration"
  , shader$h = `uniform vec4 color;
`;
ShaderStore.IncludesShadersStore[name$h] = shader$h;
var name$g = "boundingBoxRendererUboDeclaration"
  , shader$g = `layout(std140,column_major) uniform;
uniform BoundingBoxRenderer {
vec4 color;
mat4 world;
mat4 viewProjection;
mat4 viewProjectionR;
};
`;
ShaderStore.IncludesShadersStore[name$g] = shader$g;
var name$f = "boundingBoxRendererPixelShader"
  , shader$f = `#include<__decl__boundingBoxRendererFragment>
void main(void) {
gl_FragColor=color;
}`;
ShaderStore.ShadersStore[name$f] = shader$f;
var name$e = "boundingBoxRendererVertexDeclaration"
  , shader$e = `uniform mat4 world;
uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
`;
ShaderStore.IncludesShadersStore[name$e] = shader$e;
var name$d = "boundingBoxRendererVertexShader"
  , shader$d = `
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$d] = shader$d;
Object.defineProperty(Scene.prototype, "forceShowBoundingBoxes", {
    get: function() {
        return this._forceShowBoundingBoxes || !1
    },
    set: function(a) {
        this._forceShowBoundingBoxes = a,
        a && 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(a) {
        this._showBoundingBox = a,
        a && this.getScene().getBoundingBoxRenderer()
    },
    enumerable: !0,
    configurable: !0
});
var BoundingBoxRenderer = function() {
    function a(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 a.prototype._buildUniformLayout = function(e) {
        e.addUniform("color", 4),
        e.addUniform("world", 16),
        e.addUniform("viewProjection", 16),
        e.addUniform("viewProjectionR", 16),
        e.create()
    }
    ,
    a.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)
    }
    ,
    a.prototype._evaluateSubMesh = function(e, i) {
        if (e.showSubMeshesBoundingBox) {
            var o = i.getBoundingInfo();
            o != null && (o.boundingBox._tag = e.renderingGroupId,
            this.renderList.push(o.boundingBox))
        }
    }
    ,
    a.prototype._preActiveMesh = function(e) {
        if (e.showBoundingBox || this.scene.forceShowBoundingBoxes) {
            var i = e.getBoundingInfo();
            i.boundingBox._tag = e.renderingGroupId,
            this.renderList.push(i.boundingBox)
        }
    }
    ,
    a.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()
              , i = CreateBoxVertexData({
                size: 1
            });
            this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(e,i.positions,VertexBuffer.PositionKind,!1),
            this._createIndexBuffer(),
            this._fillIndexData = i.indices,
            this.onResourcesReadyObservable.notifyObservers(this)
        }
    }
    ,
    a.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])
    }
    ,
    a.prototype.rebuild = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && e._rebuild(),
        this._createIndexBuffer()
    }
    ,
    a.prototype.reset = function() {
        this.renderList.reset()
    }
    ,
    a.prototype.render = function(e) {
        var i, o;
        if (!(this.renderList.length === 0 || !this.enabled) && (this._prepareResources(),
        !!this._colorShader.isReady())) {
            var s = this.scene.getEngine();
            s.setDepthWrite(!1);
            for (var c = this.frontColor.toColor4(), d = this.backColor.toColor4(), _ = this.scene.getTransformMatrix(), b = 0; b < this.renderList.length; b++) {
                var k = this.renderList.data[b];
                if (k._tag === e) {
                    this._createWrappersForBoundingBox(k),
                    this.onBeforeBoxRenderingObservable.notifyObservers(k);
                    var j = k.minimum
                      , $ = k.maximum
                      , _e = $.subtract(j)
                      , et = j.add(_e.scale(.5))
                      , tt = Matrix.Scaling(_e.x, _e.y, _e.z).multiply(Matrix.Translation(et.x, et.y, et.z)).multiply(k.getWorldMatrix())
                      , rt = s.useReverseDepthBuffer;
                    if (this.showBackLines) {
                        var it = (i = k._drawWrapperBack) !== null && i !== void 0 ? i : this._colorShader._getDrawWrapper();
                        this._colorShader._preBind(it),
                        s.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()),
                        rt ? s.setDepthFunctionToLessOrEqual() : s.setDepthFunctionToGreaterOrEqual(),
                        this._uniformBufferBack.bindToEffect(it.effect, "BoundingBoxRenderer"),
                        this._uniformBufferBack.updateDirectColor4("color", d),
                        this._uniformBufferBack.updateMatrix("world", tt),
                        this._uniformBufferBack.updateMatrix("viewProjection", _),
                        this._uniformBufferBack.update(),
                        s.drawElementsType(Material.LineListDrawMode, 0, 24)
                    }
                    var nt = (o = k._drawWrapperFront) !== null && o !== void 0 ? o : this._colorShader._getDrawWrapper();
                    this._colorShader._preBind(nt),
                    s.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()),
                    rt ? s.setDepthFunctionToGreater() : s.setDepthFunctionToLess(),
                    this._uniformBufferFront.bindToEffect(nt.effect, "BoundingBoxRenderer"),
                    this._uniformBufferFront.updateDirectColor4("color", c),
                    this._uniformBufferFront.updateMatrix("world", tt),
                    this._uniformBufferFront.updateMatrix("viewProjection", _),
                    this._uniformBufferFront.update(),
                    s.drawElementsType(Material.LineListDrawMode, 0, 24),
                    this.onAfterBoxRenderingObservable.notifyObservers(k)
                }
            }
            this._colorShader.unbind(),
            s.setDepthFunctionToLessOrEqual(),
            s.setDepthWrite(!0)
        }
    }
    ,
    a.prototype._createWrappersForBoundingBox = function(e) {
        if (!e._drawWrapperFront) {
            var i = this.scene.getEngine();
            e._drawWrapperFront = new DrawWrapper(i),
            e._drawWrapperBack = new DrawWrapper(i),
            e._drawWrapperFront.setEffect(this._colorShader.getEffect()),
            e._drawWrapperBack.setEffect(this._colorShader.getEffect())
        }
    }
    ,
    a.prototype.renderOcclusionBoundingBox = function(e) {
        var i = this.scene.getEngine();
        this._renderPassIdForOcclusionQuery === void 0 && (this._renderPassIdForOcclusionQuery = i.createRenderPassId("Render pass for occlusion query"));
        var o = i.currentRenderPassId;
        i.currentRenderPassId = this._renderPassIdForOcclusionQuery,
        this._prepareResources();
        var s = e.subMeshes[0];
        if (!this._colorShaderForOcclusionQuery.isReady(e, void 0, s) || !e.hasBoundingInfo) {
            i.currentRenderPassId = o;
            return
        }
        this._fillIndexBuffer || (this._fillIndexBuffer = i.createIndexBuffer(this._fillIndexData));
        var c = i.useReverseDepthBuffer;
        i.setDepthWrite(!1),
        i.setColorWrite(!1);
        var d = e.getBoundingInfo().boundingBox
          , _ = d.minimum
          , b = d.maximum
          , k = b.subtract(_)
          , j = _.add(k.scale(.5))
          , $ = Matrix.Scaling(k.x, k.y, k.z).multiply(Matrix.Translation(j.x, j.y, j.z)).multiply(d.getWorldMatrix())
          , _e = s._drawWrapper;
        this._colorShaderForOcclusionQuery._preBind(_e),
        i.bindBuffers(this._vertexBuffers, this._fillIndexBuffer, _e.effect),
        c ? i.setDepthFunctionToGreater() : i.setDepthFunctionToLess(),
        this.scene.resetCachedMaterial(),
        this._uniformBufferFront.bindToEffect(_e.effect, "BoundingBoxRenderer"),
        this._uniformBufferFront.updateMatrix("world", $),
        this._uniformBufferFront.updateMatrix("viewProjection", this.scene.getTransformMatrix()),
        this._uniformBufferFront.update(),
        i.drawElementsType(Material.TriangleFillMode, 0, 36),
        this._colorShaderForOcclusionQuery.unbind(),
        i.setDepthFunctionToLessOrEqual(),
        i.setDepthWrite(!0),
        i.setColorWrite(!0),
        i.currentRenderPassId = o
    }
    ,
    a.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)
        }
    }
    ,
    a
}()
  , DataReader = function() {
    function a(e) {
        this.byteOffset = 0,
        this.buffer = e
    }
    return a.prototype.loadAsync = function(e) {
        var i = this;
        return this.buffer.readAsync(this.byteOffset, e).then(function(o) {
            i._dataView = new DataView(o.buffer,o.byteOffset,o.byteLength),
            i._dataByteOffset = 0
        })
    }
    ,
    a.prototype.readUint32 = function() {
        var e = this._dataView.getUint32(this._dataByteOffset, !0);
        return this._dataByteOffset += 4,
        this.byteOffset += 4,
        e
    }
    ,
    a.prototype.readUint8Array = function(e) {
        var i = new Uint8Array(this._dataView.buffer,this._dataView.byteOffset + this._dataByteOffset,e);
        return this._dataByteOffset += e,
        this.byteOffset += e,
        i
    }
    ,
    a.prototype.readString = function(e) {
        return Decode(this.readUint8Array(e))
    }
    ,
    a.prototype.skipBytes = function(e) {
        this._dataByteOffset += e,
        this.byteOffset += e
    }
    ,
    a
}();
function validateAsync(a, e, i, o) {
    var s = {
        externalResourceFunction: function(c) {
            return o(c).then(function(d) {
                return new Uint8Array(d)
            })
        }
    };
    return i && (s.uri = e === "file:" ? i : e + i),
    a instanceof ArrayBuffer ? GLTFValidator.validateBytes(new Uint8Array(a), s) : GLTFValidator.validateString(a, s)
}
function workerFunc$1() {
    var a = [];
    onmessage = function(e) {
        var i = e.data;
        switch (i.id) {
        case "init":
            {
                importScripts(i.url);
                break
            }
        case "validate":
            {
                validateAsync(i.data, i.rootUrl, i.fileName, function(o) {
                    return new Promise(function(s, c) {
                        var d = a.length;
                        a.push({
                            resolve: s,
                            reject: c
                        }),
                        postMessage({
                            id: "getExternalResource",
                            index: d,
                            uri: o
                        })
                    }
                    )
                }).then(function(o) {
                    postMessage({
                        id: "validate.resolve",
                        value: o
                    })
                }, function(o) {
                    postMessage({
                        id: "validate.reject",
                        reason: o
                    })
                });
                break
            }
        case "getExternalResource.resolve":
            {
                a[i.index].resolve(i.value);
                break
            }
        case "getExternalResource.reject":
            {
                a[i.index].reject(i.reason);
                break
            }
        }
    }
}
var GLTFValidation = function() {
    function a() {}
    return a.ValidateAsync = function(e, i, o, s) {
        var c = this;
        return typeof Worker == "function" ? new Promise(function(d, _) {
            var b = validateAsync + "(" + workerFunc$1 + ")()"
              , k = URL.createObjectURL(new Blob([b],{
                type: "application/javascript"
            }))
              , j = new Worker(k)
              , $ = function(et) {
                j.removeEventListener("error", $),
                j.removeEventListener("message", _e),
                _(et)
            }
              , _e = function(et) {
                var tt = et.data;
                switch (tt.id) {
                case "getExternalResource":
                    {
                        s(tt.uri).then(function(rt) {
                            j.postMessage({
                                id: "getExternalResource.resolve",
                                index: tt.index,
                                value: rt
                            }, [rt])
                        }, function(rt) {
                            j.postMessage({
                                id: "getExternalResource.reject",
                                index: tt.index,
                                reason: rt
                            })
                        });
                        break
                    }
                case "validate.resolve":
                    {
                        j.removeEventListener("error", $),
                        j.removeEventListener("message", _e),
                        d(tt.value);
                        break
                    }
                case "validate.reject":
                    j.removeEventListener("error", $),
                    j.removeEventListener("message", _e),
                    _(tt.reason)
                }
            };
            j.addEventListener("error", $),
            j.addEventListener("message", _e),
            j.postMessage({
                id: "init",
                url: c.Configuration.url
            }),
            j.postMessage({
                id: "validate",
                data: e,
                rootUrl: i,
                fileName: o
            })
        }
        ) : (this._LoadScriptPromise || (this._LoadScriptPromise = Tools.LoadScriptAsync(this.Configuration.url)),
        this._LoadScriptPromise.then(function() {
            return validateAsync(e, i, o, s)
        }))
    }
    ,
    a.Configuration = {
        url: "https://preview.babylonjs.com/gltf_validator.js"
    },
    a
}();
function readAsync(a, e, i) {
    try {
        return Promise.resolve(new Uint8Array(a,e,i))
    } catch (o) {
        return Promise.reject(o)
    }
}
var GLTFLoaderCoordinateSystemMode;
(function(a) {
    a[a.AUTO = 0] = "AUTO",
    a[a.FORCE_RIGHT_HANDED = 1] = "FORCE_RIGHT_HANDED"
}
)(GLTFLoaderCoordinateSystemMode || (GLTFLoaderCoordinateSystemMode = {}));
var GLTFLoaderAnimationStartMode;
(function(a) {
    a[a.NONE = 0] = "NONE",
    a[a.FIRST = 1] = "FIRST",
    a[a.ALL = 2] = "ALL"
}
)(GLTFLoaderAnimationStartMode || (GLTFLoaderAnimationStartMode = {}));
var GLTFLoaderState;
(function(a) {
    a[a.LOADING = 0] = "LOADING",
    a[a.READY = 1] = "READY",
    a[a.COMPLETE = 2] = "COMPLETE"
}
)(GLTFLoaderState || (GLTFLoaderState = {}));
var GLTFFileLoader = function() {
    function a() {
        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(a.prototype, "onParsed", {
        set: function(e) {
            this._onParsedObserver && this.onParsedObservable.remove(this._onParsedObserver),
            this._onParsedObserver = this.onParsedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onMeshLoaded", {
        set: function(e) {
            this._onMeshLoadedObserver && this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),
            this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onTextureLoaded", {
        set: function(e) {
            this._onTextureLoadedObserver && this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),
            this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onMaterialLoaded", {
        set: function(e) {
            this._onMaterialLoadedObserver && this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),
            this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onCameraLoaded", {
        set: function(e) {
            this._onCameraLoadedObserver && this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),
            this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onComplete", {
        set: function(e) {
            this._onCompleteObserver && this.onCompleteObservable.remove(this._onCompleteObserver),
            this._onCompleteObserver = this.onCompleteObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onError", {
        set: function(e) {
            this._onErrorObserver && this.onErrorObservable.remove(this._onErrorObserver),
            this._onErrorObserver = this.onErrorObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onExtensionLoaded", {
        set: function(e) {
            this._onExtensionLoadedObserver && this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),
            this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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(a.prototype, "onValidated", {
        set: function(e) {
            this._onValidatedObserver && this.onValidatedObservable.remove(this._onValidatedObserver),
            this._onValidatedObserver = this.onValidatedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.dispose = function() {
        this._loader && (this._loader.dispose(),
        this._loader = null);
        for (var e = 0, i = this._requests; e < i.length; e++) {
            var o = i[e];
            o.abort()
        }
        this._requests.length = 0,
        delete this._progressCallback,
        this.preprocessUrlAsync = function(s) {
            return Promise.resolve(s)
        }
        ,
        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()
    }
    ,
    a.prototype.loadFile = function(e, i, o, s, c, d) {
        var _ = this;
        if (this._progressCallback = s,
        c) {
            if (this.useRangeRequests) {
                this.validate && Logger$2.Warn("glTF validation is not supported when range requests are enabled");
                var b = {
                    abort: function() {},
                    onCompleteObservable: new Observable
                }
                  , k = {
                    readAsync: function(j, $) {
                        return new Promise(function(_e, et) {
                            _._loadFile(e, i, function(tt) {
                                _e(new Uint8Array(tt))
                            }, !0, function(tt) {
                                et(tt)
                            }, function(tt) {
                                tt.setRequestHeader("Range", "bytes=" + j + "-" + (j + $ - 1))
                            })
                        }
                        )
                    },
                    byteLength: 0
                };
                return this._unpackBinaryAsync(new DataReader(k)).then(function(j) {
                    b.onCompleteObservable.notifyObservers(b),
                    o(j)
                }, d ? function(j) {
                    return d(void 0, j)
                }
                : void 0),
                b
            }
            return this._loadFile(e, i, function(j) {
                var $ = j;
                _._unpackBinaryAsync(new DataReader({
                    readAsync: function(_e, et) {
                        return readAsync($, _e, et)
                    },
                    byteLength: $.byteLength
                })).then(function(_e) {
                    o(_e)
                }, d ? function(_e) {
                    return d(void 0, _e)
                }
                : void 0)
            }, !0, d)
        }
        return this._loadFile(e, i, function(j) {
            if (i.name)
                _._validate(e, j, "file:", i.name);
            else {
                var $ = i;
                _._validate(e, j, Tools.GetFolderPath($), Tools.GetFilename($))
            }
            o({
                json: _._parseJson(j)
            })
        }, c, d)
    }
    ,
    a.prototype.importMeshAsync = function(e, i, o, s, c, d) {
        var _ = this;
        return Promise.resolve().then(function() {
            return _.onParsedObservable.notifyObservers(o),
            _.onParsedObservable.clear(),
            _._log("Loading " + (d || "")),
            _._loader = _._getLoader(o),
            _._loader.importMeshAsync(e, i, null, o, s, c, d)
        })
    }
    ,
    a.prototype.loadAsync = function(e, i, o, s, c) {
        var d = this;
        return Promise.resolve().then(function() {
            return d.onParsedObservable.notifyObservers(i),
            d.onParsedObservable.clear(),
            d._log("Loading " + (c || "")),
            d._loader = d._getLoader(i),
            d._loader.loadAsync(e, i, o, s, c)
        })
    }
    ,
    a.prototype.loadAssetContainerAsync = function(e, i, o, s, c) {
        var d = this;
        return Promise.resolve().then(function() {
            d.onParsedObservable.notifyObservers(i),
            d.onParsedObservable.clear(),
            d._log("Loading " + (c || "")),
            d._loader = d._getLoader(i);
            var _ = new AssetContainer(e)
              , b = [];
            d.onMaterialLoadedObservable.add(function($) {
                b.push($)
            });
            var k = [];
            d.onTextureLoadedObservable.add(function($) {
                k.push($)
            });
            var j = [];
            return d.onCameraLoadedObservable.add(function($) {
                j.push($)
            }),
            d._loader.importMeshAsync(null, e, _, i, o, s, c).then(function($) {
                return Array.prototype.push.apply(_.geometries, $.geometries),
                Array.prototype.push.apply(_.meshes, $.meshes),
                Array.prototype.push.apply(_.particleSystems, $.particleSystems),
                Array.prototype.push.apply(_.skeletons, $.skeletons),
                Array.prototype.push.apply(_.animationGroups, $.animationGroups),
                Array.prototype.push.apply(_.materials, b),
                Array.prototype.push.apply(_.textures, k),
                Array.prototype.push.apply(_.lights, $.lights),
                Array.prototype.push.apply(_.transformNodes, $.transformNodes),
                Array.prototype.push.apply(_.cameras, j),
                _
            })
        })
    }
    ,
    a.prototype.canDirectLoad = function(e) {
        return e.indexOf("asset") !== -1 && e.indexOf("version") !== -1 || StringTools.StartsWith(e, "data:base64," + a.magicBase64Encoded) || StringTools.StartsWith(e, "data:;base64," + a.magicBase64Encoded) || StringTools.StartsWith(e, "data:application/octet-stream;base64," + a.magicBase64Encoded) || StringTools.StartsWith(e, "data:model/gltf-binary;base64," + a.magicBase64Encoded)
    }
    ,
    a.prototype.directLoad = function(e, i) {
        if (StringTools.StartsWith(i, "base64," + a.magicBase64Encoded) || StringTools.StartsWith(i, ";base64," + a.magicBase64Encoded) || StringTools.StartsWith(i, "application/octet-stream;base64," + a.magicBase64Encoded) || StringTools.StartsWith(i, "model/gltf-binary;base64," + a.magicBase64Encoded)) {
            var o = DecodeBase64UrlToBinary(i);
            return this._validate(e, o),
            this._unpackBinaryAsync(new DataReader({
                readAsync: function(s, c) {
                    return readAsync(o, s, c)
                },
                byteLength: o.byteLength
            }))
        }
        return this._validate(e, i),
        Promise.resolve({
            json: this._parseJson(i)
        })
    }
    ,
    a.prototype.createPlugin = function() {
        return new a
    }
    ,
    Object.defineProperty(a.prototype, "loaderState", {
        get: function() {
            return this._state
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.whenCompleteAsync = function() {
        var e = this;
        return new Promise(function(i, o) {
            e.onCompleteObservable.addOnce(function() {
                i()
            }),
            e.onErrorObservable.addOnce(function(s) {
                o(s)
            })
        }
        )
    }
    ,
    a.prototype._setState = function(e) {
        this._state !== e && (this._state = e,
        this.onLoaderStateChangedObservable.notifyObservers(this._state),
        this._log(GLTFLoaderState[this._state]))
    }
    ,
    a.prototype._loadFile = function(e, i, o, s, c, d) {
        var _ = this
          , b = e._loadFile(i, o, function(k) {
            _._onProgress(k, b)
        }, !0, s, c, d);
        return b.onCompleteObservable.add(function(k) {
            _._requests.splice(_._requests.indexOf(k), 1)
        }),
        this._requests.push(b),
        b
    }
    ,
    a.prototype._onProgress = function(e, i) {
        if (!!this._progressCallback) {
            i._lengthComputable = e.lengthComputable,
            i._loaded = e.loaded,
            i._total = e.total;
            for (var o = !0, s = 0, c = 0, d = 0, _ = this._requests; d < _.length; d++) {
                var b = _[d];
                if (b._lengthComputable === void 0 || b._loaded === void 0 || b._total === void 0)
                    return;
                o = o && b._lengthComputable,
                s += b._loaded,
                c += b._total
            }
            this._progressCallback({
                lengthComputable: o,
                loaded: s,
                total: o ? c : 0
            })
        }
    }
    ,
    a.prototype._validate = function(e, i, o, s) {
        var c = this;
        o === void 0 && (o = ""),
        s === void 0 && (s = ""),
        this.validate && (this._startPerformanceCounter("Validate JSON"),
        GLTFValidation.ValidateAsync(i, o, s, function(d) {
            return c.preprocessUrlAsync(o + d).then(function(_) {
                return e._loadFileAsync(_, void 0, !0, !0)
            })
        }).then(function(d) {
            c._endPerformanceCounter("Validate JSON"),
            c.onValidatedObservable.notifyObservers(d),
            c.onValidatedObservable.clear()
        }, function(d) {
            c._endPerformanceCounter("Validate JSON"),
            Tools.Warn("Failed to validate: " + d.message),
            c.onValidatedObservable.clear()
        }))
    }
    ,
    a.prototype._getLoader = function(e) {
        var i = e.json.asset || {};
        this._log("Asset version: " + i.version),
        i.minVersion && this._log("Asset minimum version: " + i.minVersion),
        i.generator && this._log("Asset generator: " + i.generator);
        var o = a._parseVersion(i.version);
        if (!o)
            throw new Error("Invalid version: " + i.version);
        if (i.minVersion !== void 0) {
            var s = a._parseVersion(i.minVersion);
            if (!s)
                throw new Error("Invalid minimum version: " + i.minVersion);
            if (a._compareVersion(s, {
                major: 2,
                minor: 0
            }) > 0)
                throw new Error("Incompatible minimum version: " + i.minVersion)
        }
        var c = {
            1: a._CreateGLTF1Loader,
            2: a._CreateGLTF2Loader
        }
          , d = c[o.major];
        if (!d)
            throw new Error("Unsupported version: " + i.version);
        return d(this)
    }
    ,
    a.prototype._parseJson = function(e) {
        this._startPerformanceCounter("Parse JSON"),
        this._log("JSON length: " + e.length);
        var i = JSON.parse(e);
        return this._endPerformanceCounter("Parse JSON"),
        i
    }
    ,
    a.prototype._unpackBinaryAsync = function(e) {
        var i = this;
        return this._startPerformanceCounter("Unpack Binary"),
        e.loadAsync(20).then(function() {
            var o = {
                Magic: 1179937895
            }
              , s = e.readUint32();
            if (s !== o.Magic)
                throw new Error("Unexpected magic: " + s);
            var c = e.readUint32();
            i.loggingEnabled && i._log("Binary version: " + c);
            var d = e.readUint32();
            if (e.buffer.byteLength !== 0 && d !== e.buffer.byteLength)
                throw new Error("Length in header does not match actual data length: " + d + " != " + e.buffer.byteLength);
            var _;
            switch (c) {
            case 1:
                {
                    _ = i._unpackBinaryV1Async(e, d);
                    break
                }
            case 2:
                {
                    _ = i._unpackBinaryV2Async(e, d);
                    break
                }
            default:
                throw new Error("Unsupported version: " + c)
            }
            return i._endPerformanceCounter("Unpack Binary"),
            _
        })
    }
    ,
    a.prototype._unpackBinaryV1Async = function(e, i) {
        var o = {
            JSON: 0
        }
          , s = e.readUint32()
          , c = e.readUint32();
        if (c !== o.JSON)
            throw new Error("Unexpected content format: " + c);
        var d = i - e.byteOffset
          , _ = {
            json: this._parseJson(e.readString(s)),
            bin: null
        };
        if (d !== 0) {
            var b = e.byteOffset;
            _.bin = {
                readAsync: function(k, j) {
                    return e.buffer.readAsync(b + k, j)
                },
                byteLength: d
            }
        }
        return Promise.resolve(_)
    }
    ,
    a.prototype._unpackBinaryV2Async = function(e, i) {
        var o = this
          , s = {
            JSON: 1313821514,
            BIN: 5130562
        }
          , c = e.readUint32()
          , d = e.readUint32();
        if (d !== s.JSON)
            throw new Error("First chunk format is not JSON");
        return e.byteOffset + c === i ? e.loadAsync(c).then(function() {
            return {
                json: o._parseJson(e.readString(c)),
                bin: null
            }
        }) : e.loadAsync(c + 8).then(function() {
            var _ = {
                json: o._parseJson(e.readString(c)),
                bin: null
            }
              , b = function() {
                var k = e.readUint32()
                  , j = e.readUint32();
                switch (j) {
                case s.JSON:
                    throw new Error("Unexpected JSON chunk");
                case s.BIN:
                    {
                        var $ = e.byteOffset;
                        _.bin = {
                            readAsync: function(_e, et) {
                                return e.buffer.readAsync($ + _e, et)
                            },
                            byteLength: k
                        },
                        e.skipBytes(k);
                        break
                    }
                default:
                    {
                        e.skipBytes(k);
                        break
                    }
                }
                return e.byteOffset !== i ? e.loadAsync(8).then(b) : Promise.resolve(_)
            };
            return b()
        })
    }
    ,
    a._parseVersion = function(e) {
        if (e === "1.0" || e === "1.0.1")
            return {
                major: 1,
                minor: 0
            };
        var i = (e + "").match(/^(\d+)\.(\d+)/);
        return i ? {
            major: parseInt(i[1]),
            minor: parseInt(i[2])
        } : null
    }
    ,
    a._compareVersion = function(e, i) {
        return e.major > i.major ? 1 : e.major < i.major ? -1 : e.minor > i.minor ? 1 : e.minor < i.minor ? -1 : 0
    }
    ,
    a.prototype._logOpen = function(e) {
        this._log(e),
        this._logIndentLevel++
    }
    ,
    a.prototype._logClose = function() {
        --this._logIndentLevel
    }
    ,
    a.prototype._logEnabled = function(e) {
        var i = a._logSpaces.substr(0, this._logIndentLevel * 2);
        Logger$2.Log("" + i + e)
    }
    ,
    a.prototype._logDisabled = function(e) {}
    ,
    a.prototype._startPerformanceCounterEnabled = function(e) {
        Tools.StartPerformanceCounter(e)
    }
    ,
    a.prototype._startPerformanceCounterDisabled = function(e) {}
    ,
    a.prototype._endPerformanceCounterEnabled = function(e) {
        Tools.EndPerformanceCounter(e)
    }
    ,
    a.prototype._endPerformanceCounterDisabled = function(e) {}
    ,
    a.IncrementalLoading = !0,
    a.HomogeneousCoordinates = !1,
    a.magicBase64Encoded = "Z2xURg",
    a._logSpaces = "                                ",
    a
}();
SceneLoader && SceneLoader.RegisterPlugin(new GLTFFileLoader);
var EComponentType;
(function(a) {
    a[a.BYTE = 5120] = "BYTE",
    a[a.UNSIGNED_BYTE = 5121] = "UNSIGNED_BYTE",
    a[a.SHORT = 5122] = "SHORT",
    a[a.UNSIGNED_SHORT = 5123] = "UNSIGNED_SHORT",
    a[a.FLOAT = 5126] = "FLOAT"
}
)(EComponentType || (EComponentType = {}));
var EShaderType;
(function(a) {
    a[a.FRAGMENT = 35632] = "FRAGMENT",
    a[a.VERTEX = 35633] = "VERTEX"
}
)(EShaderType || (EShaderType = {}));
var EParameterType;
(function(a) {
    a[a.BYTE = 5120] = "BYTE",
    a[a.UNSIGNED_BYTE = 5121] = "UNSIGNED_BYTE",
    a[a.SHORT = 5122] = "SHORT",
    a[a.UNSIGNED_SHORT = 5123] = "UNSIGNED_SHORT",
    a[a.INT = 5124] = "INT",
    a[a.UNSIGNED_INT = 5125] = "UNSIGNED_INT",
    a[a.FLOAT = 5126] = "FLOAT",
    a[a.FLOAT_VEC2 = 35664] = "FLOAT_VEC2",
    a[a.FLOAT_VEC3 = 35665] = "FLOAT_VEC3",
    a[a.FLOAT_VEC4 = 35666] = "FLOAT_VEC4",
    a[a.INT_VEC2 = 35667] = "INT_VEC2",
    a[a.INT_VEC3 = 35668] = "INT_VEC3",
    a[a.INT_VEC4 = 35669] = "INT_VEC4",
    a[a.BOOL = 35670] = "BOOL",
    a[a.BOOL_VEC2 = 35671] = "BOOL_VEC2",
    a[a.BOOL_VEC3 = 35672] = "BOOL_VEC3",
    a[a.BOOL_VEC4 = 35673] = "BOOL_VEC4",
    a[a.FLOAT_MAT2 = 35674] = "FLOAT_MAT2",
    a[a.FLOAT_MAT3 = 35675] = "FLOAT_MAT3",
    a[a.FLOAT_MAT4 = 35676] = "FLOAT_MAT4",
    a[a.SAMPLER_2D = 35678] = "SAMPLER_2D"
}
)(EParameterType || (EParameterType = {}));
var ETextureWrapMode;
(function(a) {
    a[a.CLAMP_TO_EDGE = 33071] = "CLAMP_TO_EDGE",
    a[a.MIRRORED_REPEAT = 33648] = "MIRRORED_REPEAT",
    a[a.REPEAT = 10497] = "REPEAT"
}
)(ETextureWrapMode || (ETextureWrapMode = {}));
var ETextureFilterType;
(function(a) {
    a[a.NEAREST = 9728] = "NEAREST",
    a[a.LINEAR = 9728] = "LINEAR",
    a[a.NEAREST_MIPMAP_NEAREST = 9984] = "NEAREST_MIPMAP_NEAREST",
    a[a.LINEAR_MIPMAP_NEAREST = 9985] = "LINEAR_MIPMAP_NEAREST",
    a[a.NEAREST_MIPMAP_LINEAR = 9986] = "NEAREST_MIPMAP_LINEAR",
    a[a.LINEAR_MIPMAP_LINEAR = 9987] = "LINEAR_MIPMAP_LINEAR"
}
)(ETextureFilterType || (ETextureFilterType = {}));
var ETextureFormat;
(function(a) {
    a[a.ALPHA = 6406] = "ALPHA",
    a[a.RGB = 6407] = "RGB",
    a[a.RGBA = 6408] = "RGBA",
    a[a.LUMINANCE = 6409] = "LUMINANCE",
    a[a.LUMINANCE_ALPHA = 6410] = "LUMINANCE_ALPHA"
}
)(ETextureFormat || (ETextureFormat = {}));
var ECullingType;
(function(a) {
    a[a.FRONT = 1028] = "FRONT",
    a[a.BACK = 1029] = "BACK",
    a[a.FRONT_AND_BACK = 1032] = "FRONT_AND_BACK"
}
)(ECullingType || (ECullingType = {}));
var EBlendingFunction;
(function(a) {
    a[a.ZERO = 0] = "ZERO",
    a[a.ONE = 1] = "ONE",
    a[a.SRC_COLOR = 768] = "SRC_COLOR",
    a[a.ONE_MINUS_SRC_COLOR = 769] = "ONE_MINUS_SRC_COLOR",
    a[a.DST_COLOR = 774] = "DST_COLOR",
    a[a.ONE_MINUS_DST_COLOR = 775] = "ONE_MINUS_DST_COLOR",
    a[a.SRC_ALPHA = 770] = "SRC_ALPHA",
    a[a.ONE_MINUS_SRC_ALPHA = 771] = "ONE_MINUS_SRC_ALPHA",
    a[a.DST_ALPHA = 772] = "DST_ALPHA",
    a[a.ONE_MINUS_DST_ALPHA = 773] = "ONE_MINUS_DST_ALPHA",
    a[a.CONSTANT_COLOR = 32769] = "CONSTANT_COLOR",
    a[a.ONE_MINUS_CONSTANT_COLOR = 32770] = "ONE_MINUS_CONSTANT_COLOR",
    a[a.CONSTANT_ALPHA = 32771] = "CONSTANT_ALPHA",
    a[a.ONE_MINUS_CONSTANT_ALPHA = 32772] = "ONE_MINUS_CONSTANT_ALPHA",
    a[a.SRC_ALPHA_SATURATE = 776] = "SRC_ALPHA_SATURATE"
}
)(EBlendingFunction || (EBlendingFunction = {}));
var GLTFUtils = function() {
    function a() {}
    return a.SetMatrix = function(e, i, o, s, c) {
        var d = null;
        if (o.semantic === "MODEL")
            d = i.getWorldMatrix();
        else if (o.semantic === "PROJECTION")
            d = e.getProjectionMatrix();
        else if (o.semantic === "VIEW")
            d = e.getViewMatrix();
        else if (o.semantic === "MODELVIEWINVERSETRANSPOSE")
            d = Matrix.Transpose(i.getWorldMatrix().multiply(e.getViewMatrix()).invert());
        else if (o.semantic === "MODELVIEW")
            d = i.getWorldMatrix().multiply(e.getViewMatrix());
        else if (o.semantic === "MODELVIEWPROJECTION")
            d = i.getWorldMatrix().multiply(e.getTransformMatrix());
        else if (o.semantic === "MODELINVERSE")
            d = i.getWorldMatrix().invert();
        else if (o.semantic === "VIEWINVERSE")
            d = e.getViewMatrix().invert();
        else if (o.semantic === "PROJECTIONINVERSE")
            d = e.getProjectionMatrix().invert();
        else if (o.semantic === "MODELVIEWINVERSE")
            d = i.getWorldMatrix().multiply(e.getViewMatrix()).invert();
        else if (o.semantic === "MODELVIEWPROJECTIONINVERSE")
            d = i.getWorldMatrix().multiply(e.getTransformMatrix()).invert();
        else if (o.semantic === "MODELINVERSETRANSPOSE")
            d = Matrix.Transpose(i.getWorldMatrix().invert());
        else
            debugger ;if (d)
            switch (o.type) {
            case EParameterType.FLOAT_MAT2:
                c.setMatrix2x2(s, Matrix.GetAsMatrix2x2(d));
                break;
            case EParameterType.FLOAT_MAT3:
                c.setMatrix3x3(s, Matrix.GetAsMatrix3x3(d));
                break;
            case EParameterType.FLOAT_MAT4:
                c.setMatrix(s, d);
                break
            }
    }
    ,
    a.SetUniform = function(e, i, o, s) {
        switch (s) {
        case EParameterType.FLOAT:
            return e.setFloat(i, o),
            !0;
        case EParameterType.FLOAT_VEC2:
            return e.setVector2(i, Vector2.FromArray(o)),
            !0;
        case EParameterType.FLOAT_VEC3:
            return e.setVector3(i, Vector3.FromArray(o)),
            !0;
        case EParameterType.FLOAT_VEC4:
            return e.setVector4(i, Vector4.FromArray(o)),
            !0;
        default:
            return !1
        }
    }
    ,
    a.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
        }
    }
    ,
    a.GetByteStrideFromType = function(e) {
        var i = e.type;
        switch (i) {
        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
        }
    }
    ,
    a.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
        }
    }
    ,
    a.GetBufferFromBufferView = function(e, i, d, s, c) {
        var d = i.byteOffset + d
          , _ = e.loadedBufferViews[i.buffer];
        if (d + s > _.byteLength)
            throw new Error("Buffer access is out of range");
        var b = _.buffer;
        switch (d += _.byteOffset,
        c) {
        case EComponentType.BYTE:
            return new Int8Array(b,d,s);
        case EComponentType.UNSIGNED_BYTE:
            return new Uint8Array(b,d,s);
        case EComponentType.SHORT:
            return new Int16Array(b,d,s);
        case EComponentType.UNSIGNED_SHORT:
            return new Uint16Array(b,d,s);
        default:
            return new Float32Array(b,d,s)
        }
    }
    ,
    a.GetBufferFromAccessor = function(e, i) {
        var o = e.bufferViews[i.bufferView]
          , s = i.count * a.GetByteStrideFromType(i);
        return a.GetBufferFromBufferView(e, o, i.byteOffset, s, i.componentType)
    }
    ,
    a.DecodeBufferToText = function(e) {
        for (var i = "", o = e.byteLength, s = 0; s < o; ++s)
            i += String.fromCharCode(e[s]);
        return i
    }
    ,
    a.GetDefaultMaterial = function(e) {
        if (!a._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 i = {
                vertex: "GLTFDefaultMaterial",
                fragment: "GLTFDefaultMaterial"
            }
              , o = {
                attributes: ["position"],
                uniforms: ["worldView", "projection", "u_emission"],
                samplers: new Array,
                needAlphaBlending: !1
            };
            a._DefaultMaterial = new ShaderMaterial("GLTFDefaultMaterial",e,i,o),
            a._DefaultMaterial.setColor4("u_emission", new Color4(.5,.5,.5,1))
        }
        return a._DefaultMaterial
    }
    ,
    a._DefaultMaterial = null,
    a
}(), ETokenType;
(function(a) {
    a[a.IDENTIFIER = 1] = "IDENTIFIER",
    a[a.UNKNOWN = 2] = "UNKNOWN",
    a[a.END_OF_INPUT = 3] = "END_OF_INPUT"
}
)(ETokenType || (ETokenType = {}));
var Tokenizer = function() {
    function a(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 a.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
    }
    ,
    a.prototype.peek = function() {
        return this._toParse[this._pos]
    }
    ,
    a.prototype.read = function() {
        return this._toParse[this._pos++]
    }
    ,
    a.prototype.forward = function() {
        this._pos++
    }
    ,
    a.prototype.isEnd = function() {
        return this._pos >= this._maxPos
    }
    ,
    a
}()
  , glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"]
  , babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"]
  , glTFAnimationPaths = ["translation", "rotation", "scale"]
  , babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"]
  , parseBuffers = function(a, e) {
    for (var i in a) {
        var o = a[i];
        e.buffers[i] = o,
        e.buffersCount++
    }
}
  , parseShaders = function(a, e) {
    for (var i in a) {
        var o = a[i];
        e.shaders[i] = o,
        e.shaderscount++
    }
}
  , parseObject = function(a, e, i) {
    for (var o in a) {
        var s = a[o];
        i[e][o] = s
    }
}
  , normalizeUVs = function(a) {
    if (!!a)
        for (var e = 0; e < a.length / 2; e++)
            a[e * 2 + 1] = 1 - a[e * 2 + 1]
}
  , getAttribute = function(a) {
    if (a.semantic === "NORMAL")
        return "normal";
    if (a.semantic === "POSITION")
        return "position";
    if (a.semantic === "JOINT")
        return "matricesIndices";
    if (a.semantic === "WEIGHT")
        return "matricesWeights";
    if (a.semantic === "COLOR")
        return "color";
    if (a.semantic && a.semantic.indexOf("TEXCOORD_") !== -1) {
        var e = Number(a.semantic.split("_")[1]);
        return "uv" + (e === 0 ? "" : e + 1)
    }
    return null
}
  , loadAnimations = function(a) {
    for (var e in a.animations) {
        var i = a.animations[e];
        if (!(!i.channels || !i.samplers))
            for (var o = null, s = 0; s < i.channels.length; s++) {
                var c = i.channels[s]
                  , d = i.samplers[c.sampler];
                if (!!d) {
                    var _ = null
                      , b = null;
                    i.parameters ? (_ = i.parameters[d.input],
                    b = i.parameters[d.output]) : (_ = d.input,
                    b = d.output);
                    var k = GLTFUtils.GetBufferFromAccessor(a, a.accessors[_])
                      , j = GLTFUtils.GetBufferFromAccessor(a, a.accessors[b])
                      , $ = c.target.id
                      , _e = a.scene.getNodeById($);
                    if (_e === null && (_e = a.scene.getNodeByName($)),
                    _e === null) {
                        Tools.Warn("Creating animation named " + e + ". But cannot find node named " + $ + " to attach to");
                        continue
                    }
                    var et = _e instanceof Bone
                      , tt = c.target.path
                      , rt = glTFAnimationPaths.indexOf(tt);
                    rt !== -1 && (tt = babylonAnimationPaths[rt]);
                    var it = Animation.ANIMATIONTYPE_MATRIX;
                    et || (tt === "rotationQuaternion" ? (it = Animation.ANIMATIONTYPE_QUATERNION,
                    _e.rotationQuaternion = new Quaternion) : it = Animation.ANIMATIONTYPE_VECTOR3);
                    var nt = null
                      , ot = []
                      , at = 0
                      , st = !1;
                    et && o && o.getKeys().length === k.length && (nt = o,
                    st = !0),
                    st || (a.scene._blockEntityCollection = !!a.assetContainer,
                    nt = new Animation(e,et ? "_matrix" : tt,1,it,Animation.ANIMATIONLOOPMODE_CYCLE),
                    a.scene._blockEntityCollection = !1);
                    for (var ut = 0; ut < k.length; ut++) {
                        var ct = null;
                        if (tt === "rotationQuaternion" ? (ct = Quaternion.FromArray([j[at], j[at + 1], j[at + 2], j[at + 3]]),
                        at += 4) : (ct = Vector3.FromArray([j[at], j[at + 1], j[at + 2]]),
                        at += 3),
                        et) {
                            var lt = _e
                              , ft = Vector3.Zero()
                              , ht = new Quaternion
                              , pt = Vector3.Zero()
                              , dt = lt.getBaseMatrix();
                            st && o && (dt = o.getKeys()[ut].value),
                            dt.decompose(pt, ht, ft),
                            tt === "position" ? ft = ct : tt === "rotationQuaternion" ? ht = ct : pt = ct,
                            ct = Matrix.Compose(pt, ht, ft)
                        }
                        st ? o && (o.getKeys()[ut].value = ct) : ot.push({
                            frame: k[ut],
                            value: ct
                        })
                    }
                    !st && nt && (nt.setKeys(ot),
                    _e.animations.push(nt)),
                    o = nt,
                    a.scene.stopAnimation(_e),
                    a.scene.beginAnimation(_e, 0, k[k.length - 1], !0, 1)
                }
            }
    }
}
  , configureBoneTransformation = function(a) {
    var e = null;
    if (a.translation || a.rotation || a.scale) {
        var i = Vector3.FromArray(a.scale || [1, 1, 1])
          , o = Quaternion.FromArray(a.rotation || [0, 0, 0, 1])
          , s = Vector3.FromArray(a.translation || [0, 0, 0]);
        e = Matrix.Compose(i, o, s)
    } else
        e = Matrix.FromArray(a.matrix);
    return e
}
  , getParentBone = function(a, e, i, o) {
    for (var s = 0; s < o.bones.length; s++)
        if (o.bones[s].name === i)
            return o.bones[s];
    var c = a.nodes;
    for (var d in c) {
        var _ = c[d];
        if (!!_.jointName)
            for (var b = _.children, s = 0; s < b.length; s++) {
                var k = a.nodes[b[s]];
                if (!!k.jointName && k.jointName === i) {
                    var j = configureBoneTransformation(_)
                      , $ = new Bone(_.name || "",o,getParentBone(a, e, _.jointName, o),j);
                    return $.id = d,
                    $
                }
            }
    }
    return null
}
  , getNodeToRoot = function(a, e) {
    for (var i = 0; i < a.length; i++)
        for (var o = a[i], s = 0; s < o.node.children.length; s++) {
            var c = o.node.children[s];
            if (c === e)
                return o.bone
        }
    return null
}
  , getJointNode = function(a, e) {
    var i = a.nodes
      , o = i[e];
    if (o)
        return {
            node: o,
            id: e
        };
    for (var s in i)
        if (o = i[s],
        o.jointName === e)
            return {
                node: o,
                id: s
            };
    return null
}
  , nodeIsInJoints = function(a, e) {
    for (var i = 0; i < a.jointNames.length; i++)
        if (a.jointNames[i] === e)
            return !0;
    return !1
}
  , getNodesToRoot = function(a, e, i, o) {
    for (var s in a.nodes) {
        var c = a.nodes[s]
          , d = s;
        if (!(!c.jointName || nodeIsInJoints(i, c.jointName))) {
            var _ = configureBoneTransformation(c)
              , b = new Bone(c.name || "",e,null,_);
            b.id = d,
            o.push({
                bone: b,
                node: c,
                id: d
            })
        }
    }
    for (var k = 0; k < o.length; k++)
        for (var j = o[k], $ = j.node.children, _e = 0; _e < $.length; _e++) {
            for (var et = null, tt = 0; tt < o.length; tt++)
                if (o[tt].id === $[_e]) {
                    et = o[tt];
                    break
                }
            et && (et.bone._parent = j.bone,
            j.bone.children.push(et.bone))
        }
}
  , importSkeleton = function(a, e, i, o, s) {
    if (o || (o = new Skeleton(e.name || "","",a.scene)),
    !e.babylonSkeleton)
        return o;
    var c = []
      , d = [];
    getNodesToRoot(a, o, e, c),
    o.bones = [];
    for (var _ = 0; _ < e.jointNames.length; _++) {
        var b = getJointNode(a, e.jointNames[_]);
        if (!!b) {
            var k = b.node;
            if (!k) {
                Tools.Warn("Joint named " + e.jointNames[_] + " does not exist");
                continue
            }
            var s = b.id
              , j = a.scene.getBoneById(s);
            if (j) {
                o.bones.push(j);
                continue
            }
            for (var $ = !1, _e = null, et = 0; et < _; et++) {
                var tt = getJointNode(a, e.jointNames[et]);
                if (!!tt) {
                    var rt = tt.node;
                    if (!rt) {
                        Tools.Warn("Joint named " + e.jointNames[et] + " does not exist when looking for parent");
                        continue
                    }
                    var it = rt.children;
                    if (!!it) {
                        $ = !1;
                        for (var nt = 0; nt < it.length; nt++)
                            if (it[nt] === s) {
                                _e = getParentBone(a, e, e.jointNames[et], o),
                                $ = !0;
                                break
                            }
                        if ($)
                            break
                    }
                }
            }
            var ot = configureBoneTransformation(k);
            !_e && c.length > 0 && (_e = getNodeToRoot(c, s),
            _e && d.indexOf(_e) === -1 && d.push(_e));
            var at = new Bone(k.jointName || "",o,_e,ot);
            at.id = s
        }
    }
    var st = o.bones;
    o.bones = [];
    for (var _ = 0; _ < e.jointNames.length; _++) {
        var b = getJointNode(a, e.jointNames[_]);
        if (!!b) {
            for (var et = 0; et < st.length; et++)
                if (st[et].id === b.id) {
                    o.bones.push(st[et]);
                    break
                }
        }
    }
    o.prepare();
    for (var _ = 0; _ < d.length; _++)
        o.bones.push(d[_]);
    return o
}
  , importMesh = function(a, e, i, o, s) {
    if (s || (a.scene._blockEntityCollection = !!a.assetContainer,
    s = new Mesh(e.name || "",a.scene),
    s._parentContainer = a.assetContainer,
    a.scene._blockEntityCollection = !1,
    s.id = o),
    !e.babylonNode)
        return s;
    for (var c = [], d = null, _ = new Array, b = new Array, k = new Array, j = new Array, $ = 0; $ < i.length; $++) {
        var _e = i[$]
          , et = a.meshes[_e];
        if (!!et)
            for (var tt = 0; tt < et.primitives.length; tt++) {
                var rt = new VertexData
                  , it = et.primitives[tt];
                it.mode;
                var nt = it.attributes
                  , ot = null
                  , at = null;
                for (var st in nt)
                    if (ot = a.accessors[nt[st]],
                    at = GLTFUtils.GetBufferFromAccessor(a, ot),
                    st === "NORMAL")
                        rt.normals = new Float32Array(at.length),
                        rt.normals.set(at);
                    else if (st === "POSITION") {
                        if (GLTFFileLoader.HomogeneousCoordinates) {
                            rt.positions = new Float32Array(at.length - at.length / 4);
                            for (var ut = 0; ut < at.length; ut += 4)
                                rt.positions[ut] = at[ut],
                                rt.positions[ut + 1] = at[ut + 1],
                                rt.positions[ut + 2] = at[ut + 2]
                        } else
                            rt.positions = new Float32Array(at.length),
                            rt.positions.set(at);
                        b.push(rt.positions.length)
                    } else if (st.indexOf("TEXCOORD_") !== -1) {
                        var ct = Number(st.split("_")[1])
                          , lt = VertexBuffer.UVKind + (ct === 0 ? "" : ct + 1)
                          , ft = new Float32Array(at.length);
                        ft.set(at),
                        normalizeUVs(ft),
                        rt.set(ft, lt)
                    } else
                        st === "JOINT" ? (rt.matricesIndices = new Float32Array(at.length),
                        rt.matricesIndices.set(at)) : st === "WEIGHT" ? (rt.matricesWeights = new Float32Array(at.length),
                        rt.matricesWeights.set(at)) : st === "COLOR" && (rt.colors = new Float32Array(at.length),
                        rt.colors.set(at));
                if (ot = a.accessors[it.indices],
                ot)
                    at = GLTFUtils.GetBufferFromAccessor(a, ot),
                    rt.indices = new Int32Array(at.length),
                    rt.indices.set(at),
                    j.push(rt.indices.length);
                else {
                    for (var ht = [], ut = 0; ut < rt.positions.length / 3; ut++)
                        ht.push(ut);
                    rt.indices = new Int32Array(ht),
                    j.push(rt.indices.length)
                }
                d ? d.merge(rt) : d = rt;
                var pt = a.scene.getMaterialById(it.material);
                c.push(pt === null ? GLTFUtils.GetDefaultMaterial(a.scene) : pt),
                _.push(_.length === 0 ? 0 : _[_.length - 1] + b[b.length - 2]),
                k.push(k.length === 0 ? 0 : k[k.length - 1] + j[j.length - 2])
            }
    }
    var dt;
    a.scene._blockEntityCollection = !!a.assetContainer,
    c.length > 1 ? (dt = new MultiMaterial("multimat" + o,a.scene),
    dt.subMaterials = c) : dt = new StandardMaterial("multimat" + o,a.scene),
    c.length === 1 && (dt = c[0]),
    dt._parentContainer = a.assetContainer,
    s.material || (s.material = dt),
    new Geometry(o,a.scene,d,!1,s),
    s.computeWorldMatrix(!0),
    a.scene._blockEntityCollection = !1,
    s.subMeshes = [];
    for (var _t = 0, $ = 0; $ < i.length; $++) {
        var _e = i[$]
          , et = a.meshes[_e];
        if (!!et)
            for (var tt = 0; tt < et.primitives.length; tt++)
                et.primitives[tt].mode,
                SubMesh.AddToMesh(_t, _[_t], b[_t], k[_t], j[_t], s, s, !0),
                _t++
    }
    return s
}
  , configureNode = function(a, e, i, o) {
    a.position && (a.position = e),
    (a.rotationQuaternion || a.rotation) && (a.rotationQuaternion = i),
    a.scaling && (a.scaling = o)
}
  , configureNodeFromMatrix = function(a, e, i) {
    if (e.matrix) {
        var o = new Vector3(0,0,0)
          , s = new Quaternion
          , c = new Vector3(0,0,0)
          , d = Matrix.FromArray(e.matrix);
        d.decompose(c, s, o),
        configureNode(a, o, s, c)
    } else
        e.translation && e.rotation && e.scale && configureNode(a, Vector3.FromArray(e.translation), Quaternion.FromArray(e.rotation), Vector3.FromArray(e.scale));
    a.computeWorldMatrix(!0)
}
  , importNode$1 = function(a, e, i, o) {
    var s = null;
    if (a.importOnlyMeshes && (e.skin || e.meshes) && a.importMeshesNames && a.importMeshesNames.length > 0 && a.importMeshesNames.indexOf(e.name || "") === -1)
        return null;
    if (e.skin) {
        if (e.meshes) {
            var c = a.skins[e.skin]
              , d = importMesh(a, e, e.meshes, i, e.babylonNode);
            d.skeleton = a.scene.getLastSkeletonById(e.skin),
            d.skeleton === null && (d.skeleton = importSkeleton(a, c, d, c.babylonSkeleton, e.skin),
            c.babylonSkeleton || (c.babylonSkeleton = d.skeleton)),
            s = d
        }
    } else if (e.meshes) {
        var d = importMesh(a, e, e.mesh ? [e.mesh] : e.meshes, i, e.babylonNode);
        s = d
    } else if (e.light && !e.babylonNode && !a.importOnlyMeshes) {
        var _ = a.lights[e.light];
        if (_) {
            if (_.type === "ambient") {
                var b = _[_.type]
                  , k = new HemisphericLight(e.light,Vector3.Zero(),a.scene);
                k.name = e.name || "",
                b.color && (k.diffuse = Color3.FromArray(b.color)),
                s = k
            } else if (_.type === "directional") {
                var j = _[_.type]
                  , $ = new DirectionalLight(e.light,Vector3.Zero(),a.scene);
                $.name = e.name || "",
                j.color && ($.diffuse = Color3.FromArray(j.color)),
                s = $
            } else if (_.type === "point") {
                var _e = _[_.type]
                  , et = new PointLight(e.light,Vector3.Zero(),a.scene);
                et.name = e.name || "",
                _e.color && (et.diffuse = Color3.FromArray(_e.color)),
                s = et
            } else if (_.type === "spot") {
                var tt = _[_.type]
                  , rt = new SpotLight(e.light,Vector3.Zero(),Vector3.Zero(),0,0,a.scene);
                rt.name = e.name || "",
                tt.color && (rt.diffuse = Color3.FromArray(tt.color)),
                tt.fallOfAngle && (rt.angle = tt.fallOfAngle),
                tt.fallOffExponent && (rt.exponent = tt.fallOffExponent),
                s = rt
            }
        }
    } else if (e.camera && !e.babylonNode && !a.importOnlyMeshes) {
        var it = a.cameras[e.camera];
        if (it) {
            if (a.scene._blockEntityCollection = !!a.assetContainer,
            it.type === "orthographic") {
                var nt = new FreeCamera(e.camera,Vector3.Zero(),a.scene,!1);
                nt.name = e.name || "",
                nt.mode = Camera$1.ORTHOGRAPHIC_CAMERA,
                nt.attachControl(),
                s = nt,
                nt._parentContainer = a.assetContainer
            } else if (it.type === "perspective") {
                var ot = it[it.type]
                  , at = new FreeCamera(e.camera,Vector3.Zero(),a.scene,!1);
                at.name = e.name || "",
                at.attachControl(),
                ot.aspectRatio || (ot.aspectRatio = a.scene.getEngine().getRenderWidth() / a.scene.getEngine().getRenderHeight()),
                ot.znear && ot.zfar && (at.maxZ = ot.zfar,
                at.minZ = ot.znear),
                s = at,
                at._parentContainer = a.assetContainer
            }
            a.scene._blockEntityCollection = !1
        }
    }
    if (!e.jointName) {
        if (e.babylonNode)
            return e.babylonNode;
        if (s === null) {
            a.scene._blockEntityCollection = !!a.assetContainer;
            var st = new Mesh(e.name || "",a.scene);
            st._parentContainer = a.assetContainer,
            a.scene._blockEntityCollection = !1,
            e.babylonNode = st,
            s = st
        }
    }
    if (s !== null) {
        if (e.matrix && s instanceof Mesh)
            configureNodeFromMatrix(s, e);
        else {
            var ut = e.translation || [0, 0, 0]
              , ct = e.rotation || [0, 0, 0, 1]
              , lt = e.scale || [1, 1, 1];
            configureNode(s, Vector3.FromArray(ut), Quaternion.FromArray(ct), Vector3.FromArray(lt))
        }
        s.updateCache(!0),
        e.babylonNode = s
    }
    return s
}
  , traverseNodes = function(a, e, i, o) {
    o === void 0 && (o = !1);
    var s = a.nodes[e]
      , c = null;
    if (a.importOnlyMeshes && !o && a.importMeshesNames ? a.importMeshesNames.indexOf(s.name || "") !== -1 || a.importMeshesNames.length === 0 ? o = !0 : o = !1 : o = !0,
    !s.jointName && o && (c = importNode$1(a, s, e),
    c !== null && (c.id = e,
    c.parent = i)),
    s.children)
        for (var d = 0; d < s.children.length; d++)
            traverseNodes(a, s.children[d], c, o)
}
  , postLoad = function(a) {
    var e = a.currentScene;
    if (e)
        for (var i = 0; i < e.nodes.length; i++)
            traverseNodes(a, e.nodes[i], null);
    else
        for (var o in a.scenes) {
            e = a.scenes[o];
            for (var i = 0; i < e.nodes.length; i++)
                traverseNodes(a, e.nodes[i], null)
        }
    loadAnimations(a);
    for (var i = 0; i < a.scene.skeletons.length; i++) {
        var s = a.scene.skeletons[i];
        a.scene.beginAnimation(s, 0, Number.MAX_VALUE, !0, 1)
    }
}
  , onBindShaderMaterial = function(a, e, i, o, s, c, d) {
    var _ = c.values || s.parameters;
    for (var b in i) {
        var k = i[b]
          , j = k.type;
        if (j === EParameterType.FLOAT_MAT2 || j === EParameterType.FLOAT_MAT3 || j === EParameterType.FLOAT_MAT4) {
            if (k.semantic && !k.source && !k.node)
                GLTFUtils.SetMatrix(e.scene, a, k, b, o.getEffect());
            else if (k.semantic && (k.source || k.node)) {
                var $ = e.scene.getNodeByName(k.source || k.node || "");
                if ($ === null && ($ = e.scene.getNodeById(k.source || k.node || "")),
                $ === null)
                    continue;
                GLTFUtils.SetMatrix(e.scene, $, k, b, o.getEffect())
            }
        } else {
            var _e = _[s.uniforms[b]];
            if (!_e)
                continue;
            if (j === EParameterType.SAMPLER_2D) {
                var et = e.textures[c.values ? _e : k.value].babylonTexture;
                if (et == null)
                    continue;
                o.getEffect().setTexture(b, et)
            } else
                GLTFUtils.SetUniform(o.getEffect(), b, _e, j)
        }
    }
    d(o)
}
  , prepareShaderMaterialUniforms = function(a, e, i, o, s) {
    var c = o.values || i.parameters
      , d = i.uniforms;
    for (var _ in s) {
        var b = s[_]
          , k = b.type
          , j = c[d[_]];
        if (j === void 0 && (j = b.value),
        !!j) {
            var $ = function(_e) {
                return function(et) {
                    b.value && _e && (e.setTexture(_e, et),
                    delete s[_e])
                }
            };
            k === EParameterType.SAMPLER_2D ? GLTFLoaderExtension.LoadTextureAsync(a, o.values ? j : b.value, $(_), function() {
                return $(null)
            }) : b.value && GLTFUtils.SetUniform(e, _, o.values ? j : b.value, k) && delete s[_]
        }
    }
}
  , onShaderCompileError = function(a, e, i) {
    return function(o, s) {
        e.dispose(!0),
        i("Cannot compile program named " + a.name + ". Error: " + s + ". Default material will be applied")
    }
}
  , onShaderCompileSuccess = function(a, e, i, o, s, c) {
    return function(d) {
        prepareShaderMaterialUniforms(a, e, i, o, s),
        e.onBind = function(_) {
            onBindShaderMaterial(_, a, s, e, i, o, c)
        }
    }
}
  , parseShaderUniforms = function(a, e, i) {
    for (var o in e.uniforms) {
        var s = e.uniforms[o]
          , c = e.parameters[s];
        if (a.currentIdentifier === o && c.semantic && !c.source && !c.node) {
            var d = glTFTransforms.indexOf(c.semantic);
            if (d !== -1)
                return delete i[o],
                babylonTransforms[d]
        }
    }
    return a.currentIdentifier
}
  , importMaterials = function(a) {
    for (var e in a.materials)
        GLTFLoaderExtension.LoadMaterialAsync(a, e, function(i) {}, function() {})
}
  , GLTFLoaderBase = function() {
    function a() {}
    return a.CreateRuntime = function(e, i, o) {
        var s = {
            extensions: {},
            accessors: {},
            buffers: {},
            bufferViews: {},
            meshes: {},
            lights: {},
            cameras: {},
            nodes: {},
            images: {},
            textures: {},
            shaders: {},
            programs: {},
            samplers: {},
            techniques: {},
            materials: {},
            animations: {},
            skins: {},
            extensionsUsed: [],
            scenes: {},
            buffersCount: 0,
            shaderscount: 0,
            scene: i,
            rootUrl: o,
            loadedBufferCount: 0,
            loadedBufferViews: {},
            loadedShaderCount: 0,
            importOnlyMeshes: !1,
            dummyNodes: [],
            assetContainer: null
        };
        return e.extensions && parseObject(e.extensions, "extensions", s),
        e.extensionsUsed && parseObject(e.extensionsUsed, "extensionsUsed", s),
        e.buffers && parseBuffers(e.buffers, s),
        e.bufferViews && parseObject(e.bufferViews, "bufferViews", s),
        e.accessors && parseObject(e.accessors, "accessors", s),
        e.meshes && parseObject(e.meshes, "meshes", s),
        e.lights && parseObject(e.lights, "lights", s),
        e.cameras && parseObject(e.cameras, "cameras", s),
        e.nodes && parseObject(e.nodes, "nodes", s),
        e.images && parseObject(e.images, "images", s),
        e.textures && parseObject(e.textures, "textures", s),
        e.shaders && parseShaders(e.shaders, s),
        e.programs && parseObject(e.programs, "programs", s),
        e.samplers && parseObject(e.samplers, "samplers", s),
        e.techniques && parseObject(e.techniques, "techniques", s),
        e.materials && parseObject(e.materials, "materials", s),
        e.animations && parseObject(e.animations, "animations", s),
        e.skins && parseObject(e.skins, "skins", s),
        e.scenes && (s.scenes = e.scenes),
        e.scene && e.scenes && (s.currentScene = e.scenes[e.scene]),
        s
    }
    ,
    a.LoadBufferAsync = function(e, i, o, s, c) {
        var d = e.buffers[i];
        Tools.IsBase64(d.uri) ? setTimeout(function() {
            return o(new Uint8Array(Tools.DecodeBase64(d.uri)))
        }) : Tools.LoadFile(e.rootUrl + d.uri, function(_) {
            return o(new Uint8Array(_))
        }, c, void 0, !0, function(_) {
            _ && s(_.status + " " + _.statusText)
        })
    }
    ,
    a.LoadTextureBufferAsync = function(e, i, o, s) {
        var c = e.textures[i];
        if (!c || !c.source) {
            s("");
            return
        }
        if (c.babylonTexture) {
            o(null);
            return
        }
        var d = e.images[c.source];
        Tools.IsBase64(d.uri) ? setTimeout(function() {
            return o(new Uint8Array(Tools.DecodeBase64(d.uri)))
        }) : Tools.LoadFile(e.rootUrl + d.uri, function(_) {
            return o(new Uint8Array(_))
        }, void 0, void 0, !0, function(_) {
            _ && s(_.status + " " + _.statusText)
        })
    }
    ,
    a.CreateTextureAsync = function(e, i, o, s, c) {
        var d = e.textures[i];
        if (d.babylonTexture) {
            s(d.babylonTexture);
            return
        }
        var _ = e.samplers[d.sampler]
          , b = _.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST || _.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR || _.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST || _.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR
          , k = Texture.BILINEAR_SAMPLINGMODE
          , j = o == null ? new Blob : new Blob([o])
          , $ = URL.createObjectURL(j)
          , _e = function() {
            return URL.revokeObjectURL($)
        }
          , et = new Texture($,e.scene,!b,!0,k,_e,_e);
        _.wrapS !== void 0 && (et.wrapU = GLTFUtils.GetWrapMode(_.wrapS)),
        _.wrapT !== void 0 && (et.wrapV = GLTFUtils.GetWrapMode(_.wrapT)),
        et.name = i,
        d.babylonTexture = et,
        s(et)
    }
    ,
    a.LoadShaderStringAsync = function(e, i, o, s) {
        var c = e.shaders[i];
        if (Tools.IsBase64(c.uri)) {
            var d = atob(c.uri.split(",")[1]);
            o && o(d)
        } else
            Tools.LoadFile(e.rootUrl + c.uri, o, void 0, void 0, !1, function(_) {
                _ && s && s(_.status + " " + _.statusText)
            })
    }
    ,
    a.LoadMaterialAsync = function(e, i, o, s) {
        var c = e.materials[i];
        if (!c.technique) {
            s && s("No technique found.");
            return
        }
        var d = e.techniques[c.technique];
        if (!d) {
            e.scene._blockEntityCollection = !!e.assetContainer;
            var _ = new StandardMaterial(i,e.scene);
            _._parentContainer = e.assetContainer,
            e.scene._blockEntityCollection = !1,
            _.diffuseColor = new Color3(.5,.5,.5),
            _.sideOrientation = Material.CounterClockWiseSideOrientation,
            o(_);
            return
        }
        var b = e.programs[d.program]
          , k = d.states
          , j = Effect.ShadersStore[b.vertexShader + "VertexShader"]
          , $ = Effect.ShadersStore[b.fragmentShader + "PixelShader"]
          , _e = ""
          , et = ""
          , tt = new Tokenizer(j)
          , rt = new Tokenizer($)
          , it = {}
          , nt = []
          , ot = []
          , at = [];
        for (var st in d.uniforms) {
            var ut = d.uniforms[st]
              , ct = d.parameters[ut];
            if (it[st] = ct,
            ct.semantic && !ct.node && !ct.source) {
                var lt = glTFTransforms.indexOf(ct.semantic);
                lt !== -1 ? (nt.push(babylonTransforms[lt]),
                delete it[st]) : nt.push(st)
            } else
                ct.type === EParameterType.SAMPLER_2D ? at.push(st) : nt.push(st)
        }
        for (var ft in d.attributes) {
            var ht = d.attributes[ft]
              , pt = d.parameters[ht];
            if (pt.semantic) {
                var dt = getAttribute(pt);
                dt && ot.push(dt)
            }
        }
        for (; !tt.isEnd() && tt.getNextToken(); ) {
            var _t = tt.currentToken;
            if (_t !== ETokenType.IDENTIFIER) {
                _e += tt.currentString;
                continue
            }
            var mt = !1;
            for (var ft in d.attributes) {
                var ht = d.attributes[ft]
                  , pt = d.parameters[ht];
                if (tt.currentIdentifier === ft && pt.semantic) {
                    _e += getAttribute(pt),
                    mt = !0;
                    break
                }
            }
            mt || (_e += parseShaderUniforms(tt, d, it))
        }
        for (; !rt.isEnd() && rt.getNextToken(); ) {
            var _t = rt.currentToken;
            if (_t !== ETokenType.IDENTIFIER) {
                et += rt.currentString;
                continue
            }
            et += parseShaderUniforms(rt, d, it)
        }
        var vt = {
            vertex: b.vertexShader + i,
            fragment: b.fragmentShader + i
        }
          , yt = {
            attributes: ot,
            uniforms: nt,
            samplers: at,
            needAlphaBlending: k && k.enable && k.enable.indexOf(3042) !== -1
        };
        Effect.ShadersStore[b.vertexShader + i + "VertexShader"] = _e,
        Effect.ShadersStore[b.fragmentShader + i + "PixelShader"] = et;
        var Et = new ShaderMaterial(i,e.scene,vt,yt);
        if (Et.onError = onShaderCompileError(b, Et, s),
        Et.onCompiled = onShaderCompileSuccess(e, Et, d, c, it, o),
        Et.sideOrientation = Material.CounterClockWiseSideOrientation,
        k && k.functions) {
            var At = k.functions;
            At.cullFace && At.cullFace[0] !== ECullingType.BACK && (Et.backFaceCulling = !1);
            var gt = At.blendFuncSeparate;
            gt && (gt[0] === EBlendingFunction.SRC_ALPHA && gt[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && gt[2] === EBlendingFunction.ONE && gt[3] === EBlendingFunction.ONE ? Et.alphaMode = Constants.ALPHA_COMBINE : gt[0] === EBlendingFunction.ONE && gt[1] === EBlendingFunction.ONE && gt[2] === EBlendingFunction.ZERO && gt[3] === EBlendingFunction.ONE ? Et.alphaMode = Constants.ALPHA_ONEONE : gt[0] === EBlendingFunction.SRC_ALPHA && gt[1] === EBlendingFunction.ONE && gt[2] === EBlendingFunction.ZERO && gt[3] === EBlendingFunction.ONE ? Et.alphaMode = Constants.ALPHA_ADD : gt[0] === EBlendingFunction.ZERO && gt[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && gt[2] === EBlendingFunction.ONE && gt[3] === EBlendingFunction.ONE ? Et.alphaMode = Constants.ALPHA_SUBTRACT : gt[0] === EBlendingFunction.DST_COLOR && gt[1] === EBlendingFunction.ZERO && gt[2] === EBlendingFunction.ONE && gt[3] === EBlendingFunction.ONE ? Et.alphaMode = Constants.ALPHA_MULTIPLY : gt[0] === EBlendingFunction.SRC_ALPHA && gt[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && gt[2] === EBlendingFunction.ONE && gt[3] === EBlendingFunction.ONE && (Et.alphaMode = Constants.ALPHA_MAXIMIZED))
        }
    }
    ,
    a
}()
  , GLTFLoader$1 = function() {
    function a() {}
    return a.RegisterExtension = function(e) {
        if (a.Extensions[e.name]) {
            Tools.Error('Tool with the same name "' + e.name + '" already exists');
            return
        }
        a.Extensions[e.name] = e
    }
    ,
    a.prototype.dispose = function() {}
    ,
    a.prototype._importMeshAsync = function(e, i, o, s, c, d, _, b) {
        var k = this;
        return i.useRightHandedSystem = !0,
        GLTFLoaderExtension.LoadRuntimeAsync(i, o, s, function(j) {
            j.assetContainer = c,
            j.importOnlyMeshes = !0,
            e === "" ? j.importMeshesNames = [] : typeof e == "string" ? j.importMeshesNames = [e] : e && !(e instanceof Array) ? j.importMeshesNames = [e] : (j.importMeshesNames = [],
            Tools.Warn("Argument meshesNames must be of type string or string[]")),
            k._createNodes(j);
            var $ = new Array
              , _e = new Array;
            for (var et in j.nodes) {
                var tt = j.nodes[et];
                tt.babylonNode instanceof AbstractMesh && $.push(tt.babylonNode)
            }
            for (var rt in j.skins) {
                var it = j.skins[rt];
                it.babylonSkeleton instanceof Skeleton && _e.push(it.babylonSkeleton)
            }
            k._loadBuffersAsync(j, function() {
                k._loadShadersAsync(j, function() {
                    importMaterials(j),
                    postLoad(j),
                    !GLTFFileLoader.IncrementalLoading && d && d($, _e)
                })
            }, _),
            GLTFFileLoader.IncrementalLoading && d && d($, _e)
        }, b),
        !0
    }
    ,
    a.prototype.importMeshAsync = function(e, i, o, s, c, d) {
        var _ = this;
        return new Promise(function(b, k) {
            _._importMeshAsync(e, i, s, c, o, function(j, $) {
                b({
                    meshes: j,
                    particleSystems: [],
                    skeletons: $,
                    animationGroups: [],
                    lights: [],
                    transformNodes: [],
                    geometries: []
                })
            }, d, function(j) {
                k(new Error(j))
            })
        }
        )
    }
    ,
    a.prototype._loadAsync = function(e, i, o, s, c, d) {
        var _ = this;
        e.useRightHandedSystem = !0,
        GLTFLoaderExtension.LoadRuntimeAsync(e, i, o, function(b) {
            GLTFLoaderExtension.LoadRuntimeExtensionsAsync(b, function() {
                _._createNodes(b),
                _._loadBuffersAsync(b, function() {
                    _._loadShadersAsync(b, function() {
                        importMaterials(b),
                        postLoad(b),
                        GLTFFileLoader.IncrementalLoading || s()
                    })
                }),
                GLTFFileLoader.IncrementalLoading && s()
            }, d)
        }, d)
    }
    ,
    a.prototype.loadAsync = function(e, i, o, s) {
        var c = this;
        return new Promise(function(d, _) {
            c._loadAsync(e, i, o, function() {
                d()
            }, s, function(b) {
                _(new Error(b))
            })
        }
        )
    }
    ,
    a.prototype._loadShadersAsync = function(e, i) {
        var o = !1
          , s = function(_, b) {
            GLTFLoaderExtension.LoadShaderStringAsync(e, _, function(k) {
                k instanceof ArrayBuffer || (e.loadedShaderCount++,
                k && (Effect.ShadersStore[_ + (b.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = k),
                e.loadedShaderCount === e.shaderscount && i())
            }, function() {
                Tools.Error("Error when loading shader program named " + _ + " located at " + b.uri)
            })
        };
        for (var c in e.shaders) {
            o = !0;
            var d = e.shaders[c];
            d ? s.bind(this, c, d)() : Tools.Error("No shader named: " + c)
        }
        o || i()
    }
    ,
    a.prototype._loadBuffersAsync = function(e, i, o) {
        var s = !1
          , c = function(b, k) {
            GLTFLoaderExtension.LoadBufferAsync(e, b, function(j) {
                e.loadedBufferCount++,
                j && (j.byteLength != e.buffers[b].byteLength && Tools.Error("Buffer named " + b + " is length " + j.byteLength + ". Expected: " + k.byteLength),
                e.loadedBufferViews[b] = j),
                e.loadedBufferCount === e.buffersCount && i()
            }, function() {
                Tools.Error("Error when loading buffer named " + b + " located at " + k.uri)
            })
        };
        for (var d in e.buffers) {
            s = !0;
            var _ = e.buffers[d];
            _ ? c.bind(this, d, _)() : Tools.Error("No buffer named: " + d)
        }
        s || i()
    }
    ,
    a.prototype._createNodes = function(e) {
        var i = e.currentScene;
        if (i)
            for (var o = 0; o < i.nodes.length; o++)
                traverseNodes(e, i.nodes[o], null);
        else
            for (var s in e.scenes) {
                i = e.scenes[s];
                for (var o = 0; o < i.nodes.length; o++)
                    traverseNodes(e, i.nodes[o], null)
            }
    }
    ,
    a.Extensions = {},
    a
}()
  , GLTFLoaderExtension = function() {
    function a(e) {
        this._name = e
    }
    return Object.defineProperty(a.prototype, "name", {
        get: function() {
            return this._name
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.loadRuntimeAsync = function(e, i, o, s, c) {
        return !1
    }
    ,
    a.prototype.loadRuntimeExtensionsAsync = function(e, i, o) {
        return !1
    }
    ,
    a.prototype.loadBufferAsync = function(e, i, o, s, c) {
        return !1
    }
    ,
    a.prototype.loadTextureBufferAsync = function(e, i, o, s) {
        return !1
    }
    ,
    a.prototype.createTextureAsync = function(e, i, o, s, c) {
        return !1
    }
    ,
    a.prototype.loadShaderStringAsync = function(e, i, o, s) {
        return !1
    }
    ,
    a.prototype.loadMaterialAsync = function(e, i, o, s) {
        return !1
    }
    ,
    a.LoadRuntimeAsync = function(e, i, o, s, c) {
        a.ApplyExtensions(function(d) {
            return d.loadRuntimeAsync(e, i, o, s, c)
        }, function() {
            setTimeout(function() {
                !s || s(GLTFLoaderBase.CreateRuntime(i.json, e, o))
            })
        })
    }
    ,
    a.LoadRuntimeExtensionsAsync = function(e, i, o) {
        a.ApplyExtensions(function(s) {
            return s.loadRuntimeExtensionsAsync(e, i, o)
        }, function() {
            setTimeout(function() {
                i()
            })
        })
    }
    ,
    a.LoadBufferAsync = function(e, i, o, s, c) {
        a.ApplyExtensions(function(d) {
            return d.loadBufferAsync(e, i, o, s, c)
        }, function() {
            GLTFLoaderBase.LoadBufferAsync(e, i, o, s, c)
        })
    }
    ,
    a.LoadTextureAsync = function(e, i, o, s) {
        a.LoadTextureBufferAsync(e, i, function(c) {
            c && a.CreateTextureAsync(e, i, c, o, s)
        }, s)
    }
    ,
    a.LoadShaderStringAsync = function(e, i, o, s) {
        a.ApplyExtensions(function(c) {
            return c.loadShaderStringAsync(e, i, o, s)
        }, function() {
            GLTFLoaderBase.LoadShaderStringAsync(e, i, o, s)
        })
    }
    ,
    a.LoadMaterialAsync = function(e, i, o, s) {
        a.ApplyExtensions(function(c) {
            return c.loadMaterialAsync(e, i, o, s)
        }, function() {
            GLTFLoaderBase.LoadMaterialAsync(e, i, o, s)
        })
    }
    ,
    a.LoadTextureBufferAsync = function(e, i, o, s) {
        a.ApplyExtensions(function(c) {
            return c.loadTextureBufferAsync(e, i, o, s)
        }, function() {
            GLTFLoaderBase.LoadTextureBufferAsync(e, i, o, s)
        })
    }
    ,
    a.CreateTextureAsync = function(e, i, o, s, c) {
        a.ApplyExtensions(function(d) {
            return d.createTextureAsync(e, i, o, s, c)
        }, function() {
            GLTFLoaderBase.CreateTextureAsync(e, i, o, s, c)
        })
    }
    ,
    a.ApplyExtensions = function(e, i) {
        for (var o in GLTFLoader$1.Extensions) {
            var s = GLTFLoader$1.Extensions[o];
            if (e(s))
                return
        }
        i()
    }
    ,
    a
}();
GLTFFileLoader._CreateGLTF1Loader = function() {
    return new GLTFLoader$1
}
;
var BinaryExtensionBufferName = "binary_glTF"
  , GLTFBinaryExtension = function(a) {
    __extends(e, a);
    function e() {
        return a.call(this, "KHR_binary_glTF") || this
    }
    return e.prototype.loadRuntimeAsync = function(i, o, s, c, d) {
        var _ = o.json.extensionsUsed;
        return !_ || _.indexOf(this.name) === -1 || !o.bin ? !1 : (this._bin = o.bin,
        c(GLTFLoaderBase.CreateRuntime(o.json, i, s)),
        !0)
    }
    ,
    e.prototype.loadBufferAsync = function(i, o, s, c) {
        return i.extensionsUsed.indexOf(this.name) === -1 || o !== BinaryExtensionBufferName ? !1 : (this._bin.readAsync(0, this._bin.byteLength).then(s, function(d) {
            return c(d.message)
        }),
        !0)
    }
    ,
    e.prototype.loadTextureBufferAsync = function(i, o, s, c) {
        var d = i.textures[o]
          , _ = i.images[d.source];
        if (!_.extensions || !(this.name in _.extensions))
            return !1;
        var b = _.extensions[this.name]
          , k = i.bufferViews[b.bufferView]
          , j = GLTFUtils.GetBufferFromBufferView(i, k, 0, k.byteLength, EComponentType.UNSIGNED_BYTE);
        return s(j),
        !0
    }
    ,
    e.prototype.loadShaderStringAsync = function(i, o, s, c) {
        var d = i.shaders[o];
        if (!d.extensions || !(this.name in d.extensions))
            return !1;
        var _ = d.extensions[this.name]
          , b = i.bufferViews[_.bufferView]
          , k = GLTFUtils.GetBufferFromBufferView(i, b, 0, b.byteLength, EComponentType.UNSIGNED_BYTE);
        return setTimeout(function() {
            var j = GLTFUtils.DecodeBufferToText(k);
            s(j)
        }),
        !0
    }
    ,
    e
}(GLTFLoaderExtension);
GLTFLoader$1.RegisterExtension(new GLTFBinaryExtension);
var GLTFMaterialsCommonExtension = function(a) {
    __extends(e, a);
    function e() {
        return a.call(this, "KHR_materials_common") || this
    }
    return e.prototype.loadRuntimeExtensionsAsync = function(i, o, s) {
        if (!i.extensions)
            return !1;
        var c = i.extensions[this.name];
        if (!c)
            return !1;
        var d = c.lights;
        if (d)
            for (var _ in d) {
                var b = d[_];
                switch (b.type) {
                case "ambient":
                    var k = new HemisphericLight(b.name,new Vector3(0,1,0),i.scene)
                      , j = b.ambient;
                    j && (k.diffuse = Color3.FromArray(j.color || [1, 1, 1]));
                    break;
                case "point":
                    var $ = new PointLight(b.name,new Vector3(10,10,10),i.scene)
                      , _e = b.point;
                    _e && ($.diffuse = Color3.FromArray(_e.color || [1, 1, 1]));
                    break;
                case "directional":
                    var et = new DirectionalLight(b.name,new Vector3(0,-1,0),i.scene)
                      , tt = b.directional;
                    tt && (et.diffuse = Color3.FromArray(tt.color || [1, 1, 1]));
                    break;
                case "spot":
                    var rt = b.spot;
                    if (rt) {
                        var it = new SpotLight(b.name,new Vector3(0,10,0),new Vector3(0,-1,0),rt.fallOffAngle || Math.PI,rt.fallOffExponent || 0,i.scene);
                        it.diffuse = Color3.FromArray(rt.color || [1, 1, 1])
                    }
                    break;
                default:
                    Tools.Warn('GLTF Material Common extension: light type "' + b.type + "\u201D not supported");
                    break
                }
            }
        return !1
    }
    ,
    e.prototype.loadMaterialAsync = function(i, o, s, c) {
        var d = i.materials[o];
        if (!d || !d.extensions)
            return !1;
        var _ = d.extensions[this.name];
        if (!_)
            return !1;
        var b = new StandardMaterial(o,i.scene);
        return b.sideOrientation = Material.CounterClockWiseSideOrientation,
        _.technique === "CONSTANT" && (b.disableLighting = !0),
        b.backFaceCulling = _.doubleSided === void 0 ? !1 : !_.doubleSided,
        b.alpha = _.values.transparency === void 0 ? 1 : _.values.transparency,
        b.specularPower = _.values.shininess === void 0 ? 0 : _.values.shininess,
        typeof _.values.ambient == "string" ? this._loadTexture(i, _.values.ambient, b, "ambientTexture", c) : b.ambientColor = Color3.FromArray(_.values.ambient || [0, 0, 0]),
        typeof _.values.diffuse == "string" ? this._loadTexture(i, _.values.diffuse, b, "diffuseTexture", c) : b.diffuseColor = Color3.FromArray(_.values.diffuse || [0, 0, 0]),
        typeof _.values.emission == "string" ? this._loadTexture(i, _.values.emission, b, "emissiveTexture", c) : b.emissiveColor = Color3.FromArray(_.values.emission || [0, 0, 0]),
        typeof _.values.specular == "string" ? this._loadTexture(i, _.values.specular, b, "specularTexture", c) : b.specularColor = Color3.FromArray(_.values.specular || [0, 0, 0]),
        !0
    }
    ,
    e.prototype._loadTexture = function(i, o, s, c, d) {
        GLTFLoaderBase.LoadTextureBufferAsync(i, o, function(_) {
            GLTFLoaderBase.CreateTextureAsync(i, o, _, function(b) {
                return s[c] = b
            }, d)
        }, d)
    }
    ,
    e
}(GLTFLoaderExtension);
GLTFLoader$1.RegisterExtension(new GLTFMaterialsCommonExtension);
var Deferred = function() {
    function a() {
        var e = this;
        this.promise = new Promise(function(i, o) {
            e._resolve = i,
            e._reject = o
        }
        )
    }
    return Object.defineProperty(a.prototype, "resolve", {
        get: function() {
            return this._resolve
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "reject", {
        get: function() {
            return this._reject
        },
        enumerable: !1,
        configurable: !0
    }),
    a
}()
  , PBRMaterial = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o) || this;
        return s.directIntensity = 1,
        s.emissiveIntensity = 1,
        s.environmentIntensity = 1,
        s.specularIntensity = 1,
        s.disableBumpMap = !1,
        s.ambientTextureStrength = 1,
        s.ambientTextureImpactOnAnalyticalLights = e.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,
        s.metallicF0Factor = 1,
        s.metallicReflectanceColor = Color3.White(),
        s.useOnlyMetallicFromMetallicReflectanceTexture = !1,
        s.ambientColor = new Color3(0,0,0),
        s.albedoColor = new Color3(1,1,1),
        s.reflectivityColor = new Color3(1,1,1),
        s.reflectionColor = new Color3(1,1,1),
        s.emissiveColor = new Color3(0,0,0),
        s.microSurface = 1,
        s.useLightmapAsShadowmap = !1,
        s.useAlphaFromAlbedoTexture = !1,
        s.forceAlphaTest = !1,
        s.alphaCutOff = .4,
        s.useSpecularOverAlpha = !0,
        s.useMicroSurfaceFromReflectivityMapAlpha = !1,
        s.useRoughnessFromMetallicTextureAlpha = !0,
        s.useRoughnessFromMetallicTextureGreen = !1,
        s.useMetallnessFromMetallicTextureBlue = !1,
        s.useAmbientOcclusionFromMetallicTextureRed = !1,
        s.useAmbientInGrayScale = !1,
        s.useAutoMicroSurfaceFromReflectivityMap = !1,
        s.useRadianceOverAlpha = !0,
        s.useObjectSpaceNormalMap = !1,
        s.useParallax = !1,
        s.useParallaxOcclusion = !1,
        s.parallaxScaleBias = .05,
        s.disableLighting = !1,
        s.forceIrradianceInFragment = !1,
        s.maxSimultaneousLights = 4,
        s.invertNormalMapX = !1,
        s.invertNormalMapY = !1,
        s.twoSidedLighting = !1,
        s.useAlphaFresnel = !1,
        s.useLinearAlphaFresnel = !1,
        s.environmentBRDFTexture = null,
        s.forceNormalForward = !1,
        s.enableSpecularAntiAliasing = !1,
        s.useHorizonOcclusion = !0,
        s.useRadianceOcclusion = !0,
        s.unlit = !1,
        s._environmentBRDFTexture = GetEnvironmentBRDFTexture(o),
        s
    }
    return Object.defineProperty(e.prototype, "refractionTexture", {
        get: function() {
            return this.subSurface.refractionTexture
        },
        set: function(i) {
            this.subSurface.refractionTexture = i,
            i ? 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(i) {
            this.subSurface.indexOfRefraction = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "invertRefractionY", {
        get: function() {
            return this.subSurface.invertRefractionY
        },
        set: function(i) {
            this.subSurface.invertRefractionY = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "linkRefractionWithTransparency", {
        get: function() {
            return this.subSurface.linkRefractionWithTransparency
        },
        set: function(i) {
            this.subSurface.linkRefractionWithTransparency = i,
            i && (this.subSurface.isRefractionEnabled = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "usePhysicalLightFalloff", {
        get: function() {
            return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL
        },
        set: function(i) {
            i !== this.usePhysicalLightFalloff && (this._markAllSubMeshesAsTexturesDirty(),
            i ? 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(i) {
            i !== this.useGLTFLightFalloff && (this._markAllSubMeshesAsTexturesDirty(),
            i ? 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(i) {
            this._attachImageProcessingConfiguration(i),
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurvesEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurvesEnabled
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorCurvesEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingEnabled
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorGradingEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraToneMappingEnabled", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingEnabled
        },
        set: function(i) {
            this._imageProcessingConfiguration.toneMappingEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraExposure", {
        get: function() {
            return this._imageProcessingConfiguration.exposure
        },
        set: function(i) {
            this._imageProcessingConfiguration.exposure = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraContrast", {
        get: function() {
            return this._imageProcessingConfiguration.contrast
        },
        set: function(i) {
            this._imageProcessingConfiguration.contrast = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingTexture", {
        get: function() {
            return this._imageProcessingConfiguration.colorGradingTexture
        },
        set: function(i) {
            this._imageProcessingConfiguration.colorGradingTexture = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurves", {
        get: function() {
            return this._imageProcessingConfiguration.colorCurves
        },
        set: function(i) {
            this._imageProcessingConfiguration.colorCurves = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "PBRMaterial"
    }
    ,
    e.prototype.clone = function(i) {
        var o = this
          , s = SerializationHelper.Clone(function() {
            return new e(i,o.getScene())
        }, this);
        return s.id = i,
        s.name = i,
        this.stencil.copyTo(s.stencil),
        this.clearCoat.copyTo(s.clearCoat),
        this.anisotropy.copyTo(s.anisotropy),
        this.brdf.copyTo(s.brdf),
        this.sheen.copyTo(s.sheen),
        this.subSurface.copyTo(s.subSurface),
        s
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        return i.customType = "BABYLON.PBRMaterial",
        i.stencil = this.stencil.serialize(),
        i.clearCoat = this.clearCoat.serialize(),
        i.anisotropy = this.anisotropy.serialize(),
        i.brdf = this.brdf.serialize(),
        i.sheen = this.sheen.serialize(),
        i.subSurface = this.subSurface.serialize(),
        i
    }
    ,
    e.Parse = function(i, o, s) {
        var c = SerializationHelper.Parse(function() {
            return new e(i.name,o)
        }, i, o, s);
        return i.stencil && c.stencil.parse(i.stencil, o, s),
        i.clearCoat && c.clearCoat.parse(i.clearCoat, o, s),
        i.anisotropy && c.anisotropy.parse(i.anisotropy, o, s),
        i.brdf && c.brdf.parse(i.brdf, o, s),
        i.sheen && c.sheen.parse(i.sheen, o, s),
        i.subSurface && c.subSurface.parse(i.subSurface, o, s),
        c
    }
    ,
    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 a(e, i, o) {
        i === void 0 && (i = 0),
        o === void 0 && (o = 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 = o || EngineStore.LastCreatedScene,
        this.influence = i,
        this._scene && (this._uniqueId = this._scene.getUniqueId())
    }
    return Object.defineProperty(a.prototype, "influence", {
        get: function() {
            return this._influence
        },
        set: function(e) {
            if (this._influence !== e) {
                var i = this._influence;
                this._influence = e,
                this.onInfluenceChanged.hasObservers() && this.onInfluenceChanged.notifyObservers(i === 0 || e === 0)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasPositions", {
        get: function() {
            return !!this._positions
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasNormals", {
        get: function() {
            return !!this._normals
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasTangents", {
        get: function() {
            return !!this._tangents
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasUVs", {
        get: function() {
            return !!this._uvs
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setPositions = function(e) {
        var i = this.hasPositions;
        this._positions = e,
        i !== this.hasPositions && this._onDataLayoutChanged.notifyObservers(void 0)
    }
    ,
    a.prototype.getPositions = function() {
        return this._positions
    }
    ,
    a.prototype.setNormals = function(e) {
        var i = this.hasNormals;
        this._normals = e,
        i !== this.hasNormals && this._onDataLayoutChanged.notifyObservers(void 0)
    }
    ,
    a.prototype.getNormals = function() {
        return this._normals
    }
    ,
    a.prototype.setTangents = function(e) {
        var i = this.hasTangents;
        this._tangents = e,
        i !== this.hasTangents && this._onDataLayoutChanged.notifyObservers(void 0)
    }
    ,
    a.prototype.getTangents = function() {
        return this._tangents
    }
    ,
    a.prototype.setUVs = function(e) {
        var i = this.hasUVs;
        this._uvs = e,
        i !== this.hasUVs && this._onDataLayoutChanged.notifyObservers(void 0)
    }
    ,
    a.prototype.getUVs = function() {
        return this._uvs
    }
    ,
    a.prototype.clone = function() {
        var e = this
          , i = SerializationHelper.Clone(function() {
            return new a(e.name,e.influence,e._scene)
        }, this);
        return i._positions = this._positions,
        i._normals = this._normals,
        i._tangents = this._tangents,
        i._uvs = this._uvs,
        i
    }
    ,
    a.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
    }
    ,
    a.prototype.getClassName = function() {
        return "MorphTarget"
    }
    ,
    a.Parse = function(e) {
        var i = new a(e.name,e.influence);
        if (i.setPositions(e.positions),
        e.id != null && (i.id = e.id),
        e.normals && i.setNormals(e.normals),
        e.tangents && i.setTangents(e.tangents),
        e.uvs && i.setUVs(e.uvs),
        e.animations)
            for (var o = 0; o < e.animations.length; o++) {
                var s = e.animations[o]
                  , c = GetClass("BABYLON.Animation");
                c && i.animations.push(c.Parse(s))
            }
        return i
    }
    ,
    a.FromMesh = function(e, i, o) {
        i || (i = e.name);
        var s = new a(i,o,e.getScene());
        return s.setPositions(e.getVerticesData(VertexBuffer.PositionKind)),
        e.isVerticesDataPresent(VertexBuffer.NormalKind) && s.setNormals(e.getVerticesData(VertexBuffer.NormalKind)),
        e.isVerticesDataPresent(VertexBuffer.TangentKind) && s.setTangents(e.getVerticesData(VertexBuffer.TangentKind)),
        e.isVerticesDataPresent(VertexBuffer.UVKind) && s.setUVs(e.getVerticesData(VertexBuffer.UVKind)),
        s
    }
    ,
    __decorate([serialize()], a.prototype, "id", void 0),
    a
}()
  , RawTexture2DArray = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j, $) {
        b === void 0 && (b = !0),
        k === void 0 && (k = !1),
        j === void 0 && (j = Texture.TRILINEAR_SAMPLINGMODE),
        $ === void 0 && ($ = 0);
        var _e = a.call(this, null, _, !b, k) || this;
        return _e.format = d,
        _e._texture = _.getEngine().createRawTexture2DArray(i, o, s, c, d, b, k, j, null, $),
        _e._depth = c,
        _e.is2DArray = !0,
        _e
    }
    return Object.defineProperty(e.prototype, "depth", {
        get: function() {
            return this._depth
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.update = function(i) {
        !this._texture || this._getEngine().updateRawTexture2DArray(this._texture, i, this._texture.format, this._texture.invertY, null, this._texture.type)
    }
    ,
    e.CreateRGBATexture = function(i, o, s, c, d, _, b, k, j) {
        return _ === void 0 && (_ = !0),
        b === void 0 && (b = !1),
        k === void 0 && (k = 3),
        j === void 0 && (j = 0),
        new e(i,o,s,c,5,d,_,b,k,j)
    }
    ,
    e
}(Texture)
  , MorphTargetManager = function() {
    function a(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 i = this._scene.getEngine().getCaps();
            this._canUseTextureForTargets = i.canUseGLVertexID && i.textureFloat && i.maxVertexTextureImageUnits > 0
        }
    }
    return Object.defineProperty(a.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(a.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "vertexCount", {
        get: function() {
            return this._vertexCount
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "supportsNormals", {
        get: function() {
            return this._supportsNormals && this.enableNormalMorphing
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "supportsTangents", {
        get: function() {
            return this._supportsTangents && this.enableTangentMorphing
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "supportsUVs", {
        get: function() {
            return this._supportsUVs && this.enableUVMorphing
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "numTargets", {
        get: function() {
            return this._targets.length
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "numInfluencers", {
        get: function() {
            return this._activeTargets.length
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "influences", {
        get: function() {
            return this._influences
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "useTextureToStoreTargets", {
        get: function() {
            return this._useTextureToStoreTargets
        },
        set: function(e) {
            this._useTextureToStoreTargets = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "isUsingTextureForTargets", {
        get: function() {
            return a.EnableTextureStorage && this.useTextureToStoreTargets && this._canUseTextureForTargets
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getActiveTarget = function(e) {
        return this._activeTargets.data[e]
    }
    ,
    a.prototype.getTarget = function(e) {
        return this._targets[e]
    }
    ,
    a.prototype.addTarget = function(e) {
        var i = this;
        this._targets.push(e),
        this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(function(o) {
            i._syncActiveTargets(o)
        })),
        this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(function() {
            i._syncActiveTargets(!0)
        })),
        this._syncActiveTargets(!0)
    }
    ,
    a.prototype.removeTarget = function(e) {
        var i = this._targets.indexOf(e);
        i >= 0 && (this._targets.splice(i, 1),
        e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(i, 1)[0]),
        e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(i, 1)[0]),
        this._syncActiveTargets(!0))
    }
    ,
    a.prototype._bind = function(e) {
        e.setFloat3("morphTargetTextureInfo", this._textureVertexStride, this._textureWidth, this._textureHeight),
        e.setFloatArray("morphTargetTextureIndices", this._morphTargetTextureIndices),
        e.setTexture("morphTargets", this._targetStoreTexture)
    }
    ,
    a.prototype.clone = function() {
        for (var e = new a(this._scene), i = 0, o = this._targets; i < o.length; i++) {
            var s = o[i];
            e.addTarget(s.clone())
        }
        return e.enableNormalMorphing = this.enableNormalMorphing,
        e.enableTangentMorphing = this.enableTangentMorphing,
        e.enableUVMorphing = this.enableUVMorphing,
        e
    }
    ,
    a.prototype.serialize = function() {
        var e = {};
        e.id = this.uniqueId,
        e.targets = [];
        for (var i = 0, o = this._targets; i < o.length; i++) {
            var s = o[i];
            e.targets.push(s.serialize())
        }
        return e
    }
    ,
    a.prototype._syncActiveTargets = function(e) {
        if (!this.areUpdatesFrozen) {
            var i = 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 o = -1, s = 0, c = this._targets; s < c.length; s++) {
                var d = c[s];
                if (o++,
                !(d.influence === 0 && this.optimizeInfluencers)) {
                    this._activeTargets.push(d),
                    this._morphTargetTextureIndices[i] = o,
                    this._tempInfluences[i++] = d.influence,
                    this._supportsNormals = this._supportsNormals && d.hasNormals,
                    this._supportsTangents = this._supportsTangents && d.hasTangents,
                    this._supportsUVs = this._supportsUVs && d.hasUVs;
                    var _ = d.getPositions();
                    if (_) {
                        var b = _.length / 3;
                        if (this._vertexCount === 0)
                            this._vertexCount = b;
                        else if (this._vertexCount !== b) {
                            Logger$2.Error("Incompatible target. Targets must all have the same vertices count.");
                            return
                        }
                    }
                }
            }
            (!this._influences || this._influences.length !== i) && (this._influences = new Float32Array(i));
            for (var k = 0; k < i; k++)
                this._influences[k] = this._tempInfluences[k];
            e && this.synchronize()
        }
    }
    ,
    a.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 i = !0;
                if (this._targetStoreTexture) {
                    var o = this._targetStoreTexture.getSize();
                    o.width === this._textureWidth && o.height === this._textureHeight && this._targetStoreTexture.depth === this._targets.length && (i = !1)
                }
                if (i) {
                    this._targetStoreTexture && this._targetStoreTexture.dispose();
                    for (var s = this._targets.length, c = new Float32Array(s * this._textureWidth * this._textureHeight * 4), d = 0, _ = 0; _ < s; _++) {
                        var b = this._targets[_]
                          , k = b.getPositions()
                          , j = b.getNormals()
                          , $ = b.getUVs()
                          , _e = b.getTangents();
                        if (!k) {
                            _ === 0 && Logger$2.Error("Invalid morph target. Target must have positions.");
                            return
                        }
                        d = _ * this._textureWidth * this._textureHeight * 4;
                        for (var et = 0; et < this._vertexCount; et++)
                            c[d] = k[et * 3],
                            c[d + 1] = k[et * 3 + 1],
                            c[d + 2] = k[et * 3 + 2],
                            d += 4,
                            j && (c[d] = j[et * 3],
                            c[d + 1] = j[et * 3 + 1],
                            c[d + 2] = j[et * 3 + 2],
                            d += 4),
                            $ && (c[d] = $[et * 2],
                            c[d + 1] = $[et * 2 + 1],
                            d += 4),
                            _e && (c[d] = _e[et * 3],
                            c[d + 1] = _e[et * 3 + 1],
                            c[d + 2] = _e[et * 3 + 2],
                            d += 4)
                    }
                    this._targetStoreTexture = RawTexture2DArray.CreateRGBATexture(c, this._textureWidth, this._textureHeight, s, this._scene, !1, !1, 1, 1)
                }
            }
            for (var tt = 0, rt = this._scene.meshes; tt < rt.length; tt++) {
                var it = rt[tt];
                it.morphTargetManager === this && it._syncGeometryWithMorphTargetManager()
            }
        }
    }
    ,
    a.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
        }
    }
    ,
    a.Parse = function(e, i) {
        var o = new a(i);
        o._uniqueId = e.id;
        for (var s = 0, c = e.targets; s < c.length; s++) {
            var d = c[s];
            o.addTarget(MorphTarget.Parse(d))
        }
        return o
    }
    ,
    a.EnableTextureStorage = !0,
    a
}()
  , ArrayItem = function() {
    function a() {}
    return a.Get = function(e, i, o) {
        if (!i || o == null || !i[o])
            throw new Error(e + ": Failed to find index (" + o + ")");
        return i[o]
    }
    ,
    a.Assign = function(e) {
        if (e)
            for (var i = 0; i < e.length; i++)
                e[i].index = i
    }
    ,
    a
}()
  , GLTFLoader = function() {
    function a(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 a.RegisterExtension = function(e, i) {
        a.UnregisterExtension(e) && Logger$2.Warn("Extension with the name '" + e + "' already exists"),
        a._RegisteredExtensions[e] = {
            factory: i
        }
    }
    ,
    a.UnregisterExtension = function(e) {
        return a._RegisteredExtensions[e] ? (delete a._RegisteredExtensions[e],
        !0) : !1
    }
    ,
    Object.defineProperty(a.prototype, "gltf", {
        get: function() {
            return this._gltf
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "bin", {
        get: function() {
            return this._bin
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "parent", {
        get: function() {
            return this._parent
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "babylonScene", {
        get: function() {
            return this._babylonScene
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rootBabylonMesh", {
        get: function() {
            return this._rootBabylonMesh
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.dispose = function() {
        if (!this._disposed) {
            this._disposed = !0,
            this._completePromises.length = 0;
            for (var e in this._extensions) {
                var i = this._extensions[e];
                i.dispose && i.dispose(),
                delete this._extensions[e]
            }
            this._gltf = null,
            this._babylonScene = null,
            this._rootBabylonMesh = null,
            this._parent.dispose()
        }
    }
    ,
    a.prototype.importMeshAsync = function(e, i, o, s, c, d, _) {
        var b = this;
        return _ === void 0 && (_ = ""),
        Promise.resolve().then(function() {
            b._babylonScene = i,
            b._assetContainer = o,
            b._loadData(s);
            var k = null;
            if (e) {
                var j = {};
                if (b._gltf.nodes)
                    for (var $ = 0, _e = b._gltf.nodes; $ < _e.length; $++) {
                        var et = _e[$];
                        et.name && (j[et.name] = et.index)
                    }
                var tt = e instanceof Array ? e : [e];
                k = tt.map(function(rt) {
                    var it = j[rt];
                    if (it === void 0)
                        throw new Error("Failed to find node '" + rt + "'");
                    return it
                })
            }
            return b._loadAsync(c, _, k, function() {
                return {
                    meshes: b._getMeshes(),
                    particleSystems: [],
                    skeletons: b._getSkeletons(),
                    animationGroups: b._getAnimationGroups(),
                    lights: b._babylonLights,
                    transformNodes: b._getTransformNodes(),
                    geometries: b._getGeometries()
                }
            })
        })
    }
    ,
    a.prototype.loadAsync = function(e, i, o, s, c) {
        var d = this;
        return c === void 0 && (c = ""),
        Promise.resolve().then(function() {
            return d._babylonScene = e,
            d._loadData(i),
            d._loadAsync(o, c, null, function() {})
        })
    }
    ,
    a.prototype._loadAsync = function(e, i, o, s) {
        var c = this;
        return Promise.resolve().then(function() {
            c._rootUrl = e,
            c._uniqueRootUrl = !StringTools.StartsWith(e, "file:") && i ? e : "" + e + Date.now() + "/",
            c._fileName = i,
            c._loadExtensions(),
            c._checkExtensions();
            var d = GLTFLoaderState[GLTFLoaderState.LOADING] + " => " + GLTFLoaderState[GLTFLoaderState.READY]
              , _ = GLTFLoaderState[GLTFLoaderState.LOADING] + " => " + GLTFLoaderState[GLTFLoaderState.COMPLETE];
            c._parent._startPerformanceCounter(d),
            c._parent._startPerformanceCounter(_),
            c._parent._setState(GLTFLoaderState.LOADING),
            c._extensionsOnLoading();
            var b = new Array
              , k = c._babylonScene.blockMaterialDirtyMechanism;
            if (c._babylonScene.blockMaterialDirtyMechanism = !0,
            o)
                b.push(c.loadSceneAsync("/nodes", {
                    nodes: o,
                    index: -1
                }));
            else if (c._gltf.scene != null || c._gltf.scenes && c._gltf.scenes[0]) {
                var j = ArrayItem.Get("/scene", c._gltf.scenes, c._gltf.scene || 0);
                b.push(c.loadSceneAsync("/scenes/" + j.index, j))
            }
            if (c.parent.loadAllMaterials && c._gltf.materials)
                for (var $ = 0; $ < c._gltf.materials.length; ++$) {
                    var _e = c._gltf.materials[$]
                      , et = "/materials/" + $
                      , tt = Material.TriangleFillMode;
                    b.push(c._loadMaterialAsync(et, _e, null, tt, function(it) {}))
                }
            c._babylonScene.blockMaterialDirtyMechanism = k,
            c._parent.compileMaterials && b.push(c._compileMaterialsAsync()),
            c._parent.compileShadowGenerators && b.push(c._compileShadowGeneratorsAsync());
            var rt = Promise.all(b).then(function() {
                return c._rootBabylonMesh && c._rootBabylonMesh.setEnabled(!0),
                c._extensionsOnReady(),
                c._parent._setState(GLTFLoaderState.READY),
                c._startAnimations(),
                s()
            });
            return rt.then(function(it) {
                return c._parent._endPerformanceCounter(d),
                Tools.SetImmediate(function() {
                    c._disposed || Promise.all(c._completePromises).then(function() {
                        c._parent._endPerformanceCounter(_),
                        c._parent._setState(GLTFLoaderState.COMPLETE),
                        c._parent.onCompleteObservable.notifyObservers(void 0),
                        c._parent.onCompleteObservable.clear(),
                        c.dispose()
                    }, function(nt) {
                        c._parent.onErrorObservable.notifyObservers(nt),
                        c._parent.onErrorObservable.clear(),
                        c.dispose()
                    })
                }),
                it
            })
        }).catch(function(d) {
            throw c._disposed || (c._parent.onErrorObservable.notifyObservers(d),
            c._parent.onErrorObservable.clear(),
            c.dispose()),
            d
        })
    }
    ,
    a.prototype._loadData = function(e) {
        if (this._gltf = e.json,
        this._setupData(),
        e.bin) {
            var i = this._gltf.buffers;
            if (i && i[0] && !i[0].uri) {
                var o = i[0];
                (o.byteLength < e.bin.byteLength - 3 || o.byteLength > e.bin.byteLength) && Logger$2.Warn("Binary buffer length (" + o.byteLength + ") from JSON does not match chunk length (" + e.bin.byteLength + ")"),
                this._bin = e.bin
            } else
                Logger$2.Warn("Unexpected BIN chunk")
        }
    }
    ,
    a.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 = {}, i = 0, o = this._gltf.nodes; i < o.length; i++) {
                var s = o[i];
                if (s.children)
                    for (var c = 0, d = s.children; c < d.length; c++) {
                        var _ = d[c];
                        e[_] = s.index
                    }
            }
            for (var b = this._createRootNode(), k = 0, j = this._gltf.nodes; k < j.length; k++) {
                var s = j[k]
                  , $ = e[s.index];
                s.parent = $ === void 0 ? b : this._gltf.nodes[$]
            }
        }
    }
    ,
    a.prototype._loadExtensions = function() {
        for (var e in a._RegisteredExtensions) {
            var i = a._RegisteredExtensions[e].factory(this);
            i.name !== e && Logger$2.Warn("The name of the glTF loader extension instance does not match the registered name: " + i.name + " !== " + e),
            this._extensions.push(i),
            this._parent.onExtensionLoadedObservable.notifyObservers(i)
        }
        this._extensions.sort(function(o, s) {
            return (o.order || Number.MAX_VALUE) - (s.order || Number.MAX_VALUE)
        }),
        this._parent.onExtensionLoadedObservable.clear()
    }
    ,
    a.prototype._checkExtensions = function() {
        if (this._gltf.extensionsRequired)
            for (var e = function(d) {
                var _ = i._extensions.some(function(b) {
                    return b.name === d && b.enabled
                });
                if (!_)
                    throw new Error("Require extension " + d + " is not available")
            }, i = this, o = 0, s = this._gltf.extensionsRequired; o < s.length; o++) {
                var c = s[o];
                e(c)
            }
    }
    ,
    a.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],
                a._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
    }
    ,
    a.prototype.loadSceneAsync = function(e, i) {
        var o = this
          , s = this._extensionsLoadSceneAsync(e, i);
        if (s)
            return s;
        var c = new Array;
        if (this.logOpen(e + " " + (i.name || "")),
        i.nodes)
            for (var d = 0, _ = i.nodes; d < _.length; d++) {
                var b = _[d]
                  , k = ArrayItem.Get(e + "/nodes/" + b, this._gltf.nodes, b);
                c.push(this.loadNodeAsync("/nodes/" + k.index, k, function(rt) {
                    rt.parent = o._rootBabylonMesh
                }))
            }
        if (this._gltf.nodes)
            for (var j = 0, $ = this._gltf.nodes; j < $.length; j++) {
                var k = $[j];
                if (k._babylonTransformNode && k._babylonBones)
                    for (var _e = 0, et = k._babylonBones; _e < et.length; _e++) {
                        var tt = et[_e];
                        tt.linkTransformNode(k._babylonTransformNode)
                    }
            }
        return c.push(this._loadAnimationsAsync()),
        this.logClose(),
        Promise.all(c).then(function() {})
    }
    ,
    a.prototype._forEachPrimitive = function(e, i) {
        if (e._primitiveBabylonMeshes)
            for (var o = 0, s = e._primitiveBabylonMeshes; o < s.length; o++) {
                var c = s[o];
                i(c)
            }
    }
    ,
    a.prototype._getGeometries = function() {
        var e = new Array
          , i = this._gltf.nodes;
        if (i)
            for (var o = 0, s = i; o < s.length; o++) {
                var c = s[o];
                this._forEachPrimitive(c, function(d) {
                    var _ = d.geometry;
                    _ && e.indexOf(_) === -1 && e.push(_)
                })
            }
        return e
    }
    ,
    a.prototype._getMeshes = function() {
        var e = new Array;
        this._rootBabylonMesh && e.push(this._rootBabylonMesh);
        var i = this._gltf.nodes;
        if (i)
            for (var o = 0, s = i; o < s.length; o++) {
                var c = s[o];
                this._forEachPrimitive(c, function(d) {
                    e.push(d)
                })
            }
        return e
    }
    ,
    a.prototype._getTransformNodes = function() {
        var e = new Array
          , i = this._gltf.nodes;
        if (i)
            for (var o = 0, s = i; o < s.length; o++) {
                var c = s[o];
                c._babylonTransformNode && c._babylonTransformNode.getClassName() === "TransformNode" && e.push(c._babylonTransformNode)
            }
        return e
    }
    ,
    a.prototype._getSkeletons = function() {
        var e = new Array
          , i = this._gltf.skins;
        if (i)
            for (var o = 0, s = i; o < s.length; o++) {
                var c = s[o];
                c._data && e.push(c._data.babylonSkeleton)
            }
        return e
    }
    ,
    a.prototype._getAnimationGroups = function() {
        var e = new Array
          , i = this._gltf.animations;
        if (i)
            for (var o = 0, s = i; o < s.length; o++) {
                var c = s[o];
                c._babylonAnimationGroup && e.push(c._babylonAnimationGroup)
            }
        return e
    }
    ,
    a.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(), i = 0, o = e; i < o.length; i++) {
                    var s = o[i];
                    s.start(!0)
                }
                break
            }
        default:
            {
                Logger$2.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
                return
            }
        }
    }
    ,
    a.prototype.loadNodeAsync = function(e, i, o) {
        var s = this;
        o === void 0 && (o = function() {}
        );
        var c = this._extensionsLoadNodeAsync(e, i, o);
        if (c)
            return c;
        if (i._babylonTransformNode)
            throw new Error(e + ": Invalid recursive node hierarchy");
        var d = new Array;
        this.logOpen(e + " " + (i.name || ""));
        var _ = function(j) {
            if (a.AddPointerMetadata(j, e),
            a._LoadTransform(i, j),
            i.camera != null) {
                var $ = ArrayItem.Get(e + "/camera", s._gltf.cameras, i.camera);
                d.push(s.loadCameraAsync("/cameras/" + $.index, $, function(it) {
                    it.parent = j
                }))
            }
            if (i.children)
                for (var _e = 0, et = i.children; _e < et.length; _e++) {
                    var tt = et[_e]
                      , rt = ArrayItem.Get(e + "/children/" + tt, s._gltf.nodes, tt);
                    d.push(s.loadNodeAsync("/nodes/" + rt.index, rt, function(it) {
                        it.parent = j
                    }))
                }
            o(j)
        };
        if (i.mesh == null) {
            var b = i.name || "node" + i.index;
            this._babylonScene._blockEntityCollection = !!this._assetContainer,
            i._babylonTransformNode = new TransformNode(b,this._babylonScene),
            i._babylonTransformNode._parentContainer = this._assetContainer,
            this._babylonScene._blockEntityCollection = !1,
            _(i._babylonTransformNode)
        } else {
            var k = ArrayItem.Get(e + "/mesh", this._gltf.meshes, i.mesh);
            d.push(this._loadMeshAsync("/meshes/" + k.index, i, k, _))
        }
        return this.logClose(),
        Promise.all(d).then(function() {
            return s._forEachPrimitive(i, function(j) {
                j.geometry && j.geometry.useBoundingInfoFromGeometry ? j._updateBoundingInfo() : j.refreshBoundingInfo(!0)
            }),
            i._babylonTransformNode
        })
    }
    ,
    a.prototype._loadMeshAsync = function(e, i, o, s) {
        var c = o.primitives;
        if (!c || !c.length)
            throw new Error(e + ": Primitives are missing");
        c[0].index == null && ArrayItem.Assign(c);
        var d = new Array;
        this.logOpen(e + " " + (o.name || ""));
        var _ = i.name || "node" + i.index;
        if (c.length === 1) {
            var b = o.primitives[0];
            d.push(this._loadMeshPrimitiveAsync(e + "/primitives/" + b.index, _, i, o, b, function(_e) {
                i._babylonTransformNode = _e,
                i._primitiveBabylonMeshes = [_e]
            }))
        } else {
            this._babylonScene._blockEntityCollection = !!this._assetContainer,
            i._babylonTransformNode = new TransformNode(_,this._babylonScene),
            i._babylonTransformNode._parentContainer = this._assetContainer,
            this._babylonScene._blockEntityCollection = !1,
            i._primitiveBabylonMeshes = [];
            for (var k = 0, j = c; k < j.length; k++) {
                var b = j[k];
                d.push(this._loadMeshPrimitiveAsync(e + "/primitives/" + b.index, _ + "_primitive" + b.index, i, o, b, function(et) {
                    et.parent = i._babylonTransformNode,
                    i._primitiveBabylonMeshes.push(et)
                }))
            }
        }
        if (i.skin != null) {
            var $ = ArrayItem.Get(e + "/skin", this._gltf.skins, i.skin);
            d.push(this._loadSkinAsync("/skins/" + $.index, i, $))
        }
        return s(i._babylonTransformNode),
        this.logClose(),
        Promise.all(d).then(function() {
            return i._babylonTransformNode
        })
    }
    ,
    a.prototype._loadMeshPrimitiveAsync = function(e, i, o, s, c, d) {
        var _ = this
          , b = this._extensionsLoadMeshPrimitiveAsync(e, i, o, s, c, d);
        if (b)
            return b;
        this.logOpen("" + e);
        var k = this._disableInstancedMesh === 0 && this._parent.createInstances && o.skin == null && !s.primitives[0].targets, j, $;
        if (k && c._instanceData)
            this._babylonScene._blockEntityCollection = !!this._assetContainer,
            j = c._instanceData.babylonSourceMesh.createInstance(i),
            j._parentContainer = this._assetContainer,
            this._babylonScene._blockEntityCollection = !1,
            $ = c._instanceData.promise;
        else {
            var _e = new Array;
            this._babylonScene._blockEntityCollection = !!this._assetContainer;
            var et = new Mesh(i,this._babylonScene);
            et._parentContainer = this._assetContainer,
            this._babylonScene._blockEntityCollection = !1,
            et.overrideMaterialSideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation,
            this._createMorphTargets(e, o, s, c, et),
            _e.push(this._loadVertexDataAsync(e, c, et).then(function(nt) {
                return _._loadMorphTargetsAsync(e, c, et, nt).then(function() {
                    _._babylonScene._blockEntityCollection = !!_._assetContainer,
                    nt.applyToMesh(et),
                    nt._parentContainer = _._assetContainer,
                    _._babylonScene._blockEntityCollection = !1
                })
            }));
            var tt = a._GetDrawMode(e, c.mode);
            if (c.material == null) {
                var rt = this._defaultBabylonMaterialData[tt];
                rt || (rt = this._createDefaultMaterial("__GLTFLoader._default", tt),
                this._parent.onMaterialLoadedObservable.notifyObservers(rt),
                this._defaultBabylonMaterialData[tt] = rt),
                et.material = rt
            } else {
                var it = ArrayItem.Get(e + "/material", this._gltf.materials, c.material);
                _e.push(this._loadMaterialAsync("/materials/" + it.index, it, et, tt, function(nt) {
                    et.material = nt
                }))
            }
            $ = Promise.all(_e),
            k && (c._instanceData = {
                babylonSourceMesh: et,
                promise: $
            }),
            j = et
        }
        return a.AddPointerMetadata(j, e),
        this._parent.onMeshLoadedObservable.notifyObservers(j),
        d(j),
        this.logClose(),
        $.then(function() {
            return j
        })
    }
    ,
    a.prototype._loadVertexDataAsync = function(e, i, o) {
        var s = this
          , c = this._extensionsLoadVertexDataAsync(e, i, o);
        if (c)
            return c;
        var d = i.attributes;
        if (!d)
            throw new Error(e + ": Attributes are missing");
        var _ = new Array
          , b = new Geometry(o.name,this._babylonScene);
        if (i.indices == null)
            o.isUnIndexed = !0;
        else {
            var k = ArrayItem.Get(e + "/indices", this._gltf.accessors, i.indices);
            _.push(this._loadIndicesAccessorAsync("/accessors/" + k.index, k).then(function($) {
                b.setIndices($)
            }))
        }
        var j = function($, _e, et) {
            if (d[$] != null) {
                o._delayInfo = o._delayInfo || [],
                o._delayInfo.indexOf(_e) === -1 && o._delayInfo.push(_e);
                var tt = ArrayItem.Get(e + "/attributes/" + $, s._gltf.accessors, d[$]);
                _.push(s._loadVertexAccessorAsync("/accessors/" + tt.index, tt, _e).then(function(rt) {
                    if (rt.getKind() === VertexBuffer.PositionKind && !s.parent.alwaysComputeBoundingBox && !o.skeleton) {
                        var it = tt.min
                          , nt = tt.max;
                        if (it !== void 0 && nt !== void 0) {
                            if (tt.normalized && tt.componentType !== 5126) {
                                var ot = 1;
                                switch (tt.componentType) {
                                case 5120:
                                    ot = 127;
                                    break;
                                case 5121:
                                    ot = 255;
                                    break;
                                case 5122:
                                    ot = 32767;
                                    break;
                                case 5123:
                                    ot = 65535;
                                    break
                                }
                                for (var at = 0; at < 3; ++at)
                                    it[at] = Math.max(it[at] / ot, -1),
                                    nt[at] = Math.max(nt[at] / ot, -1)
                            }
                            var st = TmpVectors.Vector3[0]
                              , ut = TmpVectors.Vector3[1];
                            st.copyFromFloats.apply(st, it),
                            ut.copyFromFloats.apply(ut, nt),
                            b._boundingInfo = new BoundingInfo(st,ut),
                            b.useBoundingInfoFromGeometry = !0
                        }
                    }
                    b.setVerticesBuffer(rt, tt.count)
                })),
                _e == VertexBuffer.MatricesIndicesExtraKind && (o.numBoneInfluencers = 8),
                et && et(tt)
            }
        };
        return j("POSITION", VertexBuffer.PositionKind),
        j("NORMAL", VertexBuffer.NormalKind),
        j("TANGENT", VertexBuffer.TangentKind),
        j("TEXCOORD_0", VertexBuffer.UVKind),
        j("TEXCOORD_1", VertexBuffer.UV2Kind),
        j("TEXCOORD_2", VertexBuffer.UV3Kind),
        j("TEXCOORD_3", VertexBuffer.UV4Kind),
        j("TEXCOORD_4", VertexBuffer.UV5Kind),
        j("TEXCOORD_5", VertexBuffer.UV6Kind),
        j("JOINTS_0", VertexBuffer.MatricesIndicesKind),
        j("WEIGHTS_0", VertexBuffer.MatricesWeightsKind),
        j("JOINTS_1", VertexBuffer.MatricesIndicesExtraKind),
        j("WEIGHTS_1", VertexBuffer.MatricesWeightsExtraKind),
        j("COLOR_0", VertexBuffer.ColorKind, function($) {
            $.type === "VEC4" && (o.hasVertexAlpha = !0)
        }),
        Promise.all(_).then(function() {
            return b
        })
    }
    ,
    a.prototype._createMorphTargets = function(e, i, o, s, c) {
        if (!!s.targets) {
            if (i._numMorphTargets == null)
                i._numMorphTargets = s.targets.length;
            else if (s.targets.length !== i._numMorphTargets)
                throw new Error(e + ": Primitives do not have the same number of targets");
            var d = o.extras ? o.extras.targetNames : null;
            c.morphTargetManager = new MorphTargetManager(c.getScene()),
            c.morphTargetManager.areUpdatesFrozen = !0;
            for (var _ = 0; _ < s.targets.length; _++) {
                var b = i.weights ? i.weights[_] : o.weights ? o.weights[_] : 0
                  , k = d ? d[_] : "morphTarget" + _;
                c.morphTargetManager.addTarget(new MorphTarget(k,b,c.getScene()))
            }
        }
    }
    ,
    a.prototype._loadMorphTargetsAsync = function(e, i, o, s) {
        if (!i.targets)
            return Promise.resolve();
        for (var c = new Array, d = o.morphTargetManager, _ = 0; _ < d.numTargets; _++) {
            var b = d.getTarget(_);
            c.push(this._loadMorphTargetVertexDataAsync(e + "/targets/" + _, s, i.targets[_], b))
        }
        return Promise.all(c).then(function() {
            d.areUpdatesFrozen = !1
        })
    }
    ,
    a.prototype._loadMorphTargetVertexDataAsync = function(e, i, o, s) {
        var c = this
          , d = new Array
          , _ = function(b, k, j) {
            if (o[b] != null) {
                var $ = i.getVertexBuffer(k);
                if (!!$) {
                    var _e = ArrayItem.Get(e + "/" + b, c._gltf.accessors, o[b]);
                    d.push(c._loadFloatAccessorAsync("/accessors/" + _e.index, _e).then(function(et) {
                        j($, et)
                    }))
                }
            }
        };
        return _("POSITION", VertexBuffer.PositionKind, function(b, k) {
            var j = new Float32Array(k.length);
            b.forEach(k.length, function($, _e) {
                j[_e] = k[_e] + $
            }),
            s.setPositions(j)
        }),
        _("NORMAL", VertexBuffer.NormalKind, function(b, k) {
            var j = new Float32Array(k.length);
            b.forEach(j.length, function($, _e) {
                j[_e] = k[_e] + $
            }),
            s.setNormals(j)
        }),
        _("TANGENT", VertexBuffer.TangentKind, function(b, k) {
            var j = new Float32Array(k.length / 3 * 4)
              , $ = 0;
            b.forEach(k.length / 3 * 4, function(_e, et) {
                (et + 1) % 4 !== 0 && (j[$] = k[$] + _e,
                $++)
            }),
            s.setTangents(j)
        }),
        Promise.all(d).then(function() {})
    }
    ,
    a._LoadTransform = function(e, i) {
        if (e.skin == null) {
            var o = Vector3.Zero()
              , s = Quaternion.Identity()
              , c = Vector3.One();
            if (e.matrix) {
                var d = Matrix.FromArray(e.matrix);
                d.decompose(c, s, o)
            } else
                e.translation && (o = Vector3.FromArray(e.translation)),
                e.rotation && (s = Quaternion.FromArray(e.rotation)),
                e.scale && (c = Vector3.FromArray(e.scale));
            i.position = o,
            i.rotationQuaternion = s,
            i.scaling = c
        }
    }
    ,
    a.prototype._loadSkinAsync = function(e, i, o) {
        var s = this
          , c = this._extensionsLoadSkinAsync(e, i, o);
        if (c)
            return c;
        var d = function(j) {
            s._forEachPrimitive(i, function($) {
                $.skeleton = j
            })
        };
        if (o._data)
            return d(o._data.babylonSkeleton),
            o._data.promise;
        var _ = "skeleton" + o.index;
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var b = new Skeleton(o.name || _,_,this._babylonScene);
        b._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        b.overrideMesh = this._rootBabylonMesh,
        this._loadBones(e, o, b),
        d(b);
        var k = this._loadSkinInverseBindMatricesDataAsync(e, o).then(function(j) {
            s._updateBoneMatrices(b, j)
        });
        return o._data = {
            babylonSkeleton: b,
            promise: k
        },
        k
    }
    ,
    a.prototype._loadBones = function(e, i, o) {
        for (var s = {}, c = 0, d = i.joints; c < d.length; c++) {
            var _ = d[c]
              , b = ArrayItem.Get(e + "/joints/" + _, this._gltf.nodes, _);
            this._loadBone(b, i, o, s)
        }
    }
    ,
    a.prototype._loadBone = function(e, i, o, s) {
        var c = s[e.index];
        if (c)
            return c;
        var d = null;
        e.parent && e.parent._babylonTransformNode !== this._rootBabylonMesh && (d = this._loadBone(e.parent, i, o, s));
        var _ = i.joints.indexOf(e.index);
        return c = new Bone(e.name || "joint" + e.index,o,d,this._getNodeMatrix(e),null,null,_),
        s[e.index] = c,
        e._babylonBones = e._babylonBones || [],
        e._babylonBones.push(c),
        c
    }
    ,
    a.prototype._loadSkinInverseBindMatricesDataAsync = function(e, i) {
        if (i.inverseBindMatrices == null)
            return Promise.resolve(null);
        var o = ArrayItem.Get(e + "/inverseBindMatrices", this._gltf.accessors, i.inverseBindMatrices);
        return this._loadFloatAccessorAsync("/accessors/" + o.index, o)
    }
    ,
    a.prototype._updateBoneMatrices = function(e, i) {
        for (var o = 0, s = e.bones; o < s.length; o++) {
            var c = s[o]
              , d = Matrix.Identity()
              , _ = c._index;
            i && _ !== -1 && (Matrix.FromArrayToRef(i, _ * 16, d),
            d.invertToRef(d));
            var b = c.getParent();
            b && d.multiplyToRef(b.getInvertedAbsoluteTransform(), d),
            c.updateMatrix(d, !1, !1),
            c._updateDifferenceMatrix(void 0, !1)
        }
    }
    ,
    a.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())
    }
    ,
    a.prototype.loadCameraAsync = function(e, i, o) {
        o === void 0 && (o = function() {}
        );
        var s = this._extensionsLoadCameraAsync(e, i, o);
        if (s)
            return s;
        var c = new Array;
        this.logOpen(e + " " + (i.name || "")),
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var d = new FreeCamera(i.name || "camera" + i.index,Vector3.Zero(),this._babylonScene,!1);
        switch (d._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        d.ignoreParentScaling = !0,
        d.rotation = new Vector3(0,Math.PI,0),
        i.type) {
        case "perspective":
            {
                var _ = i.perspective;
                if (!_)
                    throw new Error(e + ": Camera perspective properties are missing");
                d.fov = _.yfov,
                d.minZ = _.znear,
                d.maxZ = _.zfar || 0;
                break
            }
        case "orthographic":
            {
                if (!i.orthographic)
                    throw new Error(e + ": Camera orthographic properties are missing");
                d.mode = Camera$1.ORTHOGRAPHIC_CAMERA,
                d.orthoLeft = -i.orthographic.xmag,
                d.orthoRight = i.orthographic.xmag,
                d.orthoBottom = -i.orthographic.ymag,
                d.orthoTop = i.orthographic.ymag,
                d.minZ = i.orthographic.znear,
                d.maxZ = i.orthographic.zfar;
                break
            }
        default:
            throw new Error(e + ": Invalid camera type (" + i.type + ")")
        }
        return a.AddPointerMetadata(d, e),
        this._parent.onCameraLoadedObservable.notifyObservers(d),
        o(d),
        this.logClose(),
        Promise.all(c).then(function() {
            return d
        })
    }
    ,
    a.prototype._loadAnimationsAsync = function() {
        var e = this._gltf.animations;
        if (!e)
            return Promise.resolve();
        for (var i = new Array, o = 0; o < e.length; o++) {
            var s = e[o];
            i.push(this.loadAnimationAsync("/animations/" + s.index, s).then(function(c) {
                c.targetedAnimations.length === 0 && c.dispose()
            }))
        }
        return Promise.all(i).then(function() {})
    }
    ,
    a.prototype.loadAnimationAsync = function(e, i) {
        var o = this._extensionsLoadAnimationAsync(e, i);
        if (o)
            return o;
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var s = new AnimationGroup(i.name || "animation" + i.index,this._babylonScene);
        s._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        i._babylonAnimationGroup = s;
        var c = new Array;
        ArrayItem.Assign(i.channels),
        ArrayItem.Assign(i.samplers);
        for (var d = 0, _ = i.channels; d < _.length; d++) {
            var b = _[d];
            c.push(this._loadAnimationChannelAsync(e + "/channels/" + b.index, e, i, b, s))
        }
        return Promise.all(c).then(function() {
            return s.normalize(0),
            s
        })
    }
    ,
    a.prototype._loadAnimationChannelAsync = function(e, i, o, s, c, d) {
        var _ = this;
        if (d === void 0 && (d = null),
        s.target.node == null)
            return Promise.resolve();
        var b = ArrayItem.Get(e + "/target/node", this._gltf.nodes, s.target.node);
        if (s.target.path === "weights" && !b._numMorphTargets || s.target.path !== "weights" && !b._babylonTransformNode)
            return Promise.resolve();
        var k = ArrayItem.Get(e + "/sampler", o.samplers, s.sampler);
        return this._loadAnimationSamplerAsync(i + "/samplers/" + s.sampler, k).then(function(j) {
            var $, _e;
            switch (s.target.path) {
            case "translation":
                {
                    $ = "position",
                    _e = Animation.ANIMATIONTYPE_VECTOR3;
                    break
                }
            case "rotation":
                {
                    $ = "rotationQuaternion",
                    _e = Animation.ANIMATIONTYPE_QUATERNION;
                    break
                }
            case "scale":
                {
                    $ = "scaling",
                    _e = Animation.ANIMATIONTYPE_VECTOR3;
                    break
                }
            case "weights":
                {
                    $ = "influence",
                    _e = Animation.ANIMATIONTYPE_FLOAT;
                    break
                }
            default:
                throw new Error(e + "/target/path: Invalid value (" + s.target.path + ")")
            }
            var et = 0, tt;
            switch ($) {
            case "position":
                {
                    tt = function() {
                        var ct = Vector3.FromArray(j.output, et);
                        return et += 3,
                        ct
                    }
                    ;
                    break
                }
            case "rotationQuaternion":
                {
                    tt = function() {
                        var ct = Quaternion.FromArray(j.output, et);
                        return et += 4,
                        ct
                    }
                    ;
                    break
                }
            case "scaling":
                {
                    tt = function() {
                        var ct = Vector3.FromArray(j.output, et);
                        return et += 3,
                        ct
                    }
                    ;
                    break
                }
            case "influence":
                {
                    tt = function() {
                        for (var ct = new Array(b._numMorphTargets), lt = 0; lt < b._numMorphTargets; lt++)
                            ct[lt] = j.output[et++];
                        return ct
                    }
                    ;
                    break
                }
            }
            var rt;
            switch (j.interpolation) {
            case "STEP":
                {
                    rt = function(ct) {
                        return {
                            frame: j.input[ct],
                            value: tt(),
                            interpolation: AnimationKeyInterpolation.STEP
                        }
                    }
                    ;
                    break
                }
            case "LINEAR":
                {
                    rt = function(ct) {
                        return {
                            frame: j.input[ct],
                            value: tt()
                        }
                    }
                    ;
                    break
                }
            case "CUBICSPLINE":
                {
                    rt = function(ct) {
                        return {
                            frame: j.input[ct],
                            inTangent: tt(),
                            value: tt(),
                            outTangent: tt()
                        }
                    }
                    ;
                    break
                }
            }
            for (var it = new Array(j.input.length), nt = 0; nt < j.input.length; nt++)
                it[nt] = rt(nt);
            if ($ === "influence")
                for (var ot = function(ct) {
                    var lt = c.name + "_channel" + c.targetedAnimations.length
                      , ft = new Animation(lt,$,1,_e);
                    ft.setKeys(it.map(function(ht) {
                        return {
                            frame: ht.frame,
                            inTangent: ht.inTangent ? ht.inTangent[ct] : void 0,
                            value: ht.value[ct],
                            outTangent: ht.outTangent ? ht.outTangent[ct] : void 0
                        }
                    })),
                    _._forEachPrimitive(b, function(ht) {
                        var pt = ht
                          , dt = pt.morphTargetManager.getTarget(ct)
                          , _t = ft.clone();
                        dt.animations.push(_t),
                        c.addTargetedAnimation(_t, dt)
                    })
                }, at = 0; at < b._numMorphTargets; at++)
                    ot(at);
            else {
                var st = c.name + "_channel" + c.targetedAnimations.length
                  , ut = new Animation(st,$,1,_e);
                ut.setKeys(it),
                d != null && d.animations != null ? (d.animations.push(ut),
                c.addTargetedAnimation(ut, d)) : (b._babylonTransformNode.animations.push(ut),
                c.addTargetedAnimation(ut, b._babylonTransformNode))
            }
        })
    }
    ,
    a.prototype._loadAnimationSamplerAsync = function(e, i) {
        if (i._data)
            return i._data;
        var o = i.interpolation || "LINEAR";
        switch (o) {
        case "STEP":
        case "LINEAR":
        case "CUBICSPLINE":
            break;
        default:
            throw new Error(e + "/interpolation: Invalid value (" + i.interpolation + ")")
        }
        var s = ArrayItem.Get(e + "/input", this._gltf.accessors, i.input)
          , c = ArrayItem.Get(e + "/output", this._gltf.accessors, i.output);
        return i._data = Promise.all([this._loadFloatAccessorAsync("/accessors/" + s.index, s), this._loadFloatAccessorAsync("/accessors/" + c.index, c)]).then(function(d) {
            var _ = d[0]
              , b = d[1];
            return {
                input: _,
                interpolation: o,
                output: b
            }
        }),
        i._data
    }
    ,
    a.prototype.loadBufferAsync = function(e, i, o, s) {
        var c = this._extensionsLoadBufferAsync(e, i, o, s);
        if (c)
            return c;
        if (!i._data)
            if (i.uri)
                i._data = this.loadUriAsync(e + "/uri", i, i.uri);
            else {
                if (!this._bin)
                    throw new Error(e + ": Uri is missing or the binary glTF is missing its binary chunk");
                i._data = this._bin.readAsync(0, i.byteLength)
            }
        return i._data.then(function(d) {
            try {
                return new Uint8Array(d.buffer,d.byteOffset + o,s)
            } catch (_) {
                throw new Error(e + ": " + _.message)
            }
        })
    }
    ,
    a.prototype.loadBufferViewAsync = function(e, i) {
        var o = this._extensionsLoadBufferViewAsync(e, i);
        if (o)
            return o;
        if (i._data)
            return i._data;
        var s = ArrayItem.Get(e + "/buffer", this._gltf.buffers, i.buffer);
        return i._data = this.loadBufferAsync("/buffers/" + s.index, s, i.byteOffset || 0, i.byteLength),
        i._data
    }
    ,
    a.prototype._loadAccessorAsync = function(e, i, o) {
        var s = this;
        if (i._data)
            return i._data;
        var c = a._GetNumComponents(e, i.type)
          , d = c * VertexBuffer.GetTypeByteLength(i.componentType)
          , _ = c * i.count;
        if (i.bufferView == null)
            i._data = Promise.resolve(new o(_));
        else {
            var b = ArrayItem.Get(e + "/bufferView", this._gltf.bufferViews, i.bufferView);
            i._data = this.loadBufferViewAsync("/bufferViews/" + b.index, b).then(function(j) {
                if (i.componentType === 5126 && !i.normalized && (!b.byteStride || b.byteStride === d))
                    return a._GetTypedArray(e, i.componentType, j, i.byteOffset, _);
                var $ = new o(_);
                return VertexBuffer.ForEach(j, i.byteOffset || 0, b.byteStride || d, c, i.componentType, $.length, i.normalized || !1, function(_e, et) {
                    $[et] = _e
                }),
                $
            })
        }
        if (i.sparse) {
            var k = i.sparse;
            i._data = i._data.then(function(j) {
                var $ = j
                  , _e = ArrayItem.Get(e + "/sparse/indices/bufferView", s._gltf.bufferViews, k.indices.bufferView)
                  , et = ArrayItem.Get(e + "/sparse/values/bufferView", s._gltf.bufferViews, k.values.bufferView);
                return Promise.all([s.loadBufferViewAsync("/bufferViews/" + _e.index, _e), s.loadBufferViewAsync("/bufferViews/" + et.index, et)]).then(function(tt) {
                    var rt = tt[0], it = tt[1], nt = a._GetTypedArray(e + "/sparse/indices", k.indices.componentType, rt, k.indices.byteOffset, k.count), ot = c * k.count, at;
                    if (i.componentType === 5126 && !i.normalized)
                        at = a._GetTypedArray(e + "/sparse/values", i.componentType, it, k.values.byteOffset, ot);
                    else {
                        var st = a._GetTypedArray(e + "/sparse/values", i.componentType, it, k.values.byteOffset, ot);
                        at = new o(ot),
                        VertexBuffer.ForEach(st, 0, d, c, i.componentType, at.length, i.normalized || !1, function(ht, pt) {
                            at[pt] = ht
                        })
                    }
                    for (var ut = 0, ct = 0; ct < nt.length; ct++)
                        for (var lt = nt[ct] * c, ft = 0; ft < c; ft++)
                            $[lt++] = at[ut++];
                    return $
                })
            })
        }
        return i._data
    }
    ,
    a.prototype._loadFloatAccessorAsync = function(e, i) {
        return this._loadAccessorAsync(e, i, Float32Array)
    }
    ,
    a.prototype._loadIndicesAccessorAsync = function(e, i) {
        if (i.type !== "SCALAR")
            throw new Error(e + "/type: Invalid value " + i.type);
        if (i.componentType !== 5121 && i.componentType !== 5123 && i.componentType !== 5125)
            throw new Error(e + "/componentType: Invalid value " + i.componentType);
        if (i._data)
            return i._data;
        if (i.sparse) {
            var o = a._GetTypedArrayConstructor(e + "/componentType", i.componentType);
            i._data = this._loadAccessorAsync(e, i, o)
        } else {
            var s = ArrayItem.Get(e + "/bufferView", this._gltf.bufferViews, i.bufferView);
            i._data = this.loadBufferViewAsync("/bufferViews/" + s.index, s).then(function(c) {
                return a._GetTypedArray(e, i.componentType, c, i.byteOffset, i.count)
            })
        }
        return i._data
    }
    ,
    a.prototype._loadVertexBufferViewAsync = function(e, i) {
        var o = this;
        return e._babylonBuffer || (e._babylonBuffer = this.loadBufferViewAsync("/bufferViews/" + e.index, e).then(function(s) {
            return new Buffer(o._babylonScene.getEngine(),s,!1)
        })),
        e._babylonBuffer
    }
    ,
    a.prototype._loadVertexAccessorAsync = function(e, i, o) {
        var s = this, c;
        if (!((c = i._babylonVertexBuffer) === null || c === void 0) && c[o])
            return i._babylonVertexBuffer[o];
        if (i._babylonVertexBuffer || (i._babylonVertexBuffer = {}),
        i.sparse)
            i._babylonVertexBuffer[o] = this._loadFloatAccessorAsync(e, i).then(function(_) {
                return new VertexBuffer(s._babylonScene.getEngine(),_,o,!1)
            });
        else if (o === VertexBuffer.MatricesIndicesKind || o === VertexBuffer.MatricesIndicesExtraKind)
            i._babylonVertexBuffer[o] = this._loadFloatAccessorAsync(e, i).then(function(_) {
                return new VertexBuffer(s._babylonScene.getEngine(),_,o,!1)
            });
        else {
            var d = ArrayItem.Get(e + "/bufferView", this._gltf.bufferViews, i.bufferView);
            i._babylonVertexBuffer[o] = this._loadVertexBufferViewAsync(d, o).then(function(_) {
                var b = a._GetNumComponents(e, i.type);
                return new VertexBuffer(s._babylonScene.getEngine(),_,o,!1,!1,d.byteStride,!1,i.byteOffset,b,i.componentType,i.normalized,!0,1,!0)
            })
        }
        return i._babylonVertexBuffer[o]
    }
    ,
    a.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var s = new Array;
        return i && (i.baseColorFactor ? (o.albedoColor = Color3.FromArray(i.baseColorFactor),
        o.alpha = i.baseColorFactor[3]) : o.albedoColor = Color3.White(),
        o.metallic = i.metallicFactor == null ? 1 : i.metallicFactor,
        o.roughness = i.roughnessFactor == null ? 1 : i.roughnessFactor,
        i.baseColorTexture && s.push(this.loadTextureInfoAsync(e + "/baseColorTexture", i.baseColorTexture, function(c) {
            c.name = o.name + " (Base Color)",
            o.albedoTexture = c
        })),
        i.metallicRoughnessTexture && (i.metallicRoughnessTexture.nonColorData = !0,
        s.push(this.loadTextureInfoAsync(e + "/metallicRoughnessTexture", i.metallicRoughnessTexture, function(c) {
            c.name = o.name + " (Metallic Roughness)",
            o.metallicTexture = c
        })),
        o.useMetallnessFromMetallicTextureBlue = !0,
        o.useRoughnessFromMetallicTextureGreen = !0,
        o.useRoughnessFromMetallicTextureAlpha = !1)),
        Promise.all(s).then(function() {})
    }
    ,
    a.prototype._loadMaterialAsync = function(e, i, o, s, c) {
        c === void 0 && (c = function() {}
        );
        var d = this._extensionsLoadMaterialAsync(e, i, o, s, c);
        if (d)
            return d;
        i._data = i._data || {};
        var _ = i._data[s];
        if (!_) {
            this.logOpen(e + " " + (i.name || ""));
            var b = this.createMaterial(e, i, s);
            _ = {
                babylonMaterial: b,
                babylonMeshes: [],
                promise: this.loadMaterialPropertiesAsync(e, i, b)
            },
            i._data[s] = _,
            a.AddPointerMetadata(b, e),
            this._parent.onMaterialLoadedObservable.notifyObservers(b),
            this.logClose()
        }
        return o && (_.babylonMeshes.push(o),
        o.onDisposeObservable.addOnce(function() {
            var k = _.babylonMeshes.indexOf(o);
            k !== -1 && _.babylonMeshes.splice(k, 1)
        })),
        c(_.babylonMaterial),
        _.promise.then(function() {
            return _.babylonMaterial
        })
    }
    ,
    a.prototype._createDefaultMaterial = function(e, i) {
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var o = new PBRMaterial(e,this._babylonScene);
        return o._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        o.fillMode = i,
        o.enableSpecularAntiAliasing = !0,
        o.useRadianceOverAlpha = !this._parent.transparencyAsCoverage,
        o.useSpecularOverAlpha = !this._parent.transparencyAsCoverage,
        o.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE,
        o.metallic = 1,
        o.roughness = 1,
        o
    }
    ,
    a.prototype.createMaterial = function(e, i, o) {
        var s = this._extensionsCreateMaterial(e, i, o);
        if (s)
            return s;
        var c = i.name || "material" + i.index
          , d = this._createDefaultMaterial(c, o);
        return d
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this._extensionsLoadMaterialPropertiesAsync(e, i, o);
        if (s)
            return s;
        var c = new Array;
        return c.push(this.loadMaterialBasePropertiesAsync(e, i, o)),
        i.pbrMetallicRoughness && c.push(this._loadMaterialMetallicRoughnessPropertiesAsync(e + "/pbrMetallicRoughness", i.pbrMetallicRoughness, o)),
        this.loadMaterialAlphaProperties(e, i, o),
        Promise.all(c).then(function() {})
    }
    ,
    a.prototype.loadMaterialBasePropertiesAsync = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var s = new Array;
        return o.emissiveColor = i.emissiveFactor ? Color3.FromArray(i.emissiveFactor) : new Color3(0,0,0),
        i.doubleSided && (o.backFaceCulling = !1,
        o.twoSidedLighting = !0),
        i.normalTexture && (i.normalTexture.nonColorData = !0,
        s.push(this.loadTextureInfoAsync(e + "/normalTexture", i.normalTexture, function(c) {
            c.name = o.name + " (Normal)",
            o.bumpTexture = c
        })),
        o.invertNormalMapX = !this._babylonScene.useRightHandedSystem,
        o.invertNormalMapY = this._babylonScene.useRightHandedSystem,
        i.normalTexture.scale != null && (o.bumpTexture.level = i.normalTexture.scale),
        o.forceIrradianceInFragment = !0),
        i.occlusionTexture && (i.occlusionTexture.nonColorData = !0,
        s.push(this.loadTextureInfoAsync(e + "/occlusionTexture", i.occlusionTexture, function(c) {
            c.name = o.name + " (Occlusion)",
            o.ambientTexture = c
        })),
        o.useAmbientInGrayScale = !0,
        i.occlusionTexture.strength != null && (o.ambientTextureStrength = i.occlusionTexture.strength)),
        i.emissiveTexture && s.push(this.loadTextureInfoAsync(e + "/emissiveTexture", i.emissiveTexture, function(c) {
            c.name = o.name + " (Emissive)",
            o.emissiveTexture = c
        })),
        Promise.all(s).then(function() {})
    }
    ,
    a.prototype.loadMaterialAlphaProperties = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var s = i.alphaMode || "OPAQUE";
        switch (s) {
        case "OPAQUE":
            {
                o.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
                break
            }
        case "MASK":
            {
                o.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST,
                o.alphaCutOff = i.alphaCutoff == null ? .5 : i.alphaCutoff,
                o.albedoTexture && (o.albedoTexture.hasAlpha = !0);
                break
            }
        case "BLEND":
            {
                o.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND,
                o.albedoTexture && (o.albedoTexture.hasAlpha = !0,
                o.useAlphaFromAlbedoTexture = !0);
                break
            }
        default:
            throw new Error(e + "/alphaMode: Invalid value (" + i.alphaMode + ")")
        }
    }
    ,
    a.prototype.loadTextureInfoAsync = function(e, i, o) {
        var s = this;
        o === void 0 && (o = function() {}
        );
        var c = this._extensionsLoadTextureInfoAsync(e, i, o);
        if (c)
            return c;
        if (this.logOpen("" + e),
        i.texCoord >= 6)
            throw new Error(e + "/texCoord: Invalid value (" + i.texCoord + ")");
        var d = ArrayItem.Get(e + "/index", this._gltf.textures, i.index);
        d._textureInfo = i;
        var _ = this._loadTextureAsync("/textures/" + i.index, d, function(b) {
            b.coordinatesIndex = i.texCoord || 0,
            a.AddPointerMetadata(b, e),
            s._parent.onTextureLoadedObservable.notifyObservers(b),
            o(b)
        });
        return this.logClose(),
        _
    }
    ,
    a.prototype._loadTextureAsync = function(e, i, o) {
        o === void 0 && (o = function() {}
        );
        var s = this._extensionsLoadTextureAsync(e, i, o);
        if (s)
            return s;
        this.logOpen(e + " " + (i.name || ""));
        var c = i.sampler == null ? a.DefaultSampler : ArrayItem.Get(e + "/sampler", this._gltf.samplers, i.sampler)
          , d = ArrayItem.Get(e + "/source", this._gltf.images, i.source)
          , _ = this._createTextureAsync(e, c, d, o, void 0, !i._textureInfo.nonColorData);
        return this.logClose(),
        _
    }
    ,
    a.prototype._createTextureAsync = function(e, i, o, s, c, d) {
        var _ = this;
        s === void 0 && (s = function() {}
        );
        var b = this._loadSampler("/samplers/" + i.index, i)
          , k = new Array
          , j = new Deferred;
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var $ = {
            noMipmap: b.noMipMaps,
            invertY: !1,
            samplingMode: b.samplingMode,
            onLoad: function() {
                _._disposed || j.resolve()
            },
            onError: function(et, tt) {
                _._disposed || j.reject(new Error(e + ": " + (tt && tt.message ? tt.message : et || "Failed to load texture")))
            },
            mimeType: o.mimeType,
            loaderOptions: c,
            useSRGBBuffer: !!d && this._parent.useSRGBBuffers
        }
          , _e = new Texture(null,this._babylonScene,$);
        return _e._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        k.push(j.promise),
        k.push(this.loadImageAsync("/images/" + o.index, o).then(function(et) {
            var tt = o.uri || _._fileName + "#image" + o.index
              , rt = "data:" + _._uniqueRootUrl + tt;
            _e.updateURL(rt, et)
        })),
        _e.wrapU = b.wrapU,
        _e.wrapV = b.wrapV,
        s(_e),
        Promise.all(k).then(function() {
            return _e
        })
    }
    ,
    a.prototype._loadSampler = function(e, i) {
        return i._data || (i._data = {
            noMipMaps: i.minFilter === 9728 || i.minFilter === 9729,
            samplingMode: a._GetTextureSamplingMode(e, i),
            wrapU: a._GetTextureWrapMode(e + "/wrapS", i.wrapS),
            wrapV: a._GetTextureWrapMode(e + "/wrapT", i.wrapT)
        }),
        i._data
    }
    ,
    a.prototype.loadImageAsync = function(e, i) {
        if (!i._data) {
            if (this.logOpen(e + " " + (i.name || "")),
            i.uri)
                i._data = this.loadUriAsync(e + "/uri", i, i.uri);
            else {
                var o = ArrayItem.Get(e + "/bufferView", this._gltf.bufferViews, i.bufferView);
                i._data = this.loadBufferViewAsync("/bufferViews/" + o.index, o)
            }
            this.logClose()
        }
        return i._data
    }
    ,
    a.prototype.loadUriAsync = function(e, i, o) {
        var s = this
          , c = this._extensionsLoadUriAsync(e, i, o);
        if (c)
            return c;
        if (!a._ValidateUri(o))
            throw new Error(e + ": '" + o + "' is invalid");
        if (IsBase64DataUrl(o)) {
            var d = new Uint8Array(DecodeBase64UrlToBinary(o));
            return this.log(e + ": Decoded " + o.substr(0, 64) + "... (" + d.length + " bytes)"),
            Promise.resolve(d)
        }
        return this.log(e + ": Loading " + o),
        this._parent.preprocessUrlAsync(this._rootUrl + o).then(function(_) {
            return new Promise(function(b, k) {
                s._parent._loadFile(s._babylonScene, _, function(j) {
                    s._disposed || (s.log(e + ": Loaded " + o + " (" + j.byteLength + " bytes)"),
                    b(new Uint8Array(j)))
                }, !0, function(j) {
                    k(new LoadFileError(e + ": Failed to load '" + o + "'" + (j ? ": " + j.status + " " + j.statusText : ""),j))
                })
            }
            )
        })
    }
    ,
    a.AddPointerMetadata = function(e, i) {
        var o = e.metadata = e.metadata || {}
          , s = o.gltf = o.gltf || {}
          , c = s.pointers = s.pointers || [];
        c.push(i)
    }
    ,
    a._GetTextureWrapMode = function(e, i) {
        switch (i = i == null ? 10497 : i,
        i) {
        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 (" + i + ")"),
            Texture.WRAP_ADDRESSMODE
        }
    }
    ,
    a._GetTextureSamplingMode = function(e, i) {
        var o = i.magFilter == null ? 9729 : i.magFilter
          , s = i.minFilter == null ? 9987 : i.minFilter;
        if (o === 9729)
            switch (s) {
            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 (" + s + ")"),
                Texture.LINEAR_LINEAR_MIPLINEAR
            }
        else
            switch (o !== 9728 && Logger$2.Warn(e + "/magFilter: Invalid value (" + o + ")"),
            s) {
            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 (" + s + ")"),
                Texture.NEAREST_NEAREST_MIPNEAREST
            }
    }
    ,
    a._GetTypedArrayConstructor = function(e, i) {
        switch (i) {
        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 " + i)
        }
    }
    ,
    a._GetTypedArray = function(e, i, o, s, c) {
        var d = o.buffer;
        s = o.byteOffset + (s || 0);
        var _ = a._GetTypedArrayConstructor(e + "/componentType", i)
          , b = VertexBuffer.GetTypeByteLength(i);
        return s % b !== 0 ? (Logger$2.Warn(e + ": Copying buffer as byte offset (" + s + ") is not a multiple of component type byte length (" + b + ")"),
        new _(d.slice(s, s + c * b),0)) : new _(d,s,c)
    }
    ,
    a._GetNumComponents = function(e, i) {
        switch (i) {
        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 (" + i + ")")
    }
    ,
    a._ValidateUri = function(e) {
        return Tools.IsBase64(e) || e.indexOf("..") === -1
    }
    ,
    a._GetDrawMode = function(e, i) {
        switch (i == null && (i = 4),
        i) {
        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 (" + i + ")")
    }
    ,
    a.prototype._compileMaterialsAsync = function() {
        var e = this;
        this._parent._startPerformanceCounter("Compile materials");
        var i = new Array;
        if (this._gltf.materials)
            for (var o = 0, s = this._gltf.materials; o < s.length; o++) {
                var c = s[o];
                if (c._data)
                    for (var d in c._data)
                        for (var _ = c._data[d], b = 0, k = _.babylonMeshes; b < k.length; b++) {
                            var j = k[b];
                            j.computeWorldMatrix(!0);
                            var $ = _.babylonMaterial;
                            i.push($.forceCompilationAsync(j)),
                            i.push($.forceCompilationAsync(j, {
                                useInstances: !0
                            })),
                            this._parent.useClipPlane && (i.push($.forceCompilationAsync(j, {
                                clipPlane: !0
                            })),
                            i.push($.forceCompilationAsync(j, {
                                clipPlane: !0,
                                useInstances: !0
                            })))
                        }
            }
        return Promise.all(i).then(function() {
            e._parent._endPerformanceCounter("Compile materials")
        })
    }
    ,
    a.prototype._compileShadowGeneratorsAsync = function() {
        var e = this;
        this._parent._startPerformanceCounter("Compile shadow generators");
        for (var i = new Array, o = this._babylonScene.lights, s = 0, c = o; s < c.length; s++) {
            var d = c[s]
              , _ = d.getShadowGenerator();
            _ && i.push(_.forceCompilationAsync())
        }
        return Promise.all(i).then(function() {
            e._parent._endPerformanceCounter("Compile shadow generators")
        })
    }
    ,
    a.prototype._forEachExtensions = function(e) {
        for (var i = 0, o = this._extensions; i < o.length; i++) {
            var s = o[i];
            s.enabled && e(s)
        }
    }
    ,
    a.prototype._applyExtensions = function(e, i, o) {
        for (var s = 0, c = this._extensions; s < c.length; s++) {
            var d = c[s];
            if (d.enabled) {
                var _ = d.name + "." + i
                  , b = e;
                b._activeLoaderExtensionFunctions = b._activeLoaderExtensionFunctions || {};
                var k = b._activeLoaderExtensionFunctions;
                if (!k[_]) {
                    k[_] = !0;
                    try {
                        var j = o(d);
                        if (j)
                            return j
                    } finally {
                        delete k[_]
                    }
                }
            }
        }
        return null
    }
    ,
    a.prototype._extensionsOnLoading = function() {
        this._forEachExtensions(function(e) {
            return e.onLoading && e.onLoading()
        })
    }
    ,
    a.prototype._extensionsOnReady = function() {
        this._forEachExtensions(function(e) {
            return e.onReady && e.onReady()
        })
    }
    ,
    a.prototype._extensionsLoadSceneAsync = function(e, i) {
        return this._applyExtensions(i, "loadScene", function(o) {
            return o.loadSceneAsync && o.loadSceneAsync(e, i)
        })
    }
    ,
    a.prototype._extensionsLoadNodeAsync = function(e, i, o) {
        return this._applyExtensions(i, "loadNode", function(s) {
            return s.loadNodeAsync && s.loadNodeAsync(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadCameraAsync = function(e, i, o) {
        return this._applyExtensions(i, "loadCamera", function(s) {
            return s.loadCameraAsync && s.loadCameraAsync(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadVertexDataAsync = function(e, i, o) {
        return this._applyExtensions(i, "loadVertexData", function(s) {
            return s._loadVertexDataAsync && s._loadVertexDataAsync(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadMeshPrimitiveAsync = function(e, i, o, s, c, d) {
        return this._applyExtensions(c, "loadMeshPrimitive", function(_) {
            return _._loadMeshPrimitiveAsync && _._loadMeshPrimitiveAsync(e, i, o, s, c, d)
        })
    }
    ,
    a.prototype._extensionsLoadMaterialAsync = function(e, i, o, s, c) {
        return this._applyExtensions(i, "loadMaterial", function(d) {
            return d._loadMaterialAsync && d._loadMaterialAsync(e, i, o, s, c)
        })
    }
    ,
    a.prototype._extensionsCreateMaterial = function(e, i, o) {
        return this._applyExtensions(i, "createMaterial", function(s) {
            return s.createMaterial && s.createMaterial(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadMaterialPropertiesAsync = function(e, i, o) {
        return this._applyExtensions(i, "loadMaterialProperties", function(s) {
            return s.loadMaterialPropertiesAsync && s.loadMaterialPropertiesAsync(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadTextureInfoAsync = function(e, i, o) {
        return this._applyExtensions(i, "loadTextureInfo", function(s) {
            return s.loadTextureInfoAsync && s.loadTextureInfoAsync(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadTextureAsync = function(e, i, o) {
        return this._applyExtensions(i, "loadTexture", function(s) {
            return s._loadTextureAsync && s._loadTextureAsync(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadAnimationAsync = function(e, i) {
        return this._applyExtensions(i, "loadAnimation", function(o) {
            return o.loadAnimationAsync && o.loadAnimationAsync(e, i)
        })
    }
    ,
    a.prototype._extensionsLoadSkinAsync = function(e, i, o) {
        return this._applyExtensions(o, "loadSkin", function(s) {
            return s._loadSkinAsync && s._loadSkinAsync(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadUriAsync = function(e, i, o) {
        return this._applyExtensions(i, "loadUri", function(s) {
            return s._loadUriAsync && s._loadUriAsync(e, i, o)
        })
    }
    ,
    a.prototype._extensionsLoadBufferViewAsync = function(e, i) {
        return this._applyExtensions(i, "loadBufferView", function(o) {
            return o.loadBufferViewAsync && o.loadBufferViewAsync(e, i)
        })
    }
    ,
    a.prototype._extensionsLoadBufferAsync = function(e, i, o, s) {
        return this._applyExtensions(i, "loadBuffer", function(c) {
            return c.loadBufferAsync && c.loadBufferAsync(e, i, o, s)
        })
    }
    ,
    a.LoadExtensionAsync = function(e, i, o, s) {
        if (!i.extensions)
            return null;
        var c = i.extensions
          , d = c[o];
        return d ? s(e + "/extensions/" + o, d) : null
    }
    ,
    a.LoadExtraAsync = function(e, i, o, s) {
        if (!i.extras)
            return null;
        var c = i.extras
          , d = c[o];
        return d ? s(e + "/extras/" + o, d) : null
    }
    ,
    a.prototype.isExtensionUsed = function(e) {
        return !!this._gltf.extensionsUsed && this._gltf.extensionsUsed.indexOf(e) !== -1
    }
    ,
    a.prototype.logOpen = function(e) {
        this._parent._logOpen(e)
    }
    ,
    a.prototype.logClose = function() {
        this._parent._logClose()
    }
    ,
    a.prototype.log = function(e) {
        this._parent._log(e)
    }
    ,
    a.prototype.startPerformanceCounter = function(e) {
        this._parent._startPerformanceCounter(e)
    }
    ,
    a.prototype.endPerformanceCounter = function(e) {
        this._parent._endPerformanceCounter(e)
    }
    ,
    a._RegisteredExtensions = {},
    a.DefaultSampler = {
        index: -1
    },
    a
}();
GLTFFileLoader._CreateGLTF2Loader = function(a) {
    return new GLTFLoader(a)
}
;
var RawCubeTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j) {
        c === void 0 && (c = 5),
        d === void 0 && (d = 0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = !1),
        k === void 0 && (k = 3),
        j === void 0 && (j = null);
        var $ = a.call(this, "", i) || this;
        return $._texture = i.getEngine().createRawCubeTexture(o, s, c, d, _, b, k, j),
        $
    }
    return e.prototype.update = function(i, o, s, c, d) {
        d === void 0 && (d = null),
        this._texture.getEngine().updateRawCubeTexture(this._texture, i, o, s, c, d)
    }
    ,
    e.prototype.updateRGBDAsync = function(i, o, s, c) {
        return o === void 0 && (o = null),
        s === void 0 && (s = .8),
        c === void 0 && (c = 0),
        _UpdateRGBDAsync(this._texture, i, o, s, c).then(function() {})
    }
    ,
    e.prototype.clone = function() {
        var i = this;
        return SerializationHelper.Clone(function() {
            var o = i.getScene()
              , s = i._texture
              , c = new e(o,s._bufferViewArray,s.width,s.format,s.type,s.generateMipMaps,s.invertY,s.samplingMode,s._compression);
            return s.source === InternalTextureSource.CubeRawRGBD && c.updateRGBDAsync(s._bufferViewArrayArray, s._sphericalPolynomial, s._lodGenerationScale, s._lodGenerationOffset),
            c
        }, this)
    }
    ,
    e
}(CubeTexture)
  , NAME$u = "EXT_lights_image_based"
  , EXT_lights_image_based = function() {
    function a(e) {
        this.name = NAME$u,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$u)
    }
    return a.prototype.dispose = function() {
        this._loader = null,
        delete this._lights
    }
    ,
    a.prototype.onLoading = function() {
        var e = this._loader.gltf.extensions;
        if (e && e[this.name]) {
            var i = e[this.name];
            this._lights = i.lights
        }
    }
    ,
    a.prototype.loadSceneAsync = function(e, i) {
        var o = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(s, c) {
            var d = new Array;
            d.push(o._loader.loadSceneAsync(e, i)),
            o._loader.logOpen("" + s);
            var _ = ArrayItem.Get(s + "/light", o._lights, c.light);
            return d.push(o._loadLightAsync("/extensions/" + o.name + "/lights/" + c.light, _).then(function(b) {
                o._loader.babylonScene.environmentTexture = b
            })),
            o._loader.logClose(),
            Promise.all(d).then(function() {})
        })
    }
    ,
    a.prototype._loadLightAsync = function(e, i) {
        var o = this;
        if (!i._loaded) {
            var s = new Array;
            this._loader.logOpen("" + e);
            for (var c = new Array(i.specularImages.length), d = function(k) {
                var j = i.specularImages[k];
                c[k] = new Array(j.length);
                for (var $ = function(et) {
                    var tt = e + "/specularImages/" + k + "/" + et;
                    _._loader.logOpen("" + tt);
                    var rt = j[et]
                      , it = ArrayItem.Get(tt, _._loader.gltf.images, rt);
                    s.push(_._loader.loadImageAsync("/images/" + rt, it).then(function(nt) {
                        c[k][et] = nt
                    })),
                    _._loader.logClose()
                }, _e = 0; _e < j.length; _e++)
                    $(_e)
            }, _ = this, b = 0; b < i.specularImages.length; b++)
                d(b);
            this._loader.logClose(),
            i._loaded = Promise.all(s).then(function() {
                var k = new RawCubeTexture(o._loader.babylonScene,null,i.specularImageSize);
                if (k.name = i.name || "environment",
                i._babylonTexture = k,
                i.intensity != null && (k.level = i.intensity),
                i.rotation) {
                    var j = Quaternion.FromArray(i.rotation);
                    o._loader.babylonScene.useRightHandedSystem || (j = Quaternion.Inverse(j)),
                    Matrix.FromQuaternionToRef(j, k.getReflectionTextureMatrix())
                }
                if (!i.irradianceCoefficients)
                    throw new Error(e + ": Irradiance coefficients are missing");
                var $ = SphericalHarmonics.FromArray(i.irradianceCoefficients);
                $.scaleInPlace(i.intensity),
                $.convertIrradianceToLambertianRadiance();
                var _e = SphericalPolynomial.FromHarmonics($)
                  , et = (c.length - 1) / Scalar.Log2(i.specularImageSize);
                return k.updateRGBDAsync(c, _e, et)
            })
        }
        return i._loaded.then(function() {
            return i._babylonTexture
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$u, function(a) {
    return new EXT_lights_image_based(a)
});
var NAME$t = "EXT_mesh_gpu_instancing"
  , EXT_mesh_gpu_instancing = function() {
    function a(e) {
        this.name = NAME$t,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$t)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadNodeAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            s._loader._disableInstancedMesh++;
            var _ = s._loader.loadNodeAsync("/nodes/" + i.index, i, o);
            if (s._loader._disableInstancedMesh--,
            !i._primitiveBabylonMeshes)
                return _;
            var b = new Array
              , k = 0
              , j = function($) {
                if (d.attributes[$] == null) {
                    b.push(Promise.resolve(null));
                    return
                }
                var _e = ArrayItem.Get(c + "/attributes/" + $, s._loader.gltf.accessors, d.attributes[$]);
                if (b.push(s._loader._loadFloatAccessorAsync("/accessors/" + _e.bufferView, _e)),
                k === 0)
                    k = _e.count;
                else if (k !== _e.count)
                    throw new Error(c + "/attributes: Instance buffer accessors do not have the same count.")
            };
            return j("TRANSLATION"),
            j("ROTATION"),
            j("SCALE"),
            _.then(function($) {
                return Promise.all(b).then(function(_e) {
                    var et = _e[0]
                      , tt = _e[1]
                      , rt = _e[2]
                      , it = new Float32Array(k * 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 nt = 0; nt < k; ++nt)
                        et && Vector3.FromArrayToRef(et, nt * 3, TmpVectors.Vector3[0]),
                        tt && Quaternion.FromArrayToRef(tt, nt * 4, TmpVectors.Quaternion[0]),
                        rt && Vector3.FromArrayToRef(rt, nt * 3, TmpVectors.Vector3[1]),
                        Matrix.ComposeToRef(TmpVectors.Vector3[1], TmpVectors.Quaternion[0], TmpVectors.Vector3[0], TmpVectors.Matrix[0]),
                        TmpVectors.Matrix[0].copyToArray(it, nt * 16);
                    for (var ot = 0, at = i._primitiveBabylonMeshes; ot < at.length; ot++) {
                        var st = at[ot];
                        st.thinInstanceSetBuffer("matrix", it, 16, !0)
                    }
                    return $
                })
            })
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$t, function(a) {
    return new EXT_mesh_gpu_instancing(a)
});
var MeshoptCompression = function() {
    function a() {
        var e = a.Configuration.decoder;
        this._decoderModulePromise = Tools.LoadScriptAsync(Tools.GetAbsoluteUrl(e.url)).then(function() {
            return MeshoptDecoder.ready
        })
    }
    return Object.defineProperty(a, "Default", {
        get: function() {
            return a._Default || (a._Default = new a),
            a._Default
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.dispose = function() {
        delete this._decoderModulePromise
    }
    ,
    a.prototype.decodeGltfBufferAsync = function(e, i, o, s, c) {
        return this._decoderModulePromise.then(function() {
            var d = new Uint8Array(i * o);
            return MeshoptDecoder.decodeGltfBuffer(d, i, o, e, s, c),
            d
        })
    }
    ,
    a.Configuration = {
        decoder: {
            url: "https://preview.babylonjs.com/meshopt_decoder.js"
        }
    },
    a._Default = null,
    a
}()
  , NAME$s = "EXT_meshopt_compression"
  , EXT_meshopt_compression = function() {
    function a(e) {
        this.name = NAME$s,
        this.enabled = e.isExtensionUsed(NAME$s),
        this._loader = e
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadBufferViewAsync = function(e, i) {
        var o = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(s, c) {
            var d = i;
            if (d._meshOptData)
                return d._meshOptData;
            var _ = ArrayItem.Get(e + "/buffer", o._loader.gltf.buffers, c.buffer);
            return d._meshOptData = o._loader.loadBufferAsync("/buffers/" + _.index, _, c.byteOffset || 0, c.byteLength).then(function(b) {
                return MeshoptCompression.Default.decodeGltfBufferAsync(b, c.count, c.byteStride, c.mode, c.filter)
            }),
            d._meshOptData
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$s, function(a) {
    return new EXT_meshopt_compression(a)
});
var NAME$r = "EXT_texture_webp"
  , EXT_texture_webp = function() {
    function a(e) {
        this.name = NAME$r,
        this._loader = e,
        this.enabled = e.isExtensionUsed(NAME$r)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype._loadTextureAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = i.sampler == null ? GLTFLoader.DefaultSampler : ArrayItem.Get(e + "/sampler", s._loader.gltf.samplers, i.sampler)
              , b = ArrayItem.Get(c + "/source", s._loader.gltf.images, d.source);
            return s._loader._createTextureAsync(e, _, b, function(k) {
                o(k)
            }, void 0, !i._textureInfo.nonColorData)
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$r, function(a) {
    return new EXT_texture_webp(a)
});
var WorkerPool = function() {
    function a(e) {
        this._pendingActions = new Array,
        this._workerInfos = e.map(function(i) {
            return {
                worker: i,
                active: !1
            }
        })
    }
    return a.prototype.dispose = function() {
        for (var e = 0, i = this._workerInfos; e < i.length; e++) {
            var o = i[e];
            o.worker.terminate()
        }
        this._workerInfos = [],
        this._pendingActions = []
    }
    ,
    a.prototype.push = function(e) {
        for (var i = 0, o = this._workerInfos; i < o.length; i++) {
            var s = o[i];
            if (!s.active) {
                this._execute(s, e);
                return
            }
        }
        this._pendingActions.push(e)
    }
    ,
    a.prototype._execute = function(e, i) {
        var o = this;
        e.active = !0,
        i(e.worker, function() {
            e.active = !1;
            var s = o._pendingActions.shift();
            s && o._execute(e, s)
        })
    }
    ,
    a
}();
function createDecoderAsync(a) {
    return new Promise(function(e) {
        DracoDecoderModule({
            wasmBinary: a
        }).then(function(i) {
            e({
                module: i
            })
        })
    }
    )
}
function decodeMesh(a, e, i, o, s) {
    var c = new a.DecoderBuffer;
    c.Init(e, e.byteLength);
    var d = new a.Decoder, _, b;
    try {
        var k = d.GetEncodedGeometryType(c);
        switch (k) {
        case a.TRIANGULAR_MESH:
            _ = new a.Mesh,
            b = d.DecodeBufferToMesh(c, _);
            break;
        case a.POINT_CLOUD:
            _ = new a.PointCloud,
            b = d.DecodeBufferToPointCloud(c, _);
            break;
        default:
            throw new Error("Invalid geometry type " + k)
        }
        if (!b.ok() || !_.ptr)
            throw new Error(b.error_msg());
        if (k === a.TRIANGULAR_MESH) {
            var j = _.num_faces()
              , $ = j * 3
              , _e = $ * 4
              , et = a._malloc(_e);
            try {
                d.GetTrianglesUInt32Array(_, _e, et);
                var tt = new Uint32Array($);
                tt.set(new Uint32Array(a.HEAPF32.buffer,et,$)),
                o(tt)
            } finally {
                a._free(et)
            }
        }
        var rt = function(st, ut) {
            var ct = ut.num_components()
              , lt = _.num_points()
              , ft = lt * ct
              , ht = ft * Float32Array.BYTES_PER_ELEMENT
              , pt = a._malloc(ht);
            try {
                d.GetAttributeDataArrayForAllPoints(_, ut, a.DT_FLOAT32, ht, pt);
                var dt = new Float32Array(a.HEAPF32.buffer,pt,ft);
                if (st === "color" && ct === 3) {
                    for (var _t = new Float32Array(lt * 4), mt = 0, vt = 0; mt < _t.length; mt += 4,
                    vt += ct)
                        _t[mt + 0] = dt[vt + 0],
                        _t[mt + 1] = dt[vt + 1],
                        _t[mt + 2] = dt[vt + 2],
                        _t[mt + 3] = 1;
                    s(st, _t)
                } else {
                    var _t = new Float32Array(ft);
                    _t.set(new Float32Array(a.HEAPF32.buffer,pt,ft)),
                    s(st, _t)
                }
            } finally {
                a._free(pt)
            }
        };
        if (i)
            for (var it in i) {
                var nt = i[it]
                  , ot = d.GetAttributeByUniqueId(_, nt);
                rt(it, ot)
            }
        else {
            var at = {
                position: "POSITION",
                normal: "NORMAL",
                color: "COLOR",
                uv: "TEX_COORD"
            };
            for (var it in at) {
                var nt = d.GetAttributeId(_, a[at[it]]);
                if (nt !== -1) {
                    var ot = d.GetAttribute(_, nt);
                    rt(it, ot)
                }
            }
        }
    } finally {
        _ && a.destroy(_),
        a.destroy(d),
        a.destroy(c)
    }
}
function worker$1() {
    var a;
    onmessage = function(e) {
        var i = e.data;
        switch (i.id) {
        case "init":
            {
                var o = i.decoder;
                o.url && (importScripts(o.url),
                a = DracoDecoderModule({
                    wasmBinary: o.wasmBinary
                })),
                postMessage("done");
                break
            }
        case "decodeMesh":
            {
                if (!a)
                    throw new Error("Draco decoder module is not available");
                a.then(function(s) {
                    decodeMesh(s, i.dataView, i.attributes, function(c) {
                        postMessage({
                            id: "indices",
                            value: c
                        }, [c.buffer])
                    }, function(c, d) {
                        postMessage({
                            id: c,
                            value: d
                        }, [d.buffer])
                    }),
                    postMessage("done")
                });
                break
            }
        }
    }
}
var DracoCompression = function() {
    function a(e) {
        e === void 0 && (e = a.DefaultNumWorkers);
        var i = a.Configuration.decoder
          , o = i.wasmUrl && i.wasmBinaryUrl && typeof WebAssembly == "object" ? {
            url: Tools.GetAbsoluteUrl(i.wasmUrl),
            wasmBinaryPromise: Tools.LoadFileAsync(Tools.GetAbsoluteUrl(i.wasmBinaryUrl))
        } : {
            url: Tools.GetAbsoluteUrl(i.fallbackUrl),
            wasmBinaryPromise: Promise.resolve(void 0)
        };
        e && typeof Worker == "function" ? this._workerPoolPromise = o.wasmBinaryPromise.then(function(s) {
            for (var c = decodeMesh + "(" + worker$1 + ")()", d = URL.createObjectURL(new Blob([c],{
                type: "application/javascript"
            })), _ = new Array(e), b = 0; b < _.length; b++)
                _[b] = new Promise(function(k, j) {
                    var $ = new Worker(d)
                      , _e = function(tt) {
                        $.removeEventListener("error", _e),
                        $.removeEventListener("message", et),
                        j(tt)
                    }
                      , et = function(tt) {
                        tt.data === "done" && ($.removeEventListener("error", _e),
                        $.removeEventListener("message", et),
                        k($))
                    };
                    $.addEventListener("error", _e),
                    $.addEventListener("message", et),
                    $.postMessage({
                        id: "init",
                        decoder: {
                            url: o.url,
                            wasmBinary: s
                        }
                    })
                }
                );
            return Promise.all(_).then(function(k) {
                return new WorkerPool(k)
            })
        }) : this._decoderModulePromise = o.wasmBinaryPromise.then(function(s) {
            if (!o.url)
                throw new Error("Draco decoder module is not available");
            return Tools.LoadScriptAsync(o.url).then(function() {
                return createDecoderAsync(s)
            })
        })
    }
    return Object.defineProperty(a, "DecoderAvailable", {
        get: function() {
            var e = a.Configuration.decoder;
            return !!(e.wasmUrl && e.wasmBinaryUrl && typeof WebAssembly == "object" || e.fallbackUrl)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.GetDefaultNumWorkers = function() {
        return typeof navigator != "object" || !navigator.hardwareConcurrency ? 1 : Math.min(Math.floor(navigator.hardwareConcurrency * .5), 4)
    }
    ,
    Object.defineProperty(a, "Default", {
        get: function() {
            return a._Default || (a._Default = new a),
            a._Default
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.dispose = function() {
        this._workerPoolPromise && this._workerPoolPromise.then(function(e) {
            e.dispose()
        }),
        delete this._workerPoolPromise,
        delete this._decoderModulePromise
    }
    ,
    a.prototype.whenReadyAsync = function() {
        return this._workerPoolPromise ? this._workerPoolPromise.then(function() {}) : this._decoderModulePromise ? this._decoderModulePromise.then(function() {}) : Promise.resolve()
    }
    ,
    a.prototype.decodeMeshAsync = function(e, i) {
        var o = e instanceof ArrayBuffer ? new Uint8Array(e) : e;
        if (this._workerPoolPromise)
            return this._workerPoolPromise.then(function(s) {
                return new Promise(function(c, d) {
                    s.push(function(_, b) {
                        var k = new VertexData
                          , j = function(et) {
                            _.removeEventListener("error", j),
                            _.removeEventListener("message", $),
                            d(et),
                            b()
                        }
                          , $ = function(et) {
                            et.data === "done" ? (_.removeEventListener("error", j),
                            _.removeEventListener("message", $),
                            c(k),
                            b()) : et.data.id === "indices" ? k.indices = et.data.value : k.set(et.data.value, et.data.id)
                        };
                        _.addEventListener("error", j),
                        _.addEventListener("message", $);
                        var _e = new Uint8Array(o.byteLength);
                        _e.set(new Uint8Array(o.buffer,o.byteOffset,o.byteLength)),
                        _.postMessage({
                            id: "decodeMesh",
                            dataView: _e,
                            attributes: i
                        }, [_e.buffer])
                    })
                }
                )
            });
        if (this._decoderModulePromise)
            return this._decoderModulePromise.then(function(s) {
                var c = new VertexData;
                return decodeMesh(s.module, o, i, function(d) {
                    c.indices = d
                }, function(d, _) {
                    c.set(_, d)
                }),
                c
            });
        throw new Error("Draco decoder module is not available")
    }
    ,
    a.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"
        }
    },
    a.DefaultNumWorkers = a.GetDefaultNumWorkers(),
    a._Default = null,
    a
}()
  , NAME$q = "KHR_draco_mesh_compression"
  , KHR_draco_mesh_compression = function() {
    function a(e) {
        this.name = NAME$q,
        this._loader = e,
        this.enabled = DracoCompression.DecoderAvailable && this._loader.isExtensionUsed(NAME$q)
    }
    return a.prototype.dispose = function() {
        delete this.dracoCompression,
        this._loader = null
    }
    ,
    a.prototype._loadVertexDataAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            if (i.mode != null) {
                if (i.mode !== 5 && i.mode !== 4)
                    throw new Error(e + ": Unsupported mode " + i.mode);
                if (i.mode === 5)
                    throw new Error(e + ": Mode " + i.mode + " is not currently supported")
            }
            var _ = {}
              , b = function(j, $) {
                var _e = d.attributes[j];
                _e != null && (o._delayInfo = o._delayInfo || [],
                o._delayInfo.indexOf($) === -1 && o._delayInfo.push($),
                _[$] = _e)
            };
            b("POSITION", VertexBuffer.PositionKind),
            b("NORMAL", VertexBuffer.NormalKind),
            b("TANGENT", VertexBuffer.TangentKind),
            b("TEXCOORD_0", VertexBuffer.UVKind),
            b("TEXCOORD_1", VertexBuffer.UV2Kind),
            b("TEXCOORD_2", VertexBuffer.UV3Kind),
            b("TEXCOORD_3", VertexBuffer.UV4Kind),
            b("TEXCOORD_4", VertexBuffer.UV5Kind),
            b("TEXCOORD_5", VertexBuffer.UV6Kind),
            b("JOINTS_0", VertexBuffer.MatricesIndicesKind),
            b("WEIGHTS_0", VertexBuffer.MatricesWeightsKind),
            b("COLOR_0", VertexBuffer.ColorKind);
            var k = ArrayItem.Get(c, s._loader.gltf.bufferViews, d.bufferView);
            return k._dracoBabylonGeometry || (k._dracoBabylonGeometry = s._loader.loadBufferViewAsync("/bufferViews/" + k.index, k).then(function(j) {
                var $ = s.dracoCompression || DracoCompression.Default;
                return $.decodeMeshAsync(j, _).then(function(_e) {
                    var et = new Geometry(o.name,s._loader.babylonScene);
                    return _e.applyToGeometry(et),
                    et
                }).catch(function(_e) {
                    throw new Error(e + ": " + _e.message)
                })
            })),
            k._dracoBabylonGeometry
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$q, function(a) {
    return new KHR_draco_mesh_compression(a)
});
var NAME$p = "KHR_lights_punctual"
  , KHR_lights = function() {
    function a(e) {
        this.name = NAME$p,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$p)
    }
    return a.prototype.dispose = function() {
        this._loader = null,
        delete this._lights
    }
    ,
    a.prototype.onLoading = function() {
        var e = this._loader.gltf.extensions;
        if (e && e[this.name]) {
            var i = e[this.name];
            this._lights = i.lights
        }
    }
    ,
    a.prototype.loadNodeAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            return s._loader.loadNodeAsync(e, i, function(_) {
                var b, k = ArrayItem.Get(c, s._lights, d.light), j = k.name || _.name;
                switch (s._loader.babylonScene._blockEntityCollection = !!s._loader._assetContainer,
                k.type) {
                case "directional":
                    {
                        b = new DirectionalLight(j,Vector3.Backward(),s._loader.babylonScene);
                        break
                    }
                case "point":
                    {
                        b = new PointLight(j,Vector3.Zero(),s._loader.babylonScene);
                        break
                    }
                case "spot":
                    {
                        var $ = new SpotLight(j,Vector3.Zero(),Vector3.Backward(),0,1,s._loader.babylonScene);
                        $.angle = (k.spot && k.spot.outerConeAngle || Math.PI / 4) * 2,
                        $.innerAngle = (k.spot && k.spot.innerConeAngle || 0) * 2,
                        b = $;
                        break
                    }
                default:
                    throw s._loader.babylonScene._blockEntityCollection = !1,
                    new Error(c + ": Invalid light type (" + k.type + ")")
                }
                b._parentContainer = s._loader._assetContainer,
                s._loader.babylonScene._blockEntityCollection = !1,
                b.falloffType = Light.FALLOFF_GLTF,
                b.diffuse = k.color ? Color3.FromArray(k.color) : Color3.White(),
                b.intensity = k.intensity == null ? 1 : k.intensity,
                b.range = k.range == null ? Number.MAX_VALUE : k.range,
                b.parent = _,
                s._loader._babylonLights.push(b),
                GLTFLoader.AddPointerMetadata(b, c),
                o(_)
            })
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$p, function(a) {
    return new KHR_lights(a)
});
var NAME$o = "KHR_materials_pbrSpecularGlossiness"
  , KHR_materials_pbrSpecularGlossiness = function() {
    function a(e) {
        this.name = NAME$o,
        this.order = 200,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$o)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return _.push(s._loader.loadMaterialBasePropertiesAsync(e, i, o)),
            _.push(s._loadSpecularGlossinessPropertiesAsync(c, i, d, o)),
            s._loader.loadMaterialAlphaProperties(e, i, o),
            Promise.all(_).then(function() {})
        })
    }
    ,
    a.prototype._loadSpecularGlossinessPropertiesAsync = function(e, i, o, s) {
        if (!(s instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var c = new Array;
        return s.metallic = null,
        s.roughness = null,
        o.diffuseFactor ? (s.albedoColor = Color3.FromArray(o.diffuseFactor),
        s.alpha = o.diffuseFactor[3]) : s.albedoColor = Color3.White(),
        s.reflectivityColor = o.specularFactor ? Color3.FromArray(o.specularFactor) : Color3.White(),
        s.microSurface = o.glossinessFactor == null ? 1 : o.glossinessFactor,
        o.diffuseTexture && c.push(this._loader.loadTextureInfoAsync(e + "/diffuseTexture", o.diffuseTexture, function(d) {
            d.name = s.name + " (Diffuse)",
            s.albedoTexture = d
        })),
        o.specularGlossinessTexture && (c.push(this._loader.loadTextureInfoAsync(e + "/specularGlossinessTexture", o.specularGlossinessTexture, function(d) {
            d.name = s.name + " (Specular Glossiness)",
            s.reflectivityTexture = d
        })),
        s.reflectivityTexture.hasAlpha = !0,
        s.useMicroSurfaceFromReflectivityMapAlpha = !0),
        Promise.all(c).then(function() {})
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$o, function(a) {
    return new KHR_materials_pbrSpecularGlossiness(a)
});
var NAME$n = "KHR_materials_unlit"
  , KHR_materials_unlit$1 = function() {
    function a(e) {
        this.name = NAME$n,
        this.order = 210,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$n)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function() {
            return s._loadUnlitPropertiesAsync(e, i, o)
        })
    }
    ,
    a.prototype._loadUnlitPropertiesAsync = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var s = new Array;
        o.unlit = !0;
        var c = i.pbrMetallicRoughness;
        return c && (c.baseColorFactor ? (o.albedoColor = Color3.FromArray(c.baseColorFactor),
        o.alpha = c.baseColorFactor[3]) : o.albedoColor = Color3.White(),
        c.baseColorTexture && s.push(this._loader.loadTextureInfoAsync(e + "/baseColorTexture", c.baseColorTexture, function(d) {
            d.name = o.name + " (Base Color)",
            o.albedoTexture = d
        }))),
        i.doubleSided && (o.backFaceCulling = !1,
        o.twoSidedLighting = !0),
        this._loader.loadMaterialAlphaProperties(e, i, o),
        Promise.all(s).then(function() {})
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$n, function(a) {
    return new KHR_materials_unlit$1(a)
});
var NAME$m = "KHR_materials_clearcoat"
  , KHR_materials_clearcoat$1 = function() {
    function a(e) {
        this.name = NAME$m,
        this.order = 190,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$m)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return _.push(s._loader.loadMaterialPropertiesAsync(e, i, o)),
            _.push(s._loadClearCoatPropertiesAsync(c, d, o)),
            Promise.all(_).then(function() {})
        })
    }
    ,
    a.prototype._loadClearCoatPropertiesAsync = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var s = new Array;
        return o.clearCoat.isEnabled = !0,
        o.clearCoat.useRoughnessFromMainTexture = !1,
        o.clearCoat.remapF0OnInterfaceChange = !1,
        i.clearcoatFactor != null ? o.clearCoat.intensity = i.clearcoatFactor : o.clearCoat.intensity = 0,
        i.clearcoatTexture && s.push(this._loader.loadTextureInfoAsync(e + "/clearcoatTexture", i.clearcoatTexture, function(c) {
            c.name = o.name + " (ClearCoat Intensity)",
            o.clearCoat.texture = c
        })),
        i.clearcoatRoughnessFactor != null ? o.clearCoat.roughness = i.clearcoatRoughnessFactor : o.clearCoat.roughness = 0,
        i.clearcoatRoughnessTexture && (i.clearcoatRoughnessTexture.nonColorData = !0,
        s.push(this._loader.loadTextureInfoAsync(e + "/clearcoatRoughnessTexture", i.clearcoatRoughnessTexture, function(c) {
            c.name = o.name + " (ClearCoat Roughness)",
            o.clearCoat.textureRoughness = c
        }))),
        i.clearcoatNormalTexture && (i.clearcoatNormalTexture.nonColorData = !0,
        s.push(this._loader.loadTextureInfoAsync(e + "/clearcoatNormalTexture", i.clearcoatNormalTexture, function(c) {
            c.name = o.name + " (ClearCoat Normal)",
            o.clearCoat.bumpTexture = c
        })),
        o.invertNormalMapX = !o.getScene().useRightHandedSystem,
        o.invertNormalMapY = o.getScene().useRightHandedSystem,
        i.clearcoatNormalTexture.scale != null && (o.clearCoat.bumpTexture.level = i.clearcoatNormalTexture.scale)),
        Promise.all(s).then(function() {})
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$m, function(a) {
    return new KHR_materials_clearcoat$1(a)
});
var NAME$l = "KHR_materials_emissive_strength"
  , KHR_materials_emissive_strength = function() {
    function a(e) {
        this.name = NAME$l,
        this.order = 170,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$l)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            return s._loader.loadMaterialPropertiesAsync(e, i, o).then(function() {
                s._loadEmissiveProperties(c, d, o)
            })
        })
    }
    ,
    a.prototype._loadEmissiveProperties = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        i.emissiveStrength !== void 0 && o.emissiveColor.scaleToRef(i.emissiveStrength, o.emissiveColor)
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$l, function(a) {
    return new KHR_materials_emissive_strength(a)
});
var NAME$k = "KHR_materials_sheen"
  , KHR_materials_sheen$1 = function() {
    function a(e) {
        this.name = NAME$k,
        this.order = 190,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$k)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return _.push(s._loader.loadMaterialPropertiesAsync(e, i, o)),
            _.push(s._loadSheenPropertiesAsync(c, d, o)),
            Promise.all(_).then(function() {})
        })
    }
    ,
    a.prototype._loadSheenPropertiesAsync = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var s = new Array;
        return o.sheen.isEnabled = !0,
        o.sheen.intensity = 1,
        i.sheenColorFactor != null ? o.sheen.color = Color3.FromArray(i.sheenColorFactor) : o.sheen.color = Color3.Black(),
        i.sheenColorTexture && s.push(this._loader.loadTextureInfoAsync(e + "/sheenColorTexture", i.sheenColorTexture, function(c) {
            c.name = o.name + " (Sheen Color)",
            o.sheen.texture = c
        })),
        i.sheenRoughnessFactor !== void 0 ? o.sheen.roughness = i.sheenRoughnessFactor : o.sheen.roughness = 0,
        i.sheenRoughnessTexture && (i.sheenRoughnessTexture.nonColorData = !0,
        s.push(this._loader.loadTextureInfoAsync(e + "/sheenRoughnessTexture", i.sheenRoughnessTexture, function(c) {
            c.name = o.name + " (Sheen Roughness)",
            o.sheen.textureRoughness = c
        }))),
        o.sheen.albedoScaling = !0,
        o.sheen.useRoughnessFromMainTexture = !1,
        Promise.all(s).then(function() {})
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$k, function(a) {
    return new KHR_materials_sheen$1(a)
});
var NAME$j = "KHR_materials_specular"
  , KHR_materials_specular = function() {
    function a(e) {
        this.name = NAME$j,
        this.order = 190,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$j)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return _.push(s._loader.loadMaterialPropertiesAsync(e, i, o)),
            _.push(s._loadSpecularPropertiesAsync(c, d, o)),
            Promise.all(_).then(function() {})
        })
    }
    ,
    a.prototype._loadSpecularPropertiesAsync = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var s = new Array;
        return i.specularFactor !== void 0 && (o.metallicF0Factor = i.specularFactor),
        i.specularColorFactor !== void 0 && (o.metallicReflectanceColor = Color3.FromArray(i.specularColorFactor)),
        i.specularTexture && (i.specularTexture.nonColorData = !0,
        s.push(this._loader.loadTextureInfoAsync(e + "/specularTexture", i.specularTexture, function(c) {
            c.name = o.name + " (Specular F0 Strength)",
            o.metallicReflectanceTexture = c,
            o.useOnlyMetallicFromMetallicReflectanceTexture = !0
        }))),
        i.specularColorTexture && s.push(this._loader.loadTextureInfoAsync(e + "/specularColorTexture", i.specularColorTexture, function(c) {
            c.name = o.name + " (Specular F0 Color)",
            o.reflectanceTexture = c
        })),
        Promise.all(s).then(function() {})
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$j, function(a) {
    return new KHR_materials_specular(a)
});
var NAME$i = "KHR_materials_ior"
  , KHR_materials_ior = function() {
    function a(e) {
        this.name = NAME$i,
        this.order = 180,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$i)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return _.push(s._loader.loadMaterialPropertiesAsync(e, i, o)),
            _.push(s._loadIorPropertiesAsync(c, d, o)),
            Promise.all(_).then(function() {})
        })
    }
    ,
    a.prototype._loadIorPropertiesAsync = function(e, i, o) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        return i.ior !== void 0 ? o.indexOfRefraction = i.ior : o.indexOfRefraction = a._DEFAULT_IOR,
        Promise.resolve()
    }
    ,
    a._DEFAULT_IOR = 1.5,
    a
}();
GLTFLoader.RegisterExtension(NAME$i, function(a) {
    return new KHR_materials_ior(a)
});
var NAME$h = "KHR_materials_variants"
  , KHR_materials_variants = function() {
    function a(e) {
        this.name = NAME$h,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$h)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.GetAvailableVariants = function(e) {
        var i = this._GetExtensionMetadata(e);
        return i ? Object.keys(i.variants) : []
    }
    ,
    a.prototype.getAvailableVariants = function(e) {
        return a.GetAvailableVariants(e)
    }
    ,
    a.SelectVariant = function(e, i) {
        var o = this._GetExtensionMetadata(e);
        if (!o)
            throw new Error("Cannot select variant on a glTF mesh that does not have the " + NAME$h + " extension");
        var s = function(b) {
            var k = o.variants[b];
            if (k)
                for (var j = 0, $ = k; j < $.length; j++) {
                    var _e = $[j];
                    _e.mesh.material = _e.material
                }
        };
        if (i instanceof Array)
            for (var c = 0, d = i; c < d.length; c++) {
                var _ = d[c];
                s(_)
            }
        else
            s(i);
        o.lastSelected = i
    }
    ,
    a.prototype.selectVariant = function(e, i) {
        return a.SelectVariant(e, i)
    }
    ,
    a.Reset = function(e) {
        var i = this._GetExtensionMetadata(e);
        if (!i)
            throw new Error("Cannot reset on a glTF mesh that does not have the " + NAME$h + " extension");
        for (var o = 0, s = i.original; o < s.length; o++) {
            var c = s[o];
            c.mesh.material = c.material
        }
        i.lastSelected = null
    }
    ,
    a.prototype.reset = function(e) {
        return a.Reset(e)
    }
    ,
    a.GetLastSelectedVariant = function(e) {
        var i = this._GetExtensionMetadata(e);
        if (!i)
            throw new Error("Cannot get the last selected variant on a glTF mesh that does not have the " + NAME$h + " extension");
        return i.lastSelected
    }
    ,
    a.prototype.getLastSelectedVariant = function(e) {
        return a.GetLastSelectedVariant(e)
    }
    ,
    a._GetExtensionMetadata = function(e) {
        var i, o;
        return ((o = (i = e == null ? void 0 : e.metadata) === null || i === void 0 ? void 0 : i.gltf) === null || o === void 0 ? void 0 : o[NAME$h]) || null
    }
    ,
    a.prototype.onLoading = function() {
        var e = this._loader.gltf.extensions;
        if (e && e[this.name]) {
            var i = e[this.name];
            this._variants = i.variants
        }
    }
    ,
    a.prototype._loadMeshPrimitiveAsync = function(e, i, o, s, c, d) {
        var _ = this;
        return GLTFLoader.LoadExtensionAsync(e, c, this.name, function(b, k) {
            var j = new Array;
            return j.push(_._loader._loadMeshPrimitiveAsync(e, i, o, s, c, function($) {
                if (d($),
                $instanceof Mesh) {
                    var _e = GLTFLoader._GetDrawMode(e, c.mode)
                      , et = _._loader.rootBabylonMesh
                      , tt = et ? et.metadata = et.metadata || {} : {}
                      , rt = tt.gltf = tt.gltf || {}
                      , it = rt[NAME$h] = rt[NAME$h] || {
                        lastSelected: null,
                        original: [],
                        variants: {}
                    };
                    it.original.push({
                        mesh: $,
                        material: $.material
                    });
                    for (var nt = function(at) {
                        var st = k.mappings[at]
                          , ut = ArrayItem.Get(b + "/mappings/" + at + "/material", _._loader.gltf.materials, st.material);
                        j.push(_._loader._loadMaterialAsync("#/materials/" + st.material, ut, $, _e, function(ct) {
                            for (var lt = function(ht) {
                                var pt = st.variants[ht]
                                  , dt = ArrayItem.Get("/extensions/" + NAME$h + "/variants/" + pt, _._variants, pt);
                                it.variants[dt.name] = it.variants[dt.name] || [],
                                it.variants[dt.name].push({
                                    mesh: $,
                                    material: ct
                                }),
                                $.onClonedObservable.add(function(_t) {
                                    var mt = _t
                                      , vt = null
                                      , yt = mt;
                                    do {
                                        if (yt = yt.parent,
                                        !yt)
                                            return;
                                        vt = a._GetExtensionMetadata(yt)
                                    } while (vt === null);
                                    if (et && vt === a._GetExtensionMetadata(et)) {
                                        yt.metadata = {};
                                        for (var Et in et.metadata)
                                            yt.metadata[Et] = et.metadata[Et];
                                        yt.metadata.gltf = [];
                                        for (var Et in et.metadata.gltf)
                                            yt.metadata.gltf[Et] = et.metadata.gltf[Et];
                                        yt.metadata.gltf[NAME$h] = {
                                            lastSelected: null,
                                            original: [],
                                            variants: {}
                                        };
                                        for (var At = 0, gt = vt.original; At < gt.length; At++) {
                                            var St = gt[At];
                                            yt.metadata.gltf[NAME$h].original.push({
                                                mesh: St.mesh,
                                                material: St.material
                                            })
                                        }
                                        for (var Et in vt.variants)
                                            if (vt.variants.hasOwnProperty(Et)) {
                                                yt.metadata.gltf[NAME$h].variants[Et] = [];
                                                for (var xt = 0, bt = vt.variants[Et]; xt < bt.length; xt++) {
                                                    var Rt = bt[xt];
                                                    yt.metadata.gltf[NAME$h].variants[Et].push({
                                                        mesh: Rt.mesh,
                                                        material: Rt.material
                                                    })
                                                }
                                            }
                                        vt = yt.metadata.gltf[NAME$h]
                                    }
                                    for (var Mt = 0, Pt = vt.original; Mt < Pt.length; Mt++) {
                                        var It = Pt[Mt];
                                        It.mesh === $ && (It.mesh = mt)
                                    }
                                    for (var Dt = 0, Ct = vt.variants[dt.name]; Dt < Ct.length; Dt++) {
                                        var It = Ct[Dt];
                                        It.mesh === $ && (It.mesh = mt)
                                    }
                                })
                            }, ft = 0; ft < st.variants.length; ++ft)
                                lt(ft)
                        }))
                    }, ot = 0; ot < k.mappings.length; ++ot)
                        nt(ot)
                }
            })),
            Promise.all(j).then(function($) {
                var _e = $[0];
                return _e
            })
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$h, function(a) {
    return new KHR_materials_variants(a)
});
var TransmissionHelper = function() {
    function a(e, i) {
        var o = this;
        this._opaqueRenderTarget = null,
        this._opaqueMeshesCache = [],
        this._transparentMeshesCache = [],
        this._materialObservers = {},
        this._options = __assign(__assign({}, a._getDefaultOptions()), e),
        this._scene = i,
        this._scene._transmissionHelper = this,
        this.onErrorObservable = new Observable,
        this._scene.onDisposeObservable.addOnce(function(s) {
            o.dispose()
        }),
        this._parseScene(),
        this._setupRenderTargets()
    }
    return a._getDefaultOptions = function() {
        return {
            renderSize: 1024,
            samples: 4,
            lodGenerationScale: 1,
            lodGenerationOffset: -4,
            renderTargetTextureType: Constants.TEXTURETYPE_HALF_FLOAT,
            generateMipmaps: !0
        }
    }
    ,
    a.prototype.updateOptions = function(e) {
        var i = this
          , o = Object.keys(e).filter(function(d) {
            return i._options[d] !== e[d]
        });
        if (!!o.length) {
            var s = __assign(__assign({}, this._options), e)
              , c = this._options;
            this._options = s,
            s.renderSize !== c.renderSize || s.renderTargetTextureType !== c.renderTargetTextureType || s.generateMipmaps !== c.generateMipmaps || !this._opaqueRenderTarget ? this._setupRenderTargets() : (this._opaqueRenderTarget.samples = s.samples,
            this._opaqueRenderTarget.lodGenerationScale = s.lodGenerationScale,
            this._opaqueRenderTarget.lodGenerationOffset = s.lodGenerationOffset)
        }
    }
    ,
    a.prototype.getOpaqueTarget = function() {
        return this._opaqueRenderTarget
    }
    ,
    a.prototype.shouldRenderAsTransmission = function(e) {
        return e ? !!(e instanceof PBRMaterial && e.subSurface.isRefractionEnabled) : !1
    }
    ,
    a.prototype._addMesh = function(e) {
        var i = this;
        this._materialObservers[e.uniqueId] = e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),
        Tools.SetImmediate(function() {
            i.shouldRenderAsTransmission(e.material) ? (e.material.refractionTexture = i._opaqueRenderTarget,
            i._transparentMeshesCache.push(e)) : i._opaqueMeshesCache.push(e)
        })
    }
    ,
    a.prototype._removeMesh = function(e) {
        e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),
        delete this._materialObservers[e.uniqueId];
        var i = this._transparentMeshesCache.indexOf(e);
        i !== -1 && this._transparentMeshesCache.splice(i, 1),
        i = this._opaqueMeshesCache.indexOf(e),
        i !== -1 && this._opaqueMeshesCache.splice(i, 1)
    }
    ,
    a.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))
    }
    ,
    a.prototype._onMeshMaterialChanged = function(e) {
        var i = this._transparentMeshesCache.indexOf(e)
          , o = this._opaqueMeshesCache.indexOf(e)
          , s = this.shouldRenderAsTransmission(e.material);
        s ? (e.material instanceof PBRMaterial && (e.material.subSurface.refractionTexture = this._opaqueRenderTarget),
        o !== -1 ? (this._opaqueMeshesCache.splice(o, 1),
        this._transparentMeshesCache.push(e)) : i === -1 && this._transparentMeshesCache.push(e)) : i !== -1 ? (this._transparentMeshesCache.splice(i, 1),
        this._opaqueMeshesCache.push(e)) : o === -1 && this._opaqueMeshesCache.push(e)
    }
    ,
    a.prototype._setupRenderTargets = function() {
        var e = this, i, o;
        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 = (o = (i = this._options.clearColor) === null || i === void 0 ? void 0 : i.clone()) !== null && o !== void 0 ? o : 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 s, c;
        this._opaqueRenderTarget.onBeforeBindObservable.add(function(d) {
            c = e._scene.environmentIntensity,
            e._scene.environmentIntensity = 1,
            s = e._scene.imageProcessingConfiguration.applyByPostProcess,
            e._options.clearColor ? d.clearColor.copyFrom(e._options.clearColor) : e._scene.clearColor.toLinearSpaceToRef(d.clearColor),
            e._scene.imageProcessingConfiguration._applyByPostProcess = !0
        }),
        this._opaqueRenderTarget.onAfterUnbindObservable.add(function() {
            e._scene.environmentIntensity = c,
            e._scene.imageProcessingConfiguration._applyByPostProcess = s
        }),
        this._transparentMeshesCache.forEach(function(d) {
            e.shouldRenderAsTransmission(d.material) && (d.material.refractionTexture = e._opaqueRenderTarget)
        })
    }
    ,
    a.prototype.dispose = function() {
        this._scene._transmissionHelper = void 0,
        this._opaqueRenderTarget && (this._opaqueRenderTarget.dispose(),
        this._opaqueRenderTarget = null),
        this._transparentMeshesCache = [],
        this._opaqueMeshesCache = []
    }
    ,
    a
}()
  , NAME$g = "KHR_materials_transmission"
  , KHR_materials_transmission = function() {
    function a(e) {
        this.name = NAME$g,
        this.order = 175,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$g),
        this.enabled && (e.parent.transparencyAsCoverage = !0)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return _.push(s._loader.loadMaterialBasePropertiesAsync(e, i, o)),
            _.push(s._loader.loadMaterialPropertiesAsync(e, i, o)),
            _.push(s._loadTransparentPropertiesAsync(c, i, o, d)),
            Promise.all(_).then(function() {})
        })
    }
    ,
    a.prototype._loadTransparentPropertiesAsync = function(e, i, o, s) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var c = o;
        if (c.subSurface.isRefractionEnabled = !0,
        c.subSurface.volumeIndexOfRefraction = 1,
        c.subSurface.useAlbedoToTintRefraction = !0,
        s.transmissionFactor !== void 0) {
            c.subSurface.refractionIntensity = s.transmissionFactor;
            var d = c.getScene();
            c.subSurface.refractionIntensity && !d._transmissionHelper && new TransmissionHelper({},c.getScene())
        } else
            return c.subSurface.refractionIntensity = 0,
            c.subSurface.isRefractionEnabled = !1,
            Promise.resolve();
        return c.subSurface.minimumThickness = 0,
        c.subSurface.maximumThickness = 0,
        s.transmissionTexture ? (s.transmissionTexture.nonColorData = !0,
        this._loader.loadTextureInfoAsync(e + "/transmissionTexture", s.transmissionTexture, void 0).then(function(_) {
            c.subSurface.refractionIntensityTexture = _,
            c.subSurface.useGltfStyleTextures = !0
        })) : Promise.resolve()
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$g, function(a) {
    return new KHR_materials_transmission(a)
});
var NAME$f = "KHR_materials_translucency"
  , KHR_materials_translucency = function() {
    function a(e) {
        this.name = NAME$f,
        this.order = 174,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$f),
        this.enabled && (e.parent.transparencyAsCoverage = !0)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return _.push(s._loader.loadMaterialBasePropertiesAsync(e, i, o)),
            _.push(s._loader.loadMaterialPropertiesAsync(e, i, o)),
            _.push(s._loadTranslucentPropertiesAsync(c, i, o, d)),
            Promise.all(_).then(function() {})
        })
    }
    ,
    a.prototype._loadTranslucentPropertiesAsync = function(e, i, o, s) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var c = o;
        if (c.subSurface.isTranslucencyEnabled = !0,
        c.subSurface.volumeIndexOfRefraction = 1,
        c.subSurface.minimumThickness = 0,
        c.subSurface.maximumThickness = 0,
        c.subSurface.useAlbedoToTintTranslucency = !0,
        s.translucencyFactor !== void 0)
            c.subSurface.translucencyIntensity = s.translucencyFactor;
        else
            return c.subSurface.translucencyIntensity = 0,
            c.subSurface.isTranslucencyEnabled = !1,
            Promise.resolve();
        return s.translucencyTexture ? (s.translucencyTexture.nonColorData = !0,
        this._loader.loadTextureInfoAsync(e + "/translucencyTexture", s.translucencyTexture).then(function(d) {
            c.subSurface.translucencyIntensityTexture = d
        })) : Promise.resolve()
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$f, function(a) {
    return new KHR_materials_translucency(a)
});
var NAME$e = "KHR_materials_volume"
  , KHR_materials_volume = function() {
    function a(e) {
        this.name = NAME$e,
        this.order = 173,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$e),
        this.enabled && this._loader._disableInstancedMesh++
    }
    return a.prototype.dispose = function() {
        this.enabled && this._loader._disableInstancedMesh--,
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return _.push(s._loader.loadMaterialBasePropertiesAsync(e, i, o)),
            _.push(s._loader.loadMaterialPropertiesAsync(e, i, o)),
            _.push(s._loadVolumePropertiesAsync(c, i, o, d)),
            Promise.all(_).then(function() {})
        })
    }
    ,
    a.prototype._loadVolumePropertiesAsync = function(e, i, o, s) {
        if (!(o instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        if (!o.subSurface.isRefractionEnabled && !o.subSurface.isTranslucencyEnabled || !s.thicknessFactor)
            return Promise.resolve();
        o.subSurface.volumeIndexOfRefraction = o.indexOfRefraction;
        var c = s.attenuationDistance !== void 0 ? s.attenuationDistance : Number.MAX_VALUE;
        return o.subSurface.tintColorAtDistance = c,
        s.attenuationColor !== void 0 && s.attenuationColor.length == 3 && o.subSurface.tintColor.copyFromFloats(s.attenuationColor[0], s.attenuationColor[1], s.attenuationColor[2]),
        o.subSurface.minimumThickness = 0,
        o.subSurface.maximumThickness = s.thicknessFactor,
        o.subSurface.useThicknessAsDepth = !0,
        s.thicknessTexture ? (s.thicknessTexture.nonColorData = !0,
        this._loader.loadTextureInfoAsync(e + "/thicknessTexture", s.thicknessTexture).then(function(d) {
            o.subSurface.thicknessTexture = d,
            o.subSurface.useGltfStyleTextures = !0
        })) : Promise.resolve()
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$e, function(a) {
    return new KHR_materials_volume(a)
});
var NAME$d = "KHR_mesh_quantization"
  , KHR_mesh_quantization = function() {
    function a(e) {
        this.name = NAME$d,
        this.enabled = e.isExtensionUsed(NAME$d)
    }
    return a.prototype.dispose = function() {}
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$d, function(a) {
    return new KHR_mesh_quantization(a)
});
var NAME$c = "KHR_texture_basisu"
  , KHR_texture_basisu = function() {
    function a(e) {
        this.name = NAME$c,
        this._loader = e,
        this.enabled = e.isExtensionUsed(NAME$c)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype._loadTextureAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = i.sampler == null ? GLTFLoader.DefaultSampler : ArrayItem.Get(e + "/sampler", s._loader.gltf.samplers, i.sampler)
              , b = ArrayItem.Get(c + "/source", s._loader.gltf.images, d.source);
            return s._loader._createTextureAsync(e, _, b, function(k) {
                o(k)
            }, i._textureInfo.nonColorData ? {
                useRGBAIfASTCBC7NotAvailableWhenUASTC: !0
            } : void 0, !i._textureInfo.nonColorData)
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$c, function(a) {
    return new KHR_texture_basisu(a)
});
var NAME$b = "KHR_texture_transform"
  , KHR_texture_transform$1 = function() {
    function a(e) {
        this.name = NAME$b,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$b)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadTextureInfoAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            return s._loader.loadTextureInfoAsync(e, i, function(_) {
                if (!(_ instanceof Texture))
                    throw new Error(c + ": Texture type not supported");
                d.offset && (_.uOffset = d.offset[0],
                _.vOffset = d.offset[1]),
                _.uRotationCenter = 0,
                _.vRotationCenter = 0,
                d.rotation && (_.wAng = -d.rotation),
                d.scale && (_.uScale = d.scale[0],
                _.vScale = d.scale[1]),
                d.texCoord != null && (_.coordinatesIndex = d.texCoord),
                o(_)
            })
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$b, function(a) {
    return new KHR_texture_transform$1(a)
});
var NAME$a = "KHR_xmp_json_ld"
  , KHR_xmp_json_ld = function() {
    function a(e) {
        this.name = NAME$a,
        this.order = 100,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$a)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.onLoading = function() {
        var e, i, o;
        if (this._loader.rootBabylonMesh !== null) {
            var s = (e = this._loader.gltf.extensions) === null || e === void 0 ? void 0 : e.KHR_xmp_json_ld
              , c = (o = (i = this._loader.gltf.asset) === null || i === void 0 ? void 0 : i.extensions) === null || o === void 0 ? void 0 : o.KHR_xmp_json_ld;
            if (s && c) {
                var d = +c.packet;
                s.packets && d < s.packets.length && (this._loader.rootBabylonMesh.metadata = this._loader.rootBabylonMesh.metadata || {},
                this._loader.rootBabylonMesh.metadata.xmp = s.packets[d])
            }
        }
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$a, function(a) {
    return new KHR_xmp_json_ld(a)
});
var AnimationEvent = function() {
    function a(e, i, o) {
        this.frame = e,
        this.action = i,
        this.onlyOnce = o,
        this.isDone = !1
    }
    return a.prototype._clone = function() {
        return new a(this.frame,this.action,this.onlyOnce)
    }
    ,
    a
}()
  , WeightedSound = function() {
    function a(e, i, o) {
        var s = this;
        if (this.loop = !1,
        this._coneInnerAngle = 360,
        this._coneOuterAngle = 360,
        this._volume = 1,
        this.isPlaying = !1,
        this.isPaused = !1,
        this._sounds = [],
        this._weights = [],
        i.length !== o.length)
            throw new Error("Sounds length does not equal weights length");
        this.loop = e,
        this._weights = o;
        for (var c = 0, d = 0, _ = o; d < _.length; d++) {
            var b = _[d];
            c += b
        }
        for (var k = c > 0 ? 1 / c : 0, j = 0; j < this._weights.length; j++)
            this._weights[j] *= k;
        this._sounds = i;
        for (var $ = 0, _e = this._sounds; $ < _e.length; $++) {
            var et = _e[$];
            et.onEndedObservable.add(function() {
                s._onended()
            })
        }
    }
    return Object.defineProperty(a.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 i = 0, o = this._sounds; i < o.length; i++) {
                    var s = o[i];
                    s.directionalConeInnerAngle = e
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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 i = 0, o = this._sounds; i < o.length; i++) {
                    var s = o[i];
                    s.directionalConeOuterAngle = e
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "volume", {
        get: function() {
            return this._volume
        },
        set: function(e) {
            if (e !== this._volume)
                for (var i = 0, o = this._sounds; i < o.length; i++) {
                    var s = o[i];
                    s.setVolume(e)
                }
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._onended = function() {
        this._currentIndex !== void 0 && (this._sounds[this._currentIndex].autoplay = !1),
        this.loop && this.isPlaying ? this.play() : this.isPlaying = !1
    }
    ,
    a.prototype.pause = function() {
        this.isPaused = !0,
        this._currentIndex !== void 0 && this._sounds[this._currentIndex].pause()
    }
    ,
    a.prototype.stop = function() {
        this.isPlaying = !1,
        this._currentIndex !== void 0 && this._sounds[this._currentIndex].stop()
    }
    ,
    a.prototype.play = function(e) {
        if (!this.isPaused) {
            this.stop();
            for (var i = Math.random(), o = 0, s = 0; s < this._weights.length; s++)
                if (o += this._weights[s],
                i <= o) {
                    this._currentIndex = s;
                    break
                }
        }
        var c = this._sounds[this._currentIndex];
        c.isReady() ? c.play(0, this.isPaused ? void 0 : e) : c.autoplay = !0,
        this.isPlaying = !0,
        this.isPaused = !1
    }
    ,
    a
}()
  , NAME$9 = "MSFT_audio_emitter"
  , MSFT_audio_emitter = function() {
    function a(e) {
        this.name = NAME$9,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$9)
    }
    return a.prototype.dispose = function() {
        this._loader = null,
        this._clips = null,
        this._emitters = null
    }
    ,
    a.prototype.onLoading = function() {
        var e = this._loader.gltf.extensions;
        if (e && e[this.name]) {
            var i = e[this.name];
            this._clips = i.clips,
            this._emitters = i.emitters,
            ArrayItem.Assign(this._clips),
            ArrayItem.Assign(this._emitters)
        }
    }
    ,
    a.prototype.loadSceneAsync = function(e, i) {
        var o = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(s, c) {
            var d = new Array;
            d.push(o._loader.loadSceneAsync(e, i));
            for (var _ = 0, b = c.emitters; _ < b.length; _++) {
                var k = b[_]
                  , j = ArrayItem.Get(s + "/emitters", o._emitters, k);
                if (j.refDistance != null || j.maxDistance != null || j.rolloffFactor != null || j.distanceModel != null || j.innerAngle != null || j.outerAngle != null)
                    throw new Error(s + ": Direction or Distance properties are not allowed on emitters attached to a scene");
                d.push(o._loadEmitterAsync(s + "/emitters/" + j.index, j))
            }
            return Promise.all(d).then(function() {})
        })
    }
    ,
    a.prototype.loadNodeAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _ = new Array;
            return s._loader.loadNodeAsync(c, i, function(b) {
                for (var k = function(et) {
                    var tt = ArrayItem.Get(c + "/emitters", s._emitters, et);
                    _.push(s._loadEmitterAsync(c + "/emitters/" + tt.index, tt).then(function() {
                        for (var rt = 0, it = tt._babylonSounds; rt < it.length; rt++) {
                            var nt = it[rt];
                            nt.attachToMesh(b),
                            (tt.innerAngle != null || tt.outerAngle != null) && (nt.setLocalDirectionToMesh(Vector3.Forward()),
                            nt.setDirectionalCone(2 * Tools.ToDegrees(tt.innerAngle == null ? Math.PI : tt.innerAngle), 2 * Tools.ToDegrees(tt.outerAngle == null ? Math.PI : tt.outerAngle), 0))
                        }
                    }))
                }, j = 0, $ = d.emitters; j < $.length; j++) {
                    var _e = $[j];
                    k(_e)
                }
                o(b)
            }).then(function(b) {
                return Promise.all(_).then(function() {
                    return b
                })
            })
        })
    }
    ,
    a.prototype.loadAnimationAsync = function(e, i) {
        var o = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(s, c) {
            return o._loader.loadAnimationAsync(e, i).then(function(d) {
                var _ = new Array;
                ArrayItem.Assign(c.events);
                for (var b = 0, k = c.events; b < k.length; b++) {
                    var j = k[b];
                    _.push(o._loadAnimationEventAsync(s + "/events/" + j.index, e, i, j, d))
                }
                return Promise.all(_).then(function() {
                    return d
                })
            })
        })
    }
    ,
    a.prototype._loadClipAsync = function(e, i) {
        if (i._objectURL)
            return i._objectURL;
        var o;
        if (i.uri)
            o = this._loader.loadUriAsync(e, i, i.uri);
        else {
            var s = ArrayItem.Get(e + "/bufferView", this._loader.gltf.bufferViews, i.bufferView);
            o = this._loader.loadBufferViewAsync("/bufferViews/" + s.index, s)
        }
        return i._objectURL = o.then(function(c) {
            return URL.createObjectURL(new Blob([c],{
                type: i.mimeType
            }))
        }),
        i._objectURL
    }
    ,
    a.prototype._loadEmitterAsync = function(e, i) {
        var o = this;
        if (i._babylonSounds = i._babylonSounds || [],
        !i._babylonData) {
            for (var s = new Array, c = i.name || "emitter" + i.index, d = {
                loop: !1,
                autoplay: !1,
                volume: i.volume == null ? 1 : i.volume
            }, _ = function($) {
                var _e = "/extensions/" + b.name + "/clips"
                  , et = ArrayItem.Get(_e, b._clips, i.clips[$].clip);
                s.push(b._loadClipAsync(_e + "/" + i.clips[$].clip, et).then(function(tt) {
                    var rt = i._babylonSounds[$] = new Sound(c,tt,o._loader.babylonScene,null,d);
                    rt.refDistance = i.refDistance || 1,
                    rt.maxDistance = i.maxDistance || 256,
                    rt.rolloffFactor = i.rolloffFactor || 1,
                    rt.distanceModel = i.distanceModel || "exponential"
                }))
            }, b = this, k = 0; k < i.clips.length; k++)
                _(k);
            var j = Promise.all(s).then(function() {
                var $ = i.clips.map(function(et) {
                    return et.weight || 1
                })
                  , _e = new WeightedSound(i.loop || !1,i._babylonSounds,$);
                i.innerAngle && (_e.directionalConeInnerAngle = 2 * Tools.ToDegrees(i.innerAngle)),
                i.outerAngle && (_e.directionalConeOuterAngle = 2 * Tools.ToDegrees(i.outerAngle)),
                i.volume && (_e.volume = i.volume),
                i._babylonData.sound = _e
            });
            i._babylonData = {
                loaded: j
            }
        }
        return i._babylonData.loaded
    }
    ,
    a.prototype._getEventAction = function(e, i, o, s, c) {
        switch (o) {
        case "play":
            return function(d) {
                var _ = (c || 0) + (d - s);
                i.play(_)
            }
            ;
        case "stop":
            return function(d) {
                i.stop()
            }
            ;
        case "pause":
            return function(d) {
                i.pause()
            }
            ;
        default:
            throw new Error(e + ": Unsupported action " + o)
        }
    }
    ,
    a.prototype._loadAnimationEventAsync = function(e, i, o, s, c) {
        var d = this;
        if (c.targetedAnimations.length == 0)
            return Promise.resolve();
        var _ = c.targetedAnimations[0]
          , b = s.emitter
          , k = ArrayItem.Get("/extensions/" + this.name + "/emitters", this._emitters, b);
        return this._loadEmitterAsync(e, k).then(function() {
            var j = k._babylonData.sound;
            if (j) {
                var $ = new AnimationEvent(s.time,d._getEventAction(e, j, s.action, s.time, s.startOffset));
                _.animation.addEvent($),
                c.onAnimationGroupEndObservable.add(function() {
                    j.stop()
                }),
                c.onAnimationGroupPauseObservable.add(function() {
                    j.pause()
                })
            }
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$9, function(a) {
    return new MSFT_audio_emitter(a)
});
var NAME$8 = "MSFT_lod"
  , MSFT_lod = function() {
    function a(e) {
        this.name = NAME$8,
        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$8)
    }
    return a.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()
    }
    ,
    a.prototype.onReady = function() {
        for (var e = this, i = function(_) {
            var b = Promise.all(o._nodePromiseLODs[_]).then(function() {
                _ !== 0 && (e._loader.endPerformanceCounter("Node LOD " + _),
                e._loader.log("Loaded node LOD " + _)),
                e.onNodeLODsLoadedObservable.notifyObservers(_),
                _ !== e._nodePromiseLODs.length - 1 && (e._loader.startPerformanceCounter("Node LOD " + (_ + 1)),
                e._loadBufferLOD(e._nodeBufferLODs, _ + 1),
                e._nodeSignalLODs[_] && e._nodeSignalLODs[_].resolve())
            });
            o._loader._completePromises.push(b)
        }, o = this, s = 0; s < this._nodePromiseLODs.length; s++)
            i(s);
        for (var c = function(_) {
            var b = Promise.all(d._materialPromiseLODs[_]).then(function() {
                _ !== 0 && (e._loader.endPerformanceCounter("Material LOD " + _),
                e._loader.log("Loaded material LOD " + _)),
                e.onMaterialLODsLoadedObservable.notifyObservers(_),
                _ !== e._materialPromiseLODs.length - 1 && (e._loader.startPerformanceCounter("Material LOD " + (_ + 1)),
                e._loadBufferLOD(e._materialBufferLODs, _ + 1),
                e._materialSignalLODs[_] && e._materialSignalLODs[_].resolve())
            });
            d._loader._completePromises.push(b)
        }, d = this, s = 0; s < this._materialPromiseLODs.length; s++)
            c(s)
    }
    ,
    a.prototype.loadSceneAsync = function(e, i) {
        var o = this._loader.loadSceneAsync(e, i);
        return this._loadBufferLOD(this._bufferLODs, 0),
        o
    }
    ,
    a.prototype.loadNodeAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, i, this.name, function(c, d) {
            var _, b = s._getLODs(c, i, s._loader.gltf.nodes, d.ids);
            s._loader.logOpen("" + c);
            for (var k = [], j = 0; j < b.length; j++)
                k.push(null);
            for (var $ = function(_e) {
                var et = b[_e];
                _e !== 0 && (s._nodeIndexLOD = _e,
                s._nodeSignalLODs[_e] = s._nodeSignalLODs[_e] || new Deferred);
                var tt = function(it, nt) {
                    var ot, at, st;
                    it.setEnabled(!1),
                    k[nt] = it;
                    for (var ut = !0, ct = 0; ct < k.length; ct++)
                        k[ct] || (ut = !1);
                    var lt = k[k.length - 1];
                    if (ut && lt && s._isMesh(lt)) {
                        var ft = (st = (at = (ot = lt.metadata) === null || ot === void 0 ? void 0 : ot.gltf) === null || at === void 0 ? void 0 : at.extras) === null || st === void 0 ? void 0 : st.MSFT_screencoverage;
                        if (ft && ft.length) {
                            ft.reverse(),
                            lt.useLODScreenCoverage = !0;
                            for (var ct = 0; ct < k.length - 1; ct++) {
                                var ht = k[ct];
                                ht && s._isMesh(ht) && lt.addLODLevel(ft[ct + 1], ht)
                            }
                            ft[0] > 0 && lt.addLODLevel(ft[0], null)
                        }
                    }
                }
                  , rt = s._loader.loadNodeAsync("/nodes/" + et.index, et, function(it) {
                    return tt(it, _e)
                }).then(function(it) {
                    var nt, ot, at, st = (at = (ot = (nt = b[b.length - 1]._babylonTransformNode.metadata) === null || nt === void 0 ? void 0 : nt.gltf) === null || ot === void 0 ? void 0 : ot.extras) === null || at === void 0 ? void 0 : at.MSFT_screencoverage;
                    if (_e !== 0 && !st) {
                        var ut = b[_e - 1];
                        ut._babylonTransformNode && (s._disposeTransformNode(ut._babylonTransformNode),
                        delete ut._babylonTransformNode)
                    }
                    return o(it),
                    it.setEnabled(!0),
                    it
                });
                s._nodePromiseLODs[_e] = s._nodePromiseLODs[_e] || [],
                _e === 0 ? _ = rt : (s._nodeIndexLOD = null,
                s._nodePromiseLODs[_e].push(rt))
            }, j = 0; j < b.length; j++)
                $(j);
            return s._loader.logClose(),
            _
        })
    }
    ,
    a.prototype._loadMaterialAsync = function(e, i, o, s, c) {
        var d = this;
        return this._nodeIndexLOD ? null : GLTFLoader.LoadExtensionAsync(e, i, this.name, function(_, b) {
            var k, j = d._getLODs(_, i, d._loader.gltf.materials, b.ids);
            d._loader.logOpen("" + _);
            for (var $ = function(et) {
                var tt = j[et];
                et !== 0 && (d._materialIndexLOD = et);
                var rt = d._loader._loadMaterialAsync("/materials/" + tt.index, tt, o, s, function(it) {
                    et === 0 && c(it)
                }).then(function(it) {
                    if (et !== 0) {
                        c(it);
                        var nt = j[et - 1]._data;
                        nt[s] && (d._disposeMaterials([nt[s].babylonMaterial]),
                        delete nt[s])
                    }
                    return it
                });
                d._materialPromiseLODs[et] = d._materialPromiseLODs[et] || [],
                et === 0 ? k = rt : (d._materialIndexLOD = null,
                d._materialPromiseLODs[et].push(rt))
            }, _e = 0; _e < j.length; _e++)
                $(_e);
            return d._loader.logClose(),
            k
        })
    }
    ,
    a.prototype._loadUriAsync = function(e, i, o) {
        var s = this;
        if (this._nodeIndexLOD !== null) {
            this._loader.log("deferred");
            var c = this._nodeIndexLOD - 1;
            return this._nodeSignalLODs[c] = this._nodeSignalLODs[c] || new Deferred,
            this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function() {
                return s._loader.loadUriAsync(e, i, o)
            })
        } else if (this._materialIndexLOD !== null) {
            this._loader.log("deferred");
            var c = this._materialIndexLOD - 1;
            return this._materialSignalLODs[c] = this._materialSignalLODs[c] || new Deferred,
            this._materialSignalLODs[c].promise.then(function() {
                return s._loader.loadUriAsync(e, i, o)
            })
        }
        return null
    }
    ,
    a.prototype.loadBufferAsync = function(e, i, o, s) {
        if (this._loader.parent.useRangeRequests && !i.uri) {
            if (!this._loader.bin)
                throw new Error(e + ": Uri is missing or the binary glTF is missing its binary chunk");
            var c = function(d, _) {
                var b = o
                  , k = b + s - 1
                  , j = d[_];
                return j ? (j.start = Math.min(j.start, b),
                j.end = Math.max(j.end, k)) : (j = {
                    start: b,
                    end: k,
                    loaded: new Deferred
                },
                d[_] = j),
                j.loaded.promise.then(function($) {
                    return new Uint8Array($.buffer,$.byteOffset + o - j.start,s)
                })
            };
            return this._loader.log("deferred"),
            this._nodeIndexLOD !== null ? c(this._nodeBufferLODs, this._nodeIndexLOD) : this._materialIndexLOD !== null ? c(this._materialBufferLODs, this._materialIndexLOD) : c(this._bufferLODs, 0)
        }
        return null
    }
    ,
    a.prototype._isMesh = function(e) {
        return !!e.addLODLevel
    }
    ,
    a.prototype._loadBufferLOD = function(e, i) {
        var o = e[i];
        o && (this._loader.log("Loading buffer range [" + o.start + "-" + o.end + "]"),
        this._loader.bin.readAsync(o.start, o.end - o.start + 1).then(function(s) {
            o.loaded.resolve(s)
        }, function(s) {
            o.loaded.reject(s)
        }))
    }
    ,
    a.prototype._getLODs = function(e, i, o, s) {
        if (this.maxLODsToLoad <= 0)
            throw new Error("maxLODsToLoad must be greater than zero");
        for (var c = new Array, d = s.length - 1; d >= 0; d--)
            if (c.push(ArrayItem.Get(e + "/ids/" + s[d], o, s[d])),
            c.length === this.maxLODsToLoad)
                return c;
        return c.push(i),
        c
    }
    ,
    a.prototype._disposeTransformNode = function(e) {
        var i = this
          , o = new Array
          , s = e.material;
        s && o.push(s);
        for (var c = 0, d = e.getChildMeshes(); c < d.length; c++) {
            var _ = d[c];
            _.material && o.push(_.material)
        }
        e.dispose();
        var b = o.filter(function(k) {
            return i._loader.babylonScene.meshes.every(function(j) {
                return j.material != k
            })
        });
        this._disposeMaterials(b)
    }
    ,
    a.prototype._disposeMaterials = function(e) {
        for (var i = {}, o = 0, s = e; o < s.length; o++) {
            for (var c = s[o], d = 0, _ = c.getActiveTextures(); d < _.length; d++) {
                var b = _[d];
                i[b.uniqueId] = b
            }
            c.dispose()
        }
        for (var k in i)
            for (var j = 0, $ = this._loader.babylonScene.materials; j < $.length; j++) {
                var c = $[j];
                c.hasTexture(i[k]) && delete i[k]
            }
        for (var k in i)
            i[k].dispose()
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$8, function(a) {
    return new MSFT_lod(a)
});
var NAME$7 = "MSFT_minecraftMesh"
  , MSFT_minecraftMesh = function() {
    function a(e) {
        this.name = NAME$7,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$7)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtraAsync(e, i, this.name, function(c, d) {
            if (d) {
                if (!(o instanceof PBRMaterial))
                    throw new Error(c + ": Material type not supported");
                var _ = s._loader.loadMaterialPropertiesAsync(e, i, o);
                return o.needAlphaBlending() && (o.forceDepthWrite = !0,
                o.separateCullingPass = !0),
                o.backFaceCulling = o.forceDepthWrite,
                o.twoSidedLighting = !0,
                _
            }
            return null
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$7, function(a) {
    return new MSFT_minecraftMesh(a)
});
var NAME$6 = "MSFT_sRGBFactors"
  , MSFT_sRGBFactors = function() {
    function a(e) {
        this.name = NAME$6,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$6)
    }
    return a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadMaterialPropertiesAsync = function(e, i, o) {
        var s = this;
        return GLTFLoader.LoadExtraAsync(e, i, this.name, function(c, d) {
            if (d) {
                if (!(o instanceof PBRMaterial))
                    throw new Error(c + ": Material type not supported");
                var _ = s._loader.loadMaterialPropertiesAsync(e, i, o);
                return o.albedoTexture || o.albedoColor.toLinearSpaceToRef(o.albedoColor),
                o.reflectivityTexture || o.reflectivityColor.toLinearSpaceToRef(o.reflectivityColor),
                _
            }
            return null
        })
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$6, function(a) {
    return new MSFT_sRGBFactors(a)
});
var NAME$5 = "ExtrasAsMetadata"
  , ExtrasAsMetadata = function() {
    function a(e) {
        this.name = NAME$5,
        this.enabled = !0,
        this._loader = e
    }
    return a.prototype._assignExtras = function(e, i) {
        if (i.extras && Object.keys(i.extras).length > 0) {
            var o = e.metadata = e.metadata || {}
              , s = o.gltf = o.gltf || {};
            s.extras = i.extras
        }
    }
    ,
    a.prototype.dispose = function() {
        this._loader = null
    }
    ,
    a.prototype.loadNodeAsync = function(e, i, o) {
        var s = this;
        return this._loader.loadNodeAsync(e, i, function(c) {
            s._assignExtras(c, i),
            o(c)
        })
    }
    ,
    a.prototype.loadCameraAsync = function(e, i, o) {
        var s = this;
        return this._loader.loadCameraAsync(e, i, function(c) {
            s._assignExtras(c, i),
            o(c)
        })
    }
    ,
    a.prototype.createMaterial = function(e, i, o) {
        var s = this._loader.createMaterial(e, i, o);
        return this._assignExtras(s, i),
        s
    }
    ,
    a
}();
GLTFLoader.RegisterExtension(NAME$5, function(a) {
    return new ExtrasAsMetadata(a)
});
var MTLFileLoader = function() {
    function a() {
        this.materials = []
    }
    return a.prototype.parseMTL = function(e, i, o, s) {
        if (!(i instanceof ArrayBuffer)) {
            for (var c = i.split(`
`), d = /\s+/, _, b = null, k = 0; k < c.length; k++) {
                var j = c[k].trim();
                if (!(j.length === 0 || j.charAt(0) === "#")) {
                    var $ = j.indexOf(" ")
                      , _e = $ >= 0 ? j.substring(0, $) : j;
                    _e = _e.toLowerCase();
                    var et = $ >= 0 ? j.substring($ + 1).trim() : "";
                    _e === "newmtl" ? (b && this.materials.push(b),
                    e._blockEntityCollection = !!s,
                    b = new StandardMaterial(et,e),
                    b._parentContainer = s,
                    e._blockEntityCollection = !1) : _e === "kd" && b ? (_ = et.split(d, 3).map(parseFloat),
                    b.diffuseColor = Color3.FromArray(_)) : _e === "ka" && b ? (_ = et.split(d, 3).map(parseFloat),
                    b.ambientColor = Color3.FromArray(_)) : _e === "ks" && b ? (_ = et.split(d, 3).map(parseFloat),
                    b.specularColor = Color3.FromArray(_)) : _e === "ke" && b ? (_ = et.split(d, 3).map(parseFloat),
                    b.emissiveColor = Color3.FromArray(_)) : _e === "ns" && b ? b.specularPower = parseFloat(et) : _e === "d" && b ? b.alpha = parseFloat(et) : _e === "map_ka" && b ? b.ambientTexture = a._getTexture(o, et, e) : _e === "map_kd" && b ? b.diffuseTexture = a._getTexture(o, et, e) : _e === "map_ks" && b ? b.specularTexture = a._getTexture(o, et, e) : _e === "map_ns" || (_e === "map_bump" && b ? b.bumpTexture = a._getTexture(o, et, e) : _e === "map_d" && b && (b.opacityTexture = a._getTexture(o, et, e)))
                }
            }
            b && this.materials.push(b)
        }
    }
    ,
    a._getTexture = function(e, i, o) {
        if (!i)
            return null;
        var s = e;
        if (e === "file:") {
            var c = i.lastIndexOf("\\");
            c === -1 && (c = i.lastIndexOf("/")),
            c > -1 ? s += i.substr(c + 1) : s += i
        } else
            s += i;
        return new Texture(s,o,!1,a.INVERT_TEXTURE_Y)
    }
    ,
    a.INVERT_TEXTURE_Y = !0,
    a
}()
  , SolidParser = function() {
    function a(e, i, o) {
        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 = i,
        this._loadingOptions = o
    }
    return a.prototype._isInArray = function(e, i) {
        e[i[0]] || (e[i[0]] = {
            normals: [],
            idx: []
        });
        var o = e[i[0]].normals.indexOf(i[1]);
        return o === -1 ? -1 : e[i[0]].idx[o]
    }
    ,
    a.prototype._isInArrayUV = function(e, i) {
        e[i[0]] || (e[i[0]] = {
            normals: [],
            idx: [],
            uv: []
        });
        var o = e[i[0]].normals.indexOf(i[1]);
        return o != 1 && i[2] === e[i[0]].uv[o] ? e[i[0]].idx[o] : -1
    }
    ,
    a.prototype._setData = function(e, i, o, s, c, d, _) {
        var b;
        this._loadingOptions.optimizeWithUV ? b = this._isInArrayUV(this._tuplePosNorm, [e, o, i]) : b = this._isInArray(this._tuplePosNorm, [e, o]),
        b === -1 ? (this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),
        this._wrappedPositionForBabylon.push(s),
        this._wrappedUvsForBabylon.push(c),
        this._wrappedNormalsForBabylon.push(d),
        _ !== void 0 && this._wrappedColorsForBabylon.push(_),
        this._tuplePosNorm[e].normals.push(o),
        this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),
        this._loadingOptions.optimizeWithUV && this._tuplePosNorm[e].uv.push(i)) : this._indicesForBabylon.push(b)
    }
    ,
    a.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
    }
    ,
    a.prototype._getTriangles = function(e, i) {
        for (var o = i; o < e.length - 1; o++)
            this._triangles.push(e[0], e[o], e[o + 1])
    }
    ,
    a.prototype._setDataForCurrentFaceWithPattern1 = function(e, i) {
        this._getTriangles(e, i);
        for (var o = 0; o < this._triangles.length; o++) {
            var s = parseInt(this._triangles[o]) - 1;
            this._setData(s, 0, 0, this._positions[s], Vector2.Zero(), Vector3.Up(), this._loadingOptions.importVertexColors ? this._colors[s] : void 0)
        }
        this._triangles = []
    }
    ,
    a.prototype._setDataForCurrentFaceWithPattern2 = function(e, i) {
        this._getTriangles(e, i);
        for (var o = 0; o < this._triangles.length; o++) {
            var s = this._triangles[o].split("/")
              , c = parseInt(s[0]) - 1
              , d = parseInt(s[1]) - 1;
            this._setData(c, d, 0, this._positions[c], this._uvs[d], Vector3.Up(), this._loadingOptions.importVertexColors ? this._colors[c] : void 0)
        }
        this._triangles = []
    }
    ,
    a.prototype._setDataForCurrentFaceWithPattern3 = function(e, i) {
        this._getTriangles(e, i);
        for (var o = 0; o < this._triangles.length; o++) {
            var s = this._triangles[o].split("/")
              , c = parseInt(s[0]) - 1
              , d = parseInt(s[1]) - 1
              , _ = parseInt(s[2]) - 1;
            this._setData(c, d, _, this._positions[c], this._uvs[d], this._normals[_])
        }
        this._triangles = []
    }
    ,
    a.prototype._setDataForCurrentFaceWithPattern4 = function(e, i) {
        this._getTriangles(e, i);
        for (var o = 0; o < this._triangles.length; o++) {
            var s = this._triangles[o].split("//")
              , c = parseInt(s[0]) - 1
              , d = parseInt(s[1]) - 1;
            this._setData(c, 1, d, this._positions[c], Vector2.Zero(), this._normals[d], this._loadingOptions.importVertexColors ? this._colors[c] : void 0)
        }
        this._triangles = []
    }
    ,
    a.prototype._setDataForCurrentFaceWithPattern5 = function(e, i) {
        this._getTriangles(e, i);
        for (var o = 0; o < this._triangles.length; o++) {
            var s = this._triangles[o].split("/")
              , c = this._positions.length + parseInt(s[0])
              , d = this._uvs.length + parseInt(s[1])
              , _ = this._normals.length + parseInt(s[2]);
            this._setData(c, d, _, this._positions[c], this._uvs[d], this._normals[_], this._loadingOptions.importVertexColors ? this._colors[c] : void 0)
        }
        this._triangles = []
    }
    ,
    a.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 = [])
    }
    ,
    a.prototype._optimizeNormals = function(e) {
        var i = e.getVerticesData(VertexBuffer.PositionKind)
          , o = e.getVerticesData(VertexBuffer.NormalKind)
          , s = {};
        if (!(!i || !o)) {
            for (var c = 0; c < i.length / 3; c++) {
                var d = i[c * 3 + 0]
                  , _ = i[c * 3 + 1]
                  , b = i[c * 3 + 2]
                  , k = d + "_" + _ + "_" + b
                  , j = s[k];
                j || (j = [],
                s[k] = j),
                j.push(c)
            }
            var $ = new Vector3;
            for (var k in s) {
                var j = s[k];
                if (!(j.length < 2)) {
                    for (var _e = j[0], c = 1; c < j.length; ++c) {
                        var et = j[c];
                        o[_e * 3 + 0] += o[et * 3 + 0],
                        o[_e * 3 + 1] += o[et * 3 + 1],
                        o[_e * 3 + 2] += o[et * 3 + 2]
                    }
                    $.copyFromFloats(o[_e * 3 + 0], o[_e * 3 + 1], o[_e * 3 + 2]),
                    $.normalize();
                    for (var c = 0; c < j.length; ++c) {
                        var et = j[c];
                        o[et * 3 + 0] = $.x,
                        o[et * 3 + 1] = $.y,
                        o[et * 3 + 2] = $.z
                    }
                }
            }
            e.setVerticesData(VertexBuffer.NormalKind, o)
        }
    }
    ,
    a.prototype.parse = function(e, i, o, s, c) {
        for (var d, _ = i.split(`
`), b = 0; b < _.length; b++) {
            var k = _[b].trim().replace(/\s\s/g, " "), j;
            if (!(k.length === 0 || k.charAt(0) === "#"))
                if (a.VertexPattern.test(k)) {
                    if (j = k.match(/[^ ]+/g),
                    this._positions.push(new Vector3(parseFloat(j[1]),parseFloat(j[2]),parseFloat(j[3]))),
                    this._loadingOptions.importVertexColors)
                        if (j.length >= 7) {
                            var $ = parseFloat(j[4])
                              , _e = parseFloat(j[5])
                              , et = parseFloat(j[6]);
                            this._colors.push(new Color4($ > 1 ? $ / 255 : $,_e > 1 ? _e / 255 : _e,et > 1 ? et / 255 : et,j.length === 7 || j[7] === void 0 ? 1 : parseFloat(j[7])))
                        } else
                            this._colors.push(this._grayColor)
                } else if ((j = a.NormalPattern.exec(k)) !== null)
                    this._normals.push(new Vector3(parseFloat(j[1]),parseFloat(j[2]),parseFloat(j[3])));
                else if ((j = a.UVPattern.exec(k)) !== null)
                    this._uvs.push(new Vector2(parseFloat(j[1]) * this._loadingOptions.UVScaling.x,parseFloat(j[2]) * this._loadingOptions.UVScaling.y));
                else if ((j = a.FacePattern3.exec(k)) !== null)
                    this._setDataForCurrentFaceWithPattern3(j[1].trim().split(" "), 1);
                else if ((j = a.FacePattern4.exec(k)) !== null)
                    this._setDataForCurrentFaceWithPattern4(j[1].trim().split(" "), 1);
                else if ((j = a.FacePattern5.exec(k)) !== null)
                    this._setDataForCurrentFaceWithPattern5(j[1].trim().split(" "), 1);
                else if ((j = a.FacePattern2.exec(k)) !== null)
                    this._setDataForCurrentFaceWithPattern2(j[1].trim().split(" "), 1);
                else if ((j = a.FacePattern1.exec(k)) !== null)
                    this._setDataForCurrentFaceWithPattern1(j[1].trim().split(" "), 1);
                else if (a.GroupDescriptor.test(k) || a.ObjectDescriptor.test(k)) {
                    var tt = {
                        name: k.substring(2).trim(),
                        indices: void 0,
                        positions: void 0,
                        normals: void 0,
                        uvs: void 0,
                        colors: void 0,
                        materialName: ""
                    };
                    this._addPreviousObjMesh(),
                    this._meshesFromObj.push(tt),
                    this._hasMeshes = !0,
                    this._isFirstMaterial = !0,
                    this._increment = 1
                } else if (a.UseMtlDescriptor.test(k)) {
                    if (this._materialNameFromObj = k.substring(7).trim(),
                    !this._isFirstMaterial || !this._hasMeshes) {
                        this._addPreviousObjMesh();
                        var tt = {
                            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(tt),
                        this._hasMeshes = !0
                    }
                    this._hasMeshes && this._isFirstMaterial && (this._meshesFromObj[this._meshesFromObj.length - 1].materialName = this._materialNameFromObj,
                    this._isFirstMaterial = !1)
                } else
                    a.MtlLibGroupDescriptor.test(k) ? c(k.substring(7).trim()) : a.SmoothDescriptor.test(k) || console.log("Unhandled expression at line : " + k)
        }
        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 rt = null;
            if (this._indicesForBabylon.length)
                this._indicesForBabylon.reverse(),
                this._unwrapData();
            else {
                for (var it = 0, nt = this._positions; it < nt.length; it++) {
                    var ot = nt[it];
                    this._unwrappedPositionsForBabylon.push(ot.x, ot.y, ot.z)
                }
                if (this._normals.length)
                    for (var at = 0, st = this._normals; at < st.length; at++) {
                        var ut = st[at];
                        this._unwrappedNormalsForBabylon.push(ut.x, ut.y, ut.z)
                    }
                if (this._uvs.length)
                    for (var ct = 0, lt = this._uvs; ct < lt.length; ct++) {
                        var ft = lt[ct];
                        this._unwrappedUVForBabylon.push(ft.x, ft.y)
                    }
                if (this._colors.length)
                    for (var ht = 0, pt = this._colors; ht < pt.length; ht++) {
                        var dt = pt[ht];
                        this._unwrappedColorsForBabylon.push(dt.r, dt.g, dt.b, dt.a)
                    }
                this._materialNameFromObj || (rt = new StandardMaterial(Geometry.RandomId(),o),
                rt.pointsCloud = !0,
                this._materialNameFromObj = rt.name,
                this._normals.length || (rt.disableLighting = !0,
                rt.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: rt
            })
        }
        for (var _t = 0; _t < this._meshesFromObj.length; _t++) {
            if (e && this._meshesFromObj[_t].name) {
                if (e instanceof Array) {
                    if (e.indexOf(this._meshesFromObj[_t].name) === -1)
                        continue
                } else if (this._meshesFromObj[_t].name !== e)
                    continue
            }
            this._handledMesh = this._meshesFromObj[_t],
            o._blockEntityCollection = !!s;
            var mt = new Mesh(this._meshesFromObj[_t].name,o);
            if (mt._parentContainer = s,
            o._blockEntityCollection = !1,
            this._materialToUse.push(this._meshesFromObj[_t].materialName),
            ((d = this._handledMesh.positions) === null || d === void 0 ? void 0 : d.length) === 0) {
                this._babylonMeshesArray.push(mt);
                continue
            }
            var vt = new VertexData;
            if (vt.uvs = this._handledMesh.uvs,
            vt.indices = this._handledMesh.indices,
            vt.positions = this._handledMesh.positions,
            this._loadingOptions.computeNormals) {
                var yt = new Array;
                VertexData.ComputeNormals(this._handledMesh.positions, this._handledMesh.indices, yt),
                vt.normals = yt
            } else
                vt.normals = this._handledMesh.normals;
            this._loadingOptions.importVertexColors && (vt.colors = this._handledMesh.colors),
            vt.applyToMesh(mt),
            this._loadingOptions.invertY && (mt.scaling.y *= -1),
            this._loadingOptions.optimizeNormals && this._optimizeNormals(mt),
            this._babylonMeshesArray.push(mt),
            this._handledMesh.directMaterial && (mt.material = this._handledMesh.directMaterial)
        }
    }
    ,
    a.ObjectDescriptor = /^o/,
    a.GroupDescriptor = /^g/,
    a.MtlLibGroupDescriptor = /^mtllib /,
    a.UseMtlDescriptor = /^usemtl /,
    a.SmoothDescriptor = /^s /,
    a.VertexPattern = /v(\s+[\d|\.|\+|\-|e|E]+){3,7}/,
    a.NormalPattern = /vn(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,
    a.UVPattern = /vt(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,
    a.FacePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/,
    a.FacePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,
    a.FacePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,
    a.FacePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,
    a.FacePattern5 = /f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,
    a
}()
  , OBJFileLoader = function() {
    function a(e) {
        this.name = "obj",
        this.extensions = ".obj",
        this._assetContainer = null,
        this._loadingOptions = e || a.DefaultLoadingOptions
    }
    return Object.defineProperty(a, "INVERT_TEXTURE_Y", {
        get: function() {
            return MTLFileLoader.INVERT_TEXTURE_Y
        },
        set: function(e) {
            MTLFileLoader.INVERT_TEXTURE_Y = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a, "DefaultLoadingOptions", {
        get: function() {
            return {
                computeNormals: a.COMPUTE_NORMALS,
                optimizeNormals: a.OPTIMIZE_NORMALS,
                importVertexColors: a.IMPORT_VERTEX_COLORS,
                invertY: a.INVERT_Y,
                invertTextureY: a.INVERT_TEXTURE_Y,
                UVScaling: a.UV_SCALING,
                materialLoadingFailsSilently: a.MATERIAL_LOADING_FAILS_SILENTLY,
                optimizeWithUV: a.OPTIMIZE_WITH_UV,
                skipMaterials: a.SKIP_MATERIALS
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._loadMTL = function(e, i, o, s) {
        var c = i + e;
        Tools.LoadFile(c, o, void 0, void 0, !1, function(d, _) {
            s(c, _)
        })
    }
    ,
    a.prototype.createPlugin = function() {
        return new a(a.DefaultLoadingOptions)
    }
    ,
    a.prototype.canDirectLoad = function(e) {
        return !1
    }
    ,
    a.prototype.importMeshAsync = function(e, i, o, s, c, d) {
        return this._parseSolid(e, i, o, s).then(function(_) {
            return {
                meshes: _,
                particleSystems: [],
                skeletons: [],
                animationGroups: [],
                transformNodes: [],
                geometries: [],
                lights: []
            }
        })
    }
    ,
    a.prototype.loadAsync = function(e, i, o, s, c) {
        return this.importMeshAsync(null, e, i, o, s).then(function() {})
    }
    ,
    a.prototype.loadAssetContainerAsync = function(e, i, o, s, c) {
        var d = this
          , _ = new AssetContainer(e);
        return this._assetContainer = _,
        this.importMeshAsync(null, e, i, o).then(function(b) {
            return b.meshes.forEach(function(k) {
                return _.meshes.push(k)
            }),
            b.meshes.forEach(function(k) {
                var j = k.material;
                if (j && _.materials.indexOf(j) == -1) {
                    _.materials.push(j);
                    var $ = j.getActiveTextures();
                    $.forEach(function(_e) {
                        _.textures.indexOf(_e) == -1 && _.textures.push(_e)
                    })
                }
            }),
            d._assetContainer = null,
            _
        }).catch(function(b) {
            throw d._assetContainer = null,
            b
        })
    }
    ,
    a.prototype._parseSolid = function(e, i, o, s) {
        var c = this
          , d = ""
          , _ = new MTLFileLoader
          , b = new Array
          , k = []
          , j = new SolidParser(b,k,this._loadingOptions);
        j.parse(e, o, i, this._assetContainer, function(_e) {
            d = _e
        });
        var $ = [];
        return d !== "" && !this._loadingOptions.skipMaterials && $.push(new Promise(function(_e, et) {
            c._loadMTL(d, s, function(tt) {
                try {
                    _.parseMTL(i, tt, s, c._assetContainer);
                    for (var rt = 0; rt < _.materials.length; rt++) {
                        for (var it = 0, nt = [], ot; (ot = b.indexOf(_.materials[rt].name, it)) > -1; )
                            nt.push(ot),
                            it = ot + 1;
                        if (ot === -1 && nt.length === 0)
                            _.materials[rt].dispose();
                        else
                            for (var at = 0; at < nt.length; at++) {
                                var st = k[nt[at]]
                                  , ut = _.materials[rt];
                                st.material = ut,
                                st.getTotalIndices() || (ut.pointsCloud = !0)
                            }
                    }
                    _e()
                } catch (ct) {
                    Tools.Warn("Error processing MTL file: '" + d + "'"),
                    c._loadingOptions.materialLoadingFailsSilently ? _e() : et(ct)
                }
            }, function(tt, rt) {
                Tools.Warn("Error downloading MTL file: '" + d + "'"),
                c._loadingOptions.materialLoadingFailsSilently ? _e() : et(rt)
            })
        }
        )),
        Promise.all($).then(function() {
            return k
        })
    }
    ,
    a.OPTIMIZE_WITH_UV = !0,
    a.INVERT_Y = !1,
    a.IMPORT_VERTEX_COLORS = !1,
    a.COMPUTE_NORMALS = !1,
    a.OPTIMIZE_NORMALS = !1,
    a.UV_SCALING = new Vector2(1,1),
    a.SKIP_MATERIALS = !1,
    a.MATERIAL_LOADING_FAILS_SILENTLY = !0,
    a
}();
SceneLoader && SceneLoader.RegisterPlugin(new OBJFileLoader);
var STLFileLoader = function() {
    function a() {
        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 a.prototype.importMesh = function(e, i, o, s, c, d, _) {
        var b;
        if (typeof o != "string") {
            if (this._isBinary(o)) {
                var k = new Mesh("stlmesh",i);
                return this._parseBinary(k, o),
                c && c.push(k),
                !0
            }
            for (var j = new Uint8Array(o), $ = "", _e = 0; _e < o.byteLength; _e++)
                $ += String.fromCharCode(j[_e]);
            o = $
        }
        for (; b = this.solidPattern.exec(o); ) {
            var et = b[1]
              , tt = b[3];
            if (et != tt)
                return Tools.Error("Error in STL, solid name != endsolid name"),
                !1;
            if (e && et) {
                if (e instanceof Array) {
                    if (!e.indexOf(et))
                        continue
                } else if (et !== e)
                    continue
            }
            et = et || "stlmesh";
            var k = new Mesh(et,i);
            this._parseASCII(k, b[2]),
            c && c.push(k)
        }
        return !0
    }
    ,
    a.prototype.load = function(e, i, o) {
        var s = this.importMesh(null, e, i, o, null, null, null);
        return s
    }
    ,
    a.prototype.loadAssetContainer = function(e, i, o, s) {
        var c = new AssetContainer(e);
        return e._blockEntityCollection = !0,
        this.importMesh(null, e, i, o, c.meshes, null, null),
        e._blockEntityCollection = !1,
        c
    }
    ,
    a.prototype._isBinary = function(e) {
        var i, o, s;
        if (s = new DataView(e),
        s.byteLength <= 80)
            return !1;
        if (i = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8,
        o = s.getUint32(80, !0),
        80 + 32 / 8 + o * i === s.byteLength)
            return !0;
        for (var c = s.byteLength, d = 0; d < c; d++)
            if (s.getUint8(d) > 127)
                return !0;
        return !1
    }
    ,
    a.prototype._parseBinary = function(e, i) {
        for (var o = new DataView(i), s = o.getUint32(80, !0), c = 84, d = 12 * 4 + 2, _ = 0, b = new Float32Array(s * 3 * 3), k = new Float32Array(s * 3 * 3), j = new Uint32Array(s * 3), $ = 0, _e = 0; _e < s; _e++) {
            for (var et = c + _e * d, tt = o.getFloat32(et, !0), rt = o.getFloat32(et + 4, !0), it = o.getFloat32(et + 8, !0), nt = 1; nt <= 3; nt++) {
                var ot = et + nt * 12;
                b[_] = o.getFloat32(ot, !0),
                k[_] = tt,
                a.DO_NOT_ALTER_FILE_COORDINATES ? (b[_ + 1] = o.getFloat32(ot + 4, !0),
                b[_ + 2] = o.getFloat32(ot + 8, !0),
                k[_ + 1] = rt,
                k[_ + 2] = it) : (b[_ + 2] = o.getFloat32(ot + 4, !0),
                b[_ + 1] = o.getFloat32(ot + 8, !0),
                k[_ + 2] = rt,
                k[_ + 1] = it),
                _ += 3
            }
            j[$] = $++,
            j[$] = $++,
            j[$] = $++
        }
        e.setVerticesData(VertexBuffer.PositionKind, b),
        e.setVerticesData(VertexBuffer.NormalKind, k),
        e.setIndices(j),
        e.computeWorldMatrix(!0)
    }
    ,
    a.prototype._parseASCII = function(e, i) {
        for (var o = [], s = [], c = [], d = 0, _; _ = this.facetsPattern.exec(i); ) {
            var b = _[1]
              , k = this.normalPattern.exec(b);
            if (this.normalPattern.lastIndex = 0,
            !!k) {
                for (var j = [Number(k[1]), Number(k[5]), Number(k[3])], $; $ = this.vertexPattern.exec(b); )
                    a.DO_NOT_ALTER_FILE_COORDINATES ? (o.push(Number($[1]), Number($[3]), Number($[5])),
                    s.push(j[0], j[2], j[1])) : (o.push(Number($[1]), Number($[5]), Number($[3])),
                    s.push(j[0], j[1], j[2]));
                c.push(d++, d++, d++),
                this.vertexPattern.lastIndex = 0
            }
        }
        this.facetsPattern.lastIndex = 0,
        e.setVerticesData(VertexBuffer.PositionKind, o),
        e.setVerticesData(VertexBuffer.NormalKind, s),
        e.setIndices(c),
        e.computeWorldMatrix(!0)
    }
    ,
    a.DO_NOT_ALTER_FILE_COORDINATES = !1,
    a
}();
SceneLoader && SceneLoader.RegisterPlugin(new STLFileLoader);
var SoundTrack = function() {
    function a(e, i) {
        i === void 0 && (i = {}),
        this.id = -1,
        this._isInitialized = !1,
        this._scene = e,
        this.soundCollection = new Array,
        this._options = i,
        !this._options.mainTrack && this._scene.soundTracks && (this._scene.soundTracks.push(this),
        this.id = this._scene.soundTracks.length - 1)
    }
    return a.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)
    }
    ,
    a.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
        }
    }
    ,
    a.prototype.addSound = function(e) {
        var i;
        this._isInitialized || this._initializeSoundTrackAudioGraph(),
        ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.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
    }
    ,
    a.prototype.removeSound = function(e) {
        var i = this.soundCollection.indexOf(e);
        i !== -1 && this.soundCollection.splice(i, 1)
    }
    ,
    a.prototype.setVolume = function(e) {
        var i;
        ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.canUseWebAudio) && this._outputAudioNode && (this._outputAudioNode.gain.value = e)
    }
    ,
    a.prototype.switchPanningModelToHRTF = function() {
        var e;
        if (!((e = Engine.audioEngine) === null || e === void 0) && e.canUseWebAudio)
            for (var i = 0; i < this.soundCollection.length; i++)
                this.soundCollection[i].switchPanningModelToHRTF()
    }
    ,
    a.prototype.switchPanningModelToEqualPower = function() {
        var e;
        if (!((e = Engine.audioEngine) === null || e === void 0) && e.canUseWebAudio)
            for (var i = 0; i < this.soundCollection.length; i++)
                this.soundCollection[i].switchPanningModelToEqualPower()
    }
    ,
    a.prototype.connectToAnalyser = function(e) {
        var i;
        this._connectedAnalyser && this._connectedAnalyser.stopDebugCanvas(),
        this._connectedAnalyser = e,
        ((i = Engine.audioEngine) === null || i === void 0 ? void 0 : i.canUseWebAudio) && this._outputAudioNode && (this._outputAudioNode.disconnect(),
        this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, Engine.audioEngine.masterGain))
    }
    ,
    a
}();
Engine.AudioEngineFactory = function(a, e, i) {
    return new AudioEngine(a,e,i)
}
;
var AudioEngine = function() {
    function a(e, i, o) {
        var s = this;
        if (e === void 0 && (e = null),
        i === void 0 && (i = null),
        o === void 0 && (o = 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() {
            s._moveButtonToTopLeft()
        }
        ,
        !!IsWindowObjectExist()) {
            (typeof window.AudioContext != "undefined" || typeof window.webkitAudioContext != "undefined") && (window.AudioContext = window.AudioContext || window.webkitAudioContext,
            this.canUseWebAudio = !0);
            var c = document.createElement("audio");
            this._hostElement = e,
            this._audioContext = i,
            this._audioDestination = o;
            try {
                c && !!c.canPlayType && (c.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, "") || c.canPlayType("audio/mp3").replace(/^no$/, "")) && (this.isMP3supported = !0)
            } catch {}
            try {
                c && !!c.canPlayType && c.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, "") && (this.isOGGsupported = !0)
            } catch {}
        }
    }
    return Object.defineProperty(a.prototype, "audioContext", {
        get: function() {
            return this._audioContextInitialized ? !this.unlocked && !this._muteButton && this._displayMuteButton() : this._initializeAudioContext(),
            this._audioContext
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.lock = function() {
        this._triggerSuspendedState()
    }
    ,
    a.prototype.unlock = function() {
        this._triggerRunningState()
    }
    ,
    a.prototype._resumeAudioContext = function() {
        var e;
        return this._audioContext.resume !== void 0 && (e = this._audioContext.resume()),
        e || Promise.resolve()
    }
    ,
    a.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)
        }
    }
    ,
    a.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
        }))
    }
    ,
    a.prototype._triggerSuspendedState = function() {
        this.unlocked = !1,
        this.onAudioLockedObservable.notifyObservers(this),
        this._displayMuteButton()
    }
    ,
    a.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 i = 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"
              , o = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(" + i + ");  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) }"
              , s = document.createElement("style");
            s.appendChild(document.createTextNode(o)),
            document.getElementsByTagName("head")[0].appendChild(s),
            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)
        }
    }
    ,
    a.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")
    }
    ,
    a.prototype._hideMuteButton = function() {
        this._muteButton && (document.body.removeChild(this._muteButton),
        this._muteButton = null)
    }
    ,
    a.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()
    }
    ,
    a.prototype.getGlobalVolume = function() {
        return this.canUseWebAudio && this._audioContextInitialized ? this.masterGain.gain.value : -1
    }
    ,
    a.prototype.setGlobalVolume = function(e) {
        this.canUseWebAudio && this._audioContextInitialized && (this.masterGain.gain.value = e)
    }
    ,
    a.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))
    }
    ,
    a
}();
AbstractScene.AddParser(SceneComponentConstants.NAME_AUDIO, function(a, e, i, o) {
    var s, c = [], d;
    if (i.sounds = i.sounds || [],
    a.sounds !== void 0 && a.sounds !== null)
        for (var _ = 0, b = a.sounds.length; _ < b; _++) {
            var k = a.sounds[_];
            !((s = Engine.audioEngine) === null || s === void 0) && s.canUseWebAudio ? (k.url || (k.url = k.name),
            c[k.url] ? i.sounds.push(Sound.Parse(k, e, o, c[k.url])) : (d = Sound.Parse(k, e, o),
            c[k.url] = d,
            i.sounds.push(d))) : i.sounds.push(new Sound(k.name,null,e))
        }
    c = []
});
Object.defineProperty(Scene.prototype, "mainSoundTrack", {
    get: function() {
        var a = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return a || (a = new AudioSceneComponent(this),
        this._addComponent(a)),
        this._mainSoundTrack || (this._mainSoundTrack = new SoundTrack(this,{
            mainTrack: !0
        })),
        this._mainSoundTrack
    },
    enumerable: !0,
    configurable: !0
});
Scene.prototype.getSoundByName = function(a) {
    var e;
    for (e = 0; e < this.mainSoundTrack.soundCollection.length; e++)
        if (this.mainSoundTrack.soundCollection[e].name === a)
            return this.mainSoundTrack.soundCollection[e];
    if (this.soundTracks) {
        for (var i = 0; i < this.soundTracks.length; i++)
            for (e = 0; e < this.soundTracks[i].soundCollection.length; e++)
                if (this.soundTracks[i].soundCollection[e].name === a)
                    return this.soundTracks[i].soundCollection[e]
    }
    return null
}
;
Object.defineProperty(Scene.prototype, "audioEnabled", {
    get: function() {
        var a = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return a || (a = new AudioSceneComponent(this),
        this._addComponent(a)),
        a.audioEnabled
    },
    set: function(a) {
        var e = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        e || (e = new AudioSceneComponent(this),
        this._addComponent(e)),
        a ? e.enableAudio() : e.disableAudio()
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(Scene.prototype, "headphone", {
    get: function() {
        var a = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return a || (a = new AudioSceneComponent(this),
        this._addComponent(a)),
        a.headphone
    },
    set: function(a) {
        var e = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        e || (e = new AudioSceneComponent(this),
        this._addComponent(e)),
        a ? e.switchAudioModeForHeadphones() : e.switchAudioModeForNormalSpeakers()
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(Scene.prototype, "audioListenerPositionProvider", {
    get: function() {
        var a = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return a || (a = new AudioSceneComponent(this),
        this._addComponent(a)),
        a.audioListenerPositionProvider
    },
    set: function(a) {
        var e = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        if (e || (e = new AudioSceneComponent(this),
        this._addComponent(e)),
        typeof a != "function")
            throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");
        e.audioListenerPositionProvider = a
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(Scene.prototype, "audioPositioningRefreshRate", {
    get: function() {
        var a = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return a || (a = new AudioSceneComponent(this),
        this._addComponent(a)),
        a.audioPositioningRefreshRate
    },
    set: function(a) {
        var e = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        e || (e = new AudioSceneComponent(this),
        this._addComponent(e)),
        e.audioPositioningRefreshRate = a
    },
    enumerable: !0,
    configurable: !0
});
var AudioSceneComponent = function() {
    function a(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(a.prototype, "audioEnabled", {
        get: function() {
            return this._audioEnabled
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "headphone", {
        get: function() {
            return this._headphone
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "audioListenerPositionProvider", {
        get: function() {
            return this._audioListenerPositionProvider
        },
        set: function(e) {
            this._audioListenerPositionProvider = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.register = function() {
        this.scene._afterRenderStage.registerStep(SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender)
    }
    ,
    a.prototype.rebuild = function() {}
    ,
    a.prototype.serialize = function(e) {
        if (e.sounds = [],
        this.scene.soundTracks)
            for (var i = 0; i < this.scene.soundTracks.length; i++)
                for (var o = this.scene.soundTracks[i], s = 0; s < o.soundCollection.length; s++)
                    e.sounds.push(o.soundCollection[s].serialize())
    }
    ,
    a.prototype.addFromContainer = function(e) {
        var i = this;
        !e.sounds || e.sounds.forEach(function(o) {
            o.play(),
            o.autoplay = !0,
            i.scene.mainSoundTrack.addSound(o)
        })
    }
    ,
    a.prototype.removeFromContainer = function(e, i) {
        var o = this;
        i === void 0 && (i = !1),
        e.sounds && e.sounds.forEach(function(s) {
            s.stop(),
            s.autoplay = !1,
            o.scene.mainSoundTrack.removeSound(s),
            i && s.dispose()
        })
    }
    ,
    a.prototype.dispose = function() {
        var e = this.scene;
        if (e._mainSoundTrack && e.mainSoundTrack.dispose(),
        e.soundTracks)
            for (var i = 0; i < e.soundTracks.length; i++)
                e.soundTracks[i].dispose()
    }
    ,
    a.prototype.disableAudio = function() {
        var e = this.scene;
        this._audioEnabled = !1,
        Engine.audioEngine && Engine.audioEngine.audioContext && Engine.audioEngine.audioContext.suspend();
        var i;
        for (i = 0; i < e.mainSoundTrack.soundCollection.length; i++)
            e.mainSoundTrack.soundCollection[i].pause();
        if (e.soundTracks)
            for (i = 0; i < e.soundTracks.length; i++)
                for (var o = 0; o < e.soundTracks[i].soundCollection.length; o++)
                    e.soundTracks[i].soundCollection[o].pause()
    }
    ,
    a.prototype.enableAudio = function() {
        var e = this.scene;
        this._audioEnabled = !0,
        Engine.audioEngine && Engine.audioEngine.audioContext && Engine.audioEngine.audioContext.resume();
        var i;
        for (i = 0; i < e.mainSoundTrack.soundCollection.length; i++)
            e.mainSoundTrack.soundCollection[i].isPaused && e.mainSoundTrack.soundCollection[i].play();
        if (e.soundTracks)
            for (i = 0; i < e.soundTracks.length; i++)
                for (var o = 0; o < e.soundTracks[i].soundCollection.length; o++)
                    e.soundTracks[i].soundCollection[o].isPaused && e.soundTracks[i].soundCollection[o].play()
    }
    ,
    a.prototype.switchAudioModeForHeadphones = function() {
        var e = this.scene;
        if (this._headphone = !0,
        e.mainSoundTrack.switchPanningModelToHRTF(),
        e.soundTracks)
            for (var i = 0; i < e.soundTracks.length; i++)
                e.soundTracks[i].switchPanningModelToHRTF()
    }
    ,
    a.prototype.switchAudioModeForNormalSpeakers = function() {
        var e = this.scene;
        if (this._headphone = !1,
        e.mainSoundTrack.switchPanningModelToEqualPower(),
        e.soundTracks)
            for (var i = 0; i < e.soundTracks.length; i++)
                e.soundTracks[i].switchPanningModelToEqualPower()
    }
    ,
    a.prototype._afterRender = function() {
        var e = PrecisionDate.Now;
        if (!(this._lastCheck && e - this._lastCheck < this.audioPositioningRefreshRate)) {
            this._lastCheck = e;
            var i = this.scene;
            if (!(!this._audioEnabled || !i._mainSoundTrack || !i.soundTracks || i._mainSoundTrack.soundCollection.length === 0 && i.soundTracks.length === 1)) {
                var o = Engine.audioEngine;
                if (!!o && o.audioContext) {
                    if (this._audioListenerPositionProvider) {
                        var s = this._audioListenerPositionProvider();
                        s.x = s.x || 0,
                        s.y = s.y || 0,
                        s.z = s.z || 0,
                        o.audioContext.listener.setPosition(s.x, s.y, s.z)
                    } else {
                        var c;
                        if (i.activeCameras && i.activeCameras.length > 0 ? c = i.activeCameras[0] : c = i.activeCamera,
                        c) {
                            this._cachedCameraPosition.equals(c.globalPosition) || (this._cachedCameraPosition.copyFrom(c.globalPosition),
                            o.audioContext.listener.setPosition(c.globalPosition.x, c.globalPosition.y, c.globalPosition.z)),
                            c.rigCameras && c.rigCameras.length > 0 && (c = c.rigCameras[0]);
                            var d = Matrix.Invert(c.getViewMatrix())
                              , _ = Vector3.TransformNormal(a._CameraDirection, d);
                            _.normalize(),
                            !isNaN(_.x) && !isNaN(_.y) && !isNaN(_.z) && (this._cachedCameraDirection.equals(_) || (this._cachedCameraDirection.copyFrom(_),
                            o.audioContext.listener.setOrientation(_.x, _.y, _.z, 0, 1, 0)))
                        } else
                            o.audioContext.listener.setPosition(0, 0, 0)
                    }
                    var b;
                    for (b = 0; b < i.mainSoundTrack.soundCollection.length; b++) {
                        var k = i.mainSoundTrack.soundCollection[b];
                        k.useCustomAttenuation && k.updateDistanceFromListener()
                    }
                    if (i.soundTracks)
                        for (b = 0; b < i.soundTracks.length; b++)
                            for (var j = 0; j < i.soundTracks[b].soundCollection.length; j++)
                                k = i.soundTracks[b].soundCollection[j],
                                k.useCustomAttenuation && k.updateDistanceFromListener()
                }
            }
        }
    }
    ,
    a._CameraDirection = new Vector3(0,0,-1),
    a
}();
Sound._SceneComponentInitialization = function(a) {
    var e = a._getComponent(SceneComponentConstants.NAME_AUDIO);
    e || (e = new AudioSceneComponent(a),
    a._addComponent(e))
}
;
var DefaultLoadingScreen = function() {
    function a(e, i, o) {
        var s = this;
        i === void 0 && (i = ""),
        o === void 0 && (o = "black"),
        this._renderingCanvas = e,
        this._loadingText = i,
        this._loadingDivBackgroundColor = o,
        this._resizeLoadingUI = function() {
            var c = s._renderingCanvas.getBoundingClientRect()
              , d = window.getComputedStyle(s._renderingCanvas).position;
            !s._loadingDiv || (s._loadingDiv.style.position = d === "fixed" ? "fixed" : "absolute",
            s._loadingDiv.style.left = c.left + "px",
            s._loadingDiv.style.top = c.top + "px",
            s._loadingDiv.style.width = c.width + "px",
            s._loadingDiv.style.height = c.height + "px")
        }
    }
    return a.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 i = !!window.SVGSVGElement
              , o = new Image;
            a.DefaultLogoUrl ? o.src = a.DefaultLogoUrl : o.src = i ? "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+" : "https://cdn.babylonjs.com/Assets/babylonLogo.png",
            o.style.width = "150px",
            o.style.gridColumn = "1",
            o.style.gridRow = "1",
            o.style.top = "50%",
            o.style.left = "50%",
            o.style.transform = "translate(-50%, -50%)",
            o.style.position = "absolute";
            var s = document.createElement("div");
            s.style.width = "300px",
            s.style.gridColumn = "1",
            s.style.gridRow = "1",
            s.style.top = "50%",
            s.style.left = "50%",
            s.style.transform = "translate(-50%, -50%)",
            s.style.position = "absolute";
            var c = new Image;
            if (a.DefaultSpinnerUrl ? c.src = a.DefaultSpinnerUrl : c.src = i ? "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==" : "https://cdn.babylonjs.com/Assets/loadingIcon.png",
            c.style.animation = "spin1 0.75s infinite linear",
            c.style.webkitAnimation = "spin1 0.75s infinite linear",
            c.style.transformOrigin = "50% 50%",
            c.style.webkitTransformOrigin = "50% 50%",
            !i) {
                var d = {
                    w: 16,
                    h: 18.5
                }
                  , _ = {
                    w: 30,
                    h: 30
                };
                o.style.width = d.w + "vh",
                o.style.height = d.h + "vh",
                o.style.left = "calc(50% - " + d.w / 2 + "vh)",
                o.style.top = "calc(50% - " + d.h / 2 + "vh)",
                c.style.width = _.w + "vh",
                c.style.height = _.h + "vh",
                c.style.left = "calc(50% - " + _.w / 2 + "vh)",
                c.style.top = "calc(50% - " + _.h / 2 + "vh)"
            }
            s.appendChild(c),
            this._loadingDiv.appendChild(o),
            this._loadingDiv.appendChild(s),
            this._resizeLoadingUI(),
            window.addEventListener("resize", this._resizeLoadingUI),
            this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor,
            document.body.appendChild(this._loadingDiv),
            this._loadingDiv.style.opacity = "1"
        }
    }
    ,
    a.prototype.hideLoadingUI = function() {
        var e = this;
        if (!!this._loadingDiv) {
            var i = 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", i)
        }
    }
    ,
    Object.defineProperty(a.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(a.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
    }),
    a.DefaultLogoUrl = "",
    a.DefaultSpinnerUrl = "",
    a
}();
Engine.DefaultLoadingScreenFactory = function(a) {
    return new DefaultLoadingScreen(a)
}
;
var PanoramaToCubeMapTools = function() {
    function a() {}
    return a.ConvertPanoramaToCubemap = function(e, i, o, s) {
        if (!e)
            throw "ConvertPanoramaToCubemap: input cannot be null";
        if (e.length != i * o * 3)
            throw "ConvertPanoramaToCubemap: input size is wrong";
        var c = this.CreateCubemapTexture(s, this.FACE_FRONT, e, i, o)
          , d = this.CreateCubemapTexture(s, this.FACE_BACK, e, i, o)
          , _ = this.CreateCubemapTexture(s, this.FACE_LEFT, e, i, o)
          , b = this.CreateCubemapTexture(s, this.FACE_RIGHT, e, i, o)
          , k = this.CreateCubemapTexture(s, this.FACE_UP, e, i, o)
          , j = this.CreateCubemapTexture(s, this.FACE_DOWN, e, i, o);
        return {
            front: c,
            back: d,
            left: _,
            right: b,
            up: k,
            down: j,
            size: s,
            type: 1,
            format: 4,
            gammaSpace: !1
        }
    }
    ,
    a.CreateCubemapTexture = function(e, i, o, s, c) {
        for (var d = new ArrayBuffer(e * e * 4 * 3), _ = new Float32Array(d), b = i[1].subtract(i[0]).scale(1 / e), k = i[3].subtract(i[2]).scale(1 / e), j = 1 / e, $ = 0, _e = 0; _e < e; _e++) {
            for (var et = i[0], tt = i[2], rt = 0; rt < e; rt++) {
                var it = tt.subtract(et).scale($).add(et);
                it.normalize();
                var nt = this.CalcProjectionSpherical(it, o, s, c);
                _[_e * e * 3 + rt * 3 + 0] = nt.r,
                _[_e * e * 3 + rt * 3 + 1] = nt.g,
                _[_e * e * 3 + rt * 3 + 2] = nt.b,
                et = et.add(b),
                tt = tt.add(k)
            }
            $ += j
        }
        return _
    }
    ,
    a.CalcProjectionSpherical = function(e, i, o, s) {
        for (var c = Math.atan2(e.z, e.x), d = Math.acos(e.y); c < -Math.PI; )
            c += 2 * Math.PI;
        for (; c > Math.PI; )
            c -= 2 * Math.PI;
        var _ = c / Math.PI
          , b = d / Math.PI;
        _ = _ * .5 + .5;
        var k = Math.round(_ * o);
        k < 0 ? k = 0 : k >= o && (k = o - 1);
        var j = Math.round(b * s);
        j < 0 ? j = 0 : j >= s && (j = s - 1);
        var $ = s - j - 1
          , _e = i[$ * o * 3 + k * 3 + 0]
          , et = i[$ * o * 3 + k * 3 + 1]
          , tt = i[$ * o * 3 + k * 3 + 2];
        return {
            r: _e,
            g: et,
            b: tt
        }
    }
    ,
    a.FACE_LEFT = [new Vector3(-1,-1,-1), new Vector3(1,-1,-1), new Vector3(-1,1,-1), new Vector3(1,1,-1)],
    a.FACE_RIGHT = [new Vector3(1,-1,1), new Vector3(-1,-1,1), new Vector3(1,1,1), new Vector3(-1,1,1)],
    a.FACE_FRONT = [new Vector3(1,-1,-1), new Vector3(1,-1,1), new Vector3(1,1,-1), new Vector3(1,1,1)],
    a.FACE_BACK = [new Vector3(-1,-1,1), new Vector3(-1,-1,-1), new Vector3(-1,1,1), new Vector3(-1,1,-1)],
    a.FACE_DOWN = [new Vector3(1,1,-1), new Vector3(1,1,1), new Vector3(-1,1,-1), new Vector3(-1,1,1)],
    a.FACE_UP = [new Vector3(-1,-1,-1), new Vector3(-1,-1,1), new Vector3(1,-1,-1), new Vector3(1,-1,1)],
    a
}()
  , HDRTools = function() {
    function a() {}
    return a.Ldexp = function(e, i) {
        return i > 1023 ? e * Math.pow(2, 1023) * Math.pow(2, i - 1023) : i < -1074 ? e * Math.pow(2, -1074) * Math.pow(2, i + 1074) : e * Math.pow(2, i)
    }
    ,
    a.Rgbe2float = function(e, i, o, s, c, d) {
        c > 0 ? (c = this.Ldexp(1, c - (128 + 8)),
        e[d + 0] = i * c,
        e[d + 1] = o * c,
        e[d + 2] = s * c) : (e[d + 0] = 0,
        e[d + 1] = 0,
        e[d + 2] = 0)
    }
    ,
    a.readStringLine = function(e, i) {
        for (var o = "", s = "", c = i; c < e.length - i && (s = String.fromCharCode(e[c]),
        s != `
`); c++)
            o += s;
        return o
    }
    ,
    a.RGBE_ReadHeader = function(e) {
        var i = 0
          , o = 0
          , s = this.readStringLine(e, 0);
        if (s[0] != "#" || s[1] != "?")
            throw "Bad HDR Format.";
        var c = !1
          , d = !1
          , _ = 0;
        do
            _ += s.length + 1,
            s = this.readStringLine(e, _),
            s == "FORMAT=32-bit_rle_rgbe" ? d = !0 : s.length == 0 && (c = !0);
        while (!c);
        if (!d)
            throw "HDR Bad header format, unsupported FORMAT";
        _ += s.length + 1,
        s = this.readStringLine(e, _);
        var b = /^\-Y (.*) \+X (.*)$/g
          , k = b.exec(s);
        if (!k || k.length < 3)
            throw "HDR Bad header format, no size";
        if (o = parseInt(k[2]),
        i = parseInt(k[1]),
        o < 8 || o > 32767)
            throw "HDR Bad header format, unsupported size";
        return _ += s.length + 1,
        {
            height: i,
            width: o,
            dataPosition: _
        }
    }
    ,
    a.GetCubeMapTextureData = function(e, i) {
        var o = new Uint8Array(e)
          , s = this.RGBE_ReadHeader(o)
          , c = this.RGBE_ReadPixels(o, s)
          , d = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(c, s.width, s.height, i);
        return d
    }
    ,
    a.RGBE_ReadPixels = function(e, i) {
        return this.RGBE_ReadPixels_RLE(e, i)
    }
    ,
    a.RGBE_ReadPixels_RLE = function(e, i) {
        for (var o = i.height, s = i.width, c, d, _, b, k, j = i.dataPosition, $ = 0, _e = 0, et = 0, tt = new ArrayBuffer(s * 4), rt = new Uint8Array(tt), it = new ArrayBuffer(i.width * i.height * 4 * 3), nt = new Float32Array(it); o > 0; ) {
            if (c = e[j++],
            d = e[j++],
            _ = e[j++],
            b = e[j++],
            c != 2 || d != 2 || _ & 128 || i.width < 8 || i.width > 32767)
                return this.RGBE_ReadPixels_NOT_RLE(e, i);
            if ((_ << 8 | b) != s)
                throw "HDR Bad header format, wrong scan line width";
            for ($ = 0,
            et = 0; et < 4; et++)
                for (_e = (et + 1) * s; $ < _e; )
                    if (c = e[j++],
                    d = e[j++],
                    c > 128) {
                        if (k = c - 128,
                        k == 0 || k > _e - $)
                            throw "HDR Bad Format, bad scanline data (run)";
                        for (; k-- > 0; )
                            rt[$++] = d
                    } else {
                        if (k = c,
                        k == 0 || k > _e - $)
                            throw "HDR Bad Format, bad scanline data (non-run)";
                        if (rt[$++] = d,
                        --k > 0)
                            for (var ot = 0; ot < k; ot++)
                                rt[$++] = e[j++]
                    }
            for (et = 0; et < s; et++)
                c = rt[et],
                d = rt[et + s],
                _ = rt[et + 2 * s],
                b = rt[et + 3 * s],
                this.Rgbe2float(nt, c, d, _, b, (i.height - o) * s * 3 + et * 3);
            o--
        }
        return nt
    }
    ,
    a.RGBE_ReadPixels_NOT_RLE = function(e, i) {
        for (var o = i.height, s = i.width, c, d, _, b, k, j = i.dataPosition, $ = new ArrayBuffer(i.width * i.height * 4 * 3), _e = new Float32Array($); o > 0; ) {
            for (k = 0; k < i.width; k++)
                c = e[j++],
                d = e[j++],
                _ = e[j++],
                b = e[j++],
                this.Rgbe2float(_e, c, d, _, b, (i.height - o) * s * 3 + k * 3);
            o--
        }
        return _e
    }
    ,
    a
}()
  , EffectRenderer = function() {
    function a(e, i) {
        var o, s = this;
        i === void 0 && (i = a._DefaultOptions),
        this.engine = e,
        this._fullscreenViewport = new Viewport(0,0,1,1),
        i = __assign(__assign({}, a._DefaultOptions), i),
        this._vertexBuffers = (o = {},
        o[VertexBuffer.PositionKind] = new VertexBuffer(e,i.positions,VertexBuffer.PositionKind,!1,!1,2),
        o),
        this._indexBuffer = e.createIndexBuffer(i.indices),
        this._onContextRestoredObserver = e.onContextRestoredObservable.add(function() {
            s._indexBuffer = e.createIndexBuffer(i.indices);
            for (var c in s._vertexBuffers) {
                var d = s._vertexBuffers[c];
                d._rebuild()
            }
        })
    }
    return a.prototype.setViewport = function(e) {
        e === void 0 && (e = this._fullscreenViewport),
        this.engine.setViewport(e)
    }
    ,
    a.prototype.bindBuffers = function(e) {
        this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, e)
    }
    ,
    a.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({})
    }
    ,
    a.prototype.restoreStates = function() {
        this.engine.depthCullingState.depthTest = !0,
        this.engine.stencilState.stencilTest = !0
    }
    ,
    a.prototype.draw = function() {
        this.engine.drawElementsType(0, 0, 6)
    }
    ,
    a.prototype.isRenderTargetTexture = function(e) {
        return e.renderTarget !== void 0
    }
    ,
    a.prototype.render = function(e, i) {
        if (i === void 0 && (i = null),
        !!e.effect.isReady()) {
            this.setViewport();
            var o = i === null ? null : this.isRenderTargetTexture(i) ? i.renderTarget : i;
            o && this.engine.bindFramebuffer(o),
            this.applyEffectWrapper(e),
            this.draw(),
            o && this.engine.unBindFramebuffer(o),
            this.restoreStates()
        }
    }
    ,
    a.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)
    }
    ,
    a._DefaultOptions = {
        positions: [1, 1, -1, 1, -1, -1, 1, -1],
        indices: [0, 1, 2, 0, 2, 3]
    },
    a
}()
  , EffectWrapper = function() {
    function a(e) {
        var i = this;
        this.onApplyObservable = new Observable;
        var o, s = e.uniformNames || [];
        e.vertexShader ? o = {
            fragmentSource: e.fragmentShader,
            vertexSource: e.vertexShader,
            spectorName: e.name || "effectWrapper"
        } : (s.push("scale"),
        o = {
            fragmentSource: e.fragmentShader,
            vertex: "postprocess",
            spectorName: e.name || "effectWrapper"
        },
        this.onApplyObservable.add(function() {
            i.effect.setFloat2("scale", 1, 1)
        }));
        var c = e.defines ? e.defines.join(`
`) : "";
        this._drawWrapper = new DrawWrapper(e.engine),
        e.useShaderStore ? (o.fragment = o.fragmentSource,
        o.vertex || (o.vertex = o.vertexSource),
        delete o.fragmentSource,
        delete o.vertexSource,
        this.effect = e.engine.createEffect(o, e.attributeNames || ["position"], s, e.samplerNames, c, void 0, e.onCompiled, void 0, void 0, e.shaderLanguage)) : (this.effect = new Effect(o,e.attributeNames || ["position"],s,e.samplerNames,e.engine,c,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),
        this._onContextRestoredObserver = e.engine.onContextRestoredObservable.add(function() {
            i.effect._pipelineContext = null,
            i.effect._wasPreviouslyReady = !1,
            i.effect._prepareEffect()
        }))
    }
    return Object.defineProperty(a.prototype, "effect", {
        get: function() {
            return this._drawWrapper.effect
        },
        set: function(e) {
            this._drawWrapper.effect = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.dispose = function() {
        this._onContextRestoredObserver && (this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),
        this._onContextRestoredObserver = null),
        this.effect.dispose()
    }
    ,
    a
}()
  , name$c = "hdrFilteringVertexShader"
  , shader$c = `
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$c] = shader$c;
var name$b = "hdrFilteringPixelShader"
  , shader$b = `#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$b] = shader$b;
var HDRFiltering = function() {
    function a(e, i) {
        i === void 0 && (i = {}),
        this._lodGenerationOffset = 0,
        this._lodGenerationScale = .8,
        this.quality = 4096,
        this.hdrScale = 1,
        this._engine = e,
        this.hdrScale = i.hdrScale || this.hdrScale,
        this.quality = i.hdrScale || this.quality
    }
    return a.prototype._createRenderTarget = function(e) {
        var i = 0;
        this._engine.getCaps().textureHalfFloatRender ? i = 2 : this._engine.getCaps().textureFloatRender && (i = 1);
        var o = this._engine.createRenderTargetCubeTexture(e, {
            format: 5,
            type: i,
            createMipMaps: !0,
            generateMipMaps: !1,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1,
            samplingMode: 1
        });
        return this._engine.updateTextureWrappingMode(o.texture, 0, 0, 0),
        this._engine.updateTextureSamplingMode(3, o.texture, !0),
        o
    }
    ,
    a.prototype._prefilterInternal = function(e) {
        var i = e.getSize().width
          , o = Scalar.ILog2(i) + 1
          , s = this._effectWrapper.effect
          , c = this._createRenderTarget(i);
        this._effectRenderer.setViewport();
        var d = e.getInternalTexture();
        d && this._engine.updateTextureSamplingMode(3, d, !0),
        this._effectRenderer.applyEffectWrapper(this._effectWrapper);
        var _ = [[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)]];
        s.setFloat("hdrScale", this.hdrScale),
        s.setFloat2("vFilteringInfo", e.getSize().width, o),
        s.setTexture("inputTexture", e);
        for (var b = 0; b < 6; b++) {
            s.setVector3("up", _[b][0]),
            s.setVector3("right", _[b][1]),
            s.setVector3("front", _[b][2]);
            for (var k = 0; k < o; k++) {
                this._engine.bindFramebuffer(c, b, void 0, void 0, !0, k),
                this._effectRenderer.applyEffectWrapper(this._effectWrapper);
                var j = Math.pow(2, (k - this._lodGenerationOffset) / this._lodGenerationScale) / i;
                k === 0 && (j = 0),
                s.setFloat("alphaG", j),
                this._effectRenderer.draw()
            }
        }
        return this._effectRenderer.restoreStates(),
        this._engine.restoreDefaultFramebuffer(),
        this._engine._releaseTexture(e._texture),
        c._swapAndDie(e._texture),
        e._prefiltered = !0,
        e
    }
    ,
    a.prototype._createEffect = function(e, i) {
        var o = [];
        e.gammaSpace && o.push("#define GAMMA_INPUT"),
        o.push("#define NUM_SAMPLES " + this.quality + "u");
        var s = 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: o,
            onCompiled: i
        });
        return s
    }
    ,
    a.prototype.isReady = function(e) {
        return e.isReady() && this._effectWrapper.effect.isReady()
    }
    ,
    a.prototype.prefilter = function(e, i) {
        var o = this;
        return i === void 0 && (i = null),
        this._engine._features.allowTexturePrefiltering ? new Promise(function(s) {
            o._effectRenderer = new EffectRenderer(o._engine),
            o._effectWrapper = o._createEffect(e),
            o._effectWrapper.effect.executeWhenCompiled(function() {
                o._prefilterInternal(e),
                o._effectRenderer.dispose(),
                o._effectWrapper.dispose(),
                s(),
                i && i()
            })
        }
        ) : (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."))
    }
    ,
    a
}()
  , HDRCubeTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b, k, j) {
        c === void 0 && (c = !1),
        d === void 0 && (d = !0),
        _ === void 0 && (_ = !1),
        b === void 0 && (b = !1),
        k === void 0 && (k = null),
        j === void 0 && (j = null);
        var $, _e = a.call(this, o) || this;
        return _e._generateHarmonics = !0,
        _e._onError = null,
        _e._isBlocking = !0,
        _e._rotationY = 0,
        _e.boundingBoxPosition = Vector3.Zero(),
        _e.onLoadObservable = new Observable,
        i && (_e._coordinatesMode = Texture.CUBIC_MODE,
        _e.name = i,
        _e.url = i,
        _e.hasAlpha = !1,
        _e.isCube = !0,
        _e._textureMatrix = Matrix.Identity(),
        _e._prefilterOnLoad = b,
        _e._onLoad = function() {
            _e.onLoadObservable.notifyObservers(_e),
            k && k()
        }
        ,
        _e._onError = j,
        _e.gammaSpace = _,
        _e._noMipmap = c,
        _e._size = s,
        _e._generateHarmonics = d,
        _e._texture = _e._getFromCache(i, _e._noMipmap),
        _e._texture ? _e._texture.isReady ? Tools.SetImmediate(function() {
            return _e._onLoad()
        }) : _e._texture.onLoadedObservable.add(_e._onLoad) : !(($ = _e.getScene()) === null || $ === void 0) && $.useDelayedTextureLoading ? _e.delayLoadState = 4 : _e.loadTexture()),
        _e
    }
    return Object.defineProperty(e.prototype, "isBlocking", {
        get: function() {
            return this._isBlocking
        },
        set: function(i) {
            this._isBlocking = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotationY", {
        get: function() {
            return this._rotationY
        },
        set: function(i) {
            this._rotationY = i,
            this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "boundingBoxSize", {
        get: function() {
            return this._boundingBoxSize
        },
        set: function(i) {
            if (!(this._boundingBoxSize && this._boundingBoxSize.equals(i))) {
                this._boundingBoxSize = i;
                var o = this.getScene();
                o && o.markAllMaterialsAsDirty(1)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "HDRCubeTexture"
    }
    ,
    e.prototype.loadTexture = function() {
        var i = this
          , o = this._getEngine()
          , s = o.getCaps()
          , c = 0;
        s.textureFloat && s.textureFloatLinearFiltering ? c = 1 : s.textureHalfFloat && s.textureHalfFloatLinearFiltering && (c = 2);
        var d = function(k) {
            i.lodGenerationOffset = 0,
            i.lodGenerationScale = .8;
            var j = HDRTools.GetCubeMapTextureData(k, i._size);
            if (i._generateHarmonics) {
                var $ = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(j);
                i.sphericalPolynomial = $
            }
            for (var _e = [], et = null, tt = null, rt = 0; rt < 6; rt++) {
                c === 2 ? tt = new Uint16Array(i._size * i._size * 3) : c === 0 && (et = new Uint8Array(i._size * i._size * 3));
                var it = j[e._facesMapping[rt]];
                if (i.gammaSpace || tt || et) {
                    for (var nt = 0; nt < i._size * i._size; nt++)
                        if (i.gammaSpace && (it[nt * 3 + 0] = Math.pow(it[nt * 3 + 0], ToGammaSpace),
                        it[nt * 3 + 1] = Math.pow(it[nt * 3 + 1], ToGammaSpace),
                        it[nt * 3 + 2] = Math.pow(it[nt * 3 + 2], ToGammaSpace)),
                        tt && (tt[nt * 3 + 0] = ToHalfFloat(it[nt * 3 + 0]),
                        tt[nt * 3 + 1] = ToHalfFloat(it[nt * 3 + 1]),
                        tt[nt * 3 + 2] = ToHalfFloat(it[nt * 3 + 2])),
                        et) {
                            var ot = Math.max(it[nt * 3 + 0] * 255, 0)
                              , at = Math.max(it[nt * 3 + 1] * 255, 0)
                              , st = Math.max(it[nt * 3 + 2] * 255, 0)
                              , ut = Math.max(Math.max(ot, at), st);
                            if (ut > 255) {
                                var ct = 255 / ut;
                                ot *= ct,
                                at *= ct,
                                st *= ct
                            }
                            et[nt * 3 + 0] = ot,
                            et[nt * 3 + 1] = at,
                            et[nt * 3 + 2] = st
                        }
                }
                tt ? _e.push(tt) : et ? _e.push(et) : _e.push(it)
            }
            return _e
        };
        if (o._features.allowTexturePrefiltering && this._prefilterOnLoad) {
            var _ = this._onLoad
              , b = new HDRFiltering(o);
            this._onLoad = function() {
                b.prefilter(i, _)
            }
        }
        this._texture = o.createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, 4, c, this._noMipmap, d, null, this._onLoad, this._onError)
    }
    ,
    e.prototype.clone = function() {
        var i = new e(this.url,this.getScene() || this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);
        return i.level = this.level,
        i.wrapU = this.wrapU,
        i.wrapV = this.wrapV,
        i.coordinatesIndex = this.coordinatesIndex,
        i.coordinatesMode = this.coordinatesMode,
        i
    }
    ,
    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(i) {
        var o = this, s;
        this._textureMatrix = i,
        i.updateFlag !== this._textureMatrix.updateFlag && i.isIdentity() !== this._textureMatrix.isIdentity() && ((s = this.getScene()) === null || s === void 0 || s.markAllMaterialsAsDirty(1, function(c) {
            return c.getActiveTextures().indexOf(o) !== -1
        }))
    }
    ,
    e.prototype.dispose = function() {
        this.onLoadObservable.clear(),
        a.prototype.dispose.call(this)
    }
    ,
    e.Parse = function(i, o, s) {
        var c = null;
        return i.name && !i.isRenderTarget && (c = new e(s + i.name,o,i.size,i.noMipmap,i.generateHarmonics,i.useInGammaSpace),
        c.name = i.name,
        c.hasAlpha = i.hasAlpha,
        c.level = i.level,
        c.coordinatesMode = i.coordinatesMode,
        c.isBlocking = i.isBlocking),
        c && (i.boundingBoxPosition && (c.boundingBoxPosition = Vector3.FromArray(i.boundingBoxPosition)),
        i.boundingBoxSize && (c.boundingBoxSize = Vector3.FromArray(i.boundingBoxSize)),
        i.rotationY && (c.rotationY = i.rotationY)),
        c
    }
    ,
    e.prototype.serialize = function() {
        if (!this.name)
            return null;
        var i = {};
        return i.name = this.name,
        i.hasAlpha = this.hasAlpha,
        i.isCube = !0,
        i.level = this.level,
        i.size = this._size,
        i.coordinatesMode = this.coordinatesMode,
        i.useInGammaSpace = this.gammaSpace,
        i.generateHarmonics = this._generateHarmonics,
        i.customType = "BABYLON.HDRCubeTexture",
        i.noMipmap = this._noMipmap,
        i.isBlocking = this._isBlocking,
        i.rotationY = this._rotationY,
        i
    }
    ,
    e._facesMapping = ["right", "left", "up", "down", "front", "back"],
    e
}(BaseTexture);
RegisterClass("BABYLON.HDRCubeTexture", HDRCubeTexture);
var PhysicsJoint = function() {
    function a(e, i) {
        this.type = e,
        this.jointData = i,
        i.nativeParams = i.nativeParams || {}
    }
    return Object.defineProperty(a.prototype, "physicsJoint", {
        get: function() {
            return this._physicsJoint
        },
        set: function(e) {
            this._physicsJoint,
            this._physicsJoint = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "physicsPlugin", {
        set: function(e) {
            this._physicsPlugin = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.executeNativeFunction = function(e) {
        e(this._physicsPlugin.world, this._physicsJoint)
    }
    ,
    a.DistanceJoint = 0,
    a.HingeJoint = 1,
    a.BallAndSocketJoint = 2,
    a.WheelJoint = 3,
    a.SliderJoint = 4,
    a.PrismaticJoint = 5,
    a.UniversalJoint = 6,
    a.Hinge2Joint = a.WheelJoint,
    a.PointToPointJoint = 8,
    a.SpringJoint = 9,
    a.LockJoint = 10,
    a
}();
(function(a) {
    __extends(e, a);
    function e(i) {
        return a.call(this, PhysicsJoint.DistanceJoint, i) || this
    }
    return e.prototype.updateDistance = function(i, o) {
        this._physicsPlugin.updateDistanceJoint(this, i, o)
    }
    ,
    e
}
)(PhysicsJoint);
var MotorEnabledJoint = function(a) {
    __extends(e, a);
    function e(i, o) {
        return a.call(this, i, o) || this
    }
    return e.prototype.setMotor = function(i, o) {
        this._physicsPlugin.setMotor(this, i || 0, o)
    }
    ,
    e.prototype.setLimit = function(i, o) {
        this._physicsPlugin.setLimit(this, i, o)
    }
    ,
    e
}(PhysicsJoint);
(function(a) {
    __extends(e, a);
    function e(i) {
        return a.call(this, PhysicsJoint.HingeJoint, i) || this
    }
    return e.prototype.setMotor = function(i, o) {
        this._physicsPlugin.setMotor(this, i || 0, o)
    }
    ,
    e.prototype.setLimit = function(i, o) {
        this._physicsPlugin.setLimit(this, i, o)
    }
    ,
    e
}
)(MotorEnabledJoint);
(function(a) {
    __extends(e, a);
    function e(i) {
        return a.call(this, PhysicsJoint.Hinge2Joint, i) || this
    }
    return e.prototype.setMotor = function(i, o, s) {
        s === void 0 && (s = 0),
        this._physicsPlugin.setMotor(this, i || 0, o, s)
    }
    ,
    e.prototype.setLimit = function(i, o, s) {
        s === void 0 && (s = 0),
        this._physicsPlugin.setLimit(this, i, o, s)
    }
    ,
    e
}
)(MotorEnabledJoint);
Mesh._PhysicsImpostorParser = function(a, e, i) {
    return new PhysicsImpostor(e,i.physicsImpostor,{
        mass: i.physicsMass,
        friction: i.physicsFriction,
        restitution: i.physicsRestitution
    },a)
}
;
var PhysicsImpostor = function() {
    function a(e, i, o, s) {
        var c = this;
        if (o === void 0 && (o = {
            mass: 0
        }),
        this.object = e,
        this.type = i,
        this._options = o,
        this._scene = s,
        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() {
            !c._physicsEngine || (c.object.translate(c._deltaPosition, -1),
            c._deltaRotationConjugated && c.object.rotationQuaternion && c.object.rotationQuaternion.multiplyToRef(c._deltaRotationConjugated, c.object.rotationQuaternion),
            c.object.computeWorldMatrix(!1),
            c.object.parent && c.object.rotationQuaternion ? (c.getParentsRotation(),
            c._tmpQuat.multiplyToRef(c.object.rotationQuaternion, c._tmpQuat)) : c._tmpQuat.copyFrom(c.object.rotationQuaternion || new Quaternion),
            c._options.disableBidirectionalTransformation || c.object.rotationQuaternion && c._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(c, c.object.getAbsolutePosition(), c._tmpQuat),
            c._onBeforePhysicsStepCallbacks.forEach(function(d) {
                d(c)
            }))
        }
        ,
        this.afterStep = function() {
            !c._physicsEngine || (c._onAfterPhysicsStepCallbacks.forEach(function(d) {
                d(c)
            }),
            c._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(c),
            c.object.parent && c.object.rotationQuaternion && (c.getParentsRotation(),
            c._tmpQuat.conjugateInPlace(),
            c._tmpQuat.multiplyToRef(c.object.rotationQuaternion, c.object.rotationQuaternion)),
            c.object.setAbsolutePosition(c.object.position),
            c._deltaRotation && c.object.rotationQuaternion && c.object.rotationQuaternion.multiplyToRef(c._deltaRotation, c.object.rotationQuaternion),
            c.object.translate(c._deltaPosition, 1))
        }
        ,
        this.onCollideEvent = null,
        this.onCollide = function(d) {
            if (!(!c._onPhysicsCollideCallbacks.length && !c.onCollideEvent) && !!c._physicsEngine) {
                var _ = c._physicsEngine.getImpostorWithPhysicsBody(d.body);
                _ && (c.onCollideEvent && c.onCollideEvent(c, _),
                c._onPhysicsCollideCallbacks.filter(function(b) {
                    return b.otherImpostors.indexOf(_) !== -1
                }).forEach(function(b) {
                    b.callback(c, _, d.point)
                }))
            }
        }
        ,
        !this.object) {
            Logger$2.Error("No object was provided. A physics object is obligatory");
            return
        }
        this.object.parent && o.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 = o.mass === void 0 ? 0 : o.mass,
        this._options.friction = o.friction === void 0 ? .2 : o.friction,
        this._options.restitution = o.restitution === void 0 ? .2 : o.restitution,
        this.soft && (this._options.mass = this._options.mass > 0 ? this._options.mass : 1,
        this._options.pressure = o.pressure === void 0 ? 200 : o.pressure,
        this._options.stiffness = o.stiffness === void 0 ? 1 : o.stiffness,
        this._options.velocityIterations = o.velocityIterations === void 0 ? 20 : o.velocityIterations,
        this._options.positionIterations = o.positionIterations === void 0 ? 20 : o.positionIterations,
        this._options.fixedPoints = o.fixedPoints === void 0 ? 0 : o.fixedPoints,
        this._options.margin = o.margin === void 0 ? 0 : o.margin,
        this._options.damping = o.damping === void 0 ? 0 : o.damping,
        this._options.path = o.path === void 0 ? null : o.path,
        this._options.shape = o.shape === void 0 ? null : o.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(a.prototype, "isDisposed", {
        get: function() {
            return this._isDisposed
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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(a.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(a.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 i = this._physicsEngine.getPhysicsPlugin();
                !i.setBodyPressure || i.setBodyPressure(this, e)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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 i = this._physicsEngine.getPhysicsPlugin();
                !i.setBodyStiffness || i.setBodyStiffness(this, e)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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 i = this._physicsEngine.getPhysicsPlugin();
                !i.setBodyVelocityIterations || i.setBodyVelocityIterations(this, e)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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 i = this._physicsEngine.getPhysicsPlugin();
                !i.setBodyPositionIterations || i.setBodyPositionIterations(this, e)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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))
    }
    ,
    a.prototype._getPhysicsParent = function() {
        if (this.object.parent instanceof AbstractMesh) {
            var e = this.object.parent;
            return e.physicsImpostor
        }
        return null
    }
    ,
    a.prototype.isBodyInitRequired = function() {
        return this._bodyUpdateRequired || !this._physicsBody && !this._parent
    }
    ,
    a.prototype.setScalingUpdated = function() {
        this.forceUpdate()
    }
    ,
    a.prototype.forceUpdate = function() {
        this._init(),
        this.parent && !this._options.ignoreParent && this.parent.forceUpdate()
    }
    ,
    Object.defineProperty(a.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(a.prototype, "parent", {
        get: function() {
            return !this._options.ignoreParent && this._parent ? this._parent : null
        },
        set: function(e) {
            this._parent = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.resetUpdateFlags = function() {
        this._bodyUpdateRequired = !1
    }
    ,
    a.prototype.getObjectExtendSize = function() {
        if (this.object.getBoundingInfo) {
            var e = this.object.rotationQuaternion
              , i = this.object.scaling.clone();
            this.object.rotationQuaternion = a.IDENTITY_QUATERNION;
            var o = this.object.computeWorldMatrix && this.object.computeWorldMatrix(!0);
            o && o.decompose(i, void 0, void 0);
            var s = this.object.getBoundingInfo()
              , c = s.boundingBox.extendSize.scale(2).multiplyInPlace(i);
            return c.x = Math.abs(c.x),
            c.y = Math.abs(c.y),
            c.z = Math.abs(c.z),
            this.object.rotationQuaternion = e,
            this.object.computeWorldMatrix && this.object.computeWorldMatrix(!0),
            c
        } else
            return a.DEFAULT_OBJECT_SIZE
    }
    ,
    a.prototype.getObjectCenter = function() {
        if (this.object.getBoundingInfo) {
            var e = this.object.getBoundingInfo();
            return e.boundingBox.centerWorld
        } else
            return this.object.position
    }
    ,
    a.prototype.getParam = function(e) {
        return this._options[e]
    }
    ,
    a.prototype.setParam = function(e, i) {
        this._options[e] = i,
        this._bodyUpdateRequired = !0
    }
    ,
    a.prototype.setMass = function(e) {
        this.getParam("mass") !== e && this.setParam("mass", e),
        this._physicsEngine && this._physicsEngine.getPhysicsPlugin().setBodyMass(this, e)
    }
    ,
    a.prototype.getLinearVelocity = function() {
        return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : Vector3.Zero()
    }
    ,
    a.prototype.setLinearVelocity = function(e) {
        this._physicsEngine && this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, e)
    }
    ,
    a.prototype.getAngularVelocity = function() {
        return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : Vector3.Zero()
    }
    ,
    a.prototype.setAngularVelocity = function(e) {
        this._physicsEngine && this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, e)
    }
    ,
    a.prototype.executeNativeFunction = function(e) {
        this._physicsEngine && e(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody)
    }
    ,
    a.prototype.registerBeforePhysicsStep = function(e) {
        this._onBeforePhysicsStepCallbacks.push(e)
    }
    ,
    a.prototype.unregisterBeforePhysicsStep = function(e) {
        var i = this._onBeforePhysicsStepCallbacks.indexOf(e);
        i > -1 ? this._onBeforePhysicsStepCallbacks.splice(i, 1) : Logger$2.Warn("Function to remove was not found")
    }
    ,
    a.prototype.registerAfterPhysicsStep = function(e) {
        this._onAfterPhysicsStepCallbacks.push(e)
    }
    ,
    a.prototype.unregisterAfterPhysicsStep = function(e) {
        var i = this._onAfterPhysicsStepCallbacks.indexOf(e);
        i > -1 ? this._onAfterPhysicsStepCallbacks.splice(i, 1) : Logger$2.Warn("Function to remove was not found")
    }
    ,
    a.prototype.registerOnPhysicsCollide = function(e, i) {
        var o = e instanceof Array ? e : [e];
        this._onPhysicsCollideCallbacks.push({
            callback: i,
            otherImpostors: o
        })
    }
    ,
    a.prototype.unregisterOnPhysicsCollide = function(e, i) {
        var o = e instanceof Array ? e : [e]
          , s = -1
          , c = this._onPhysicsCollideCallbacks.some(function(d, _) {
            if (d.callback === i && d.otherImpostors.length === o.length) {
                var b = d.otherImpostors.every(function(k) {
                    return o.indexOf(k) > -1
                });
                return b && (s = _),
                b
            }
            return !1
        });
        c ? this._onPhysicsCollideCallbacks.splice(s, 1) : Logger$2.Warn("Function to remove was not found")
    }
    ,
    a.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
    }
    ,
    a.prototype.applyForce = function(e, i) {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().applyForce(this, e, i),
        this
    }
    ,
    a.prototype.applyImpulse = function(e, i) {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().applyImpulse(this, e, i),
        this
    }
    ,
    a.prototype.createJoint = function(e, i, o) {
        var s = new PhysicsJoint(i,o);
        return this.addJoint(e, s),
        this
    }
    ,
    a.prototype.addJoint = function(e, i) {
        return this._joints.push({
            otherImpostor: e,
            joint: i
        }),
        this._physicsEngine && this._physicsEngine.addJoint(this, e, i),
        this
    }
    ,
    a.prototype.addAnchor = function(e, i, o, s, c) {
        if (!this._physicsEngine)
            return this;
        var d = this._physicsEngine.getPhysicsPlugin();
        return d.appendAnchor ? (this._physicsEngine && d.appendAnchor(this, e, i, o, s, c),
        this) : this
    }
    ,
    a.prototype.addHook = function(e, i, o, s) {
        if (!this._physicsEngine)
            return this;
        var c = this._physicsEngine.getPhysicsPlugin();
        return c.appendAnchor ? (this._physicsEngine && c.appendHook(this, e, i, o, s),
        this) : this
    }
    ,
    a.prototype.sleep = function() {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().sleepBody(this),
        this
    }
    ,
    a.prototype.wakeUp = function() {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),
        this
    }
    ,
    a.prototype.clone = function(e) {
        return e ? new a(e,this.type,this._options,this._scene) : null
    }
    ,
    a.prototype.dispose = function() {
        var e = this;
        !this._physicsEngine || (this._joints.forEach(function(i) {
            e._physicsEngine && e._physicsEngine.removeJoint(e, i.otherImpostor, i.joint)
        }),
        this._physicsEngine.removeImpostor(this),
        this.parent && this.parent.forceUpdate(),
        this._isDisposed = !0)
    }
    ,
    a.prototype.setDeltaPosition = function(e) {
        this._deltaPosition.copyFrom(e)
    }
    ,
    a.prototype.setDeltaRotation = function(e) {
        this._deltaRotation || (this._deltaRotation = new Quaternion),
        this._deltaRotation.copyFrom(e),
        this._deltaRotationConjugated = this._deltaRotation.conjugate()
    }
    ,
    a.prototype.getBoxSizeToRef = function(e) {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, e),
        this
    }
    ,
    a.prototype.getRadius = function() {
        return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0
    }
    ,
    a.prototype.syncBoneWithImpostor = function(e, i, o, s, c) {
        var d = a._tmpVecs[0]
          , _ = this.object;
        if (_.rotationQuaternion)
            if (c) {
                var b = a._tmpQuat;
                _.rotationQuaternion.multiplyToRef(c, b),
                e.setRotationQuaternion(b, Space.WORLD, i)
            } else
                e.setRotationQuaternion(_.rotationQuaternion, Space.WORLD, i);
        d.x = 0,
        d.y = 0,
        d.z = 0,
        o && (d.x = o.x,
        d.y = o.y,
        d.z = o.z,
        e.getDirectionToRef(d, i, d),
        s == null && (s = o.length()),
        d.x *= s,
        d.y *= s,
        d.z *= s),
        e.getParent() ? (d.addInPlace(_.getAbsolutePosition()),
        e.setAbsolutePosition(d, i)) : (i.setAbsolutePosition(_.getAbsolutePosition()),
        i.position.x -= d.x,
        i.position.y -= d.y,
        i.position.z -= d.z)
    }
    ,
    a.prototype.syncImpostorWithBone = function(e, i, o, s, c, d) {
        var _ = this.object;
        if (_.rotationQuaternion)
            if (c) {
                var b = a._tmpQuat;
                e.getRotationQuaternionToRef(Space.WORLD, i, b),
                b.multiplyToRef(c, _.rotationQuaternion)
            } else
                e.getRotationQuaternionToRef(Space.WORLD, i, _.rotationQuaternion);
        var k = a._tmpVecs[0]
          , j = a._tmpVecs[1];
        d || (d = a._tmpVecs[2],
        d.x = 0,
        d.y = 1,
        d.z = 0),
        e.getDirectionToRef(d, i, j),
        e.getAbsolutePositionToRef(i, k),
        s == null && o && (s = o.length()),
        s != null && (k.x += j.x * s,
        k.y += j.y * s,
        k.z += j.z * s),
        _.setAbsolutePosition(k)
    }
    ,
    a.DEFAULT_OBJECT_SIZE = new Vector3(1,1,1),
    a.IDENTITY_QUATERNION = Quaternion.Identity(),
    a._tmpVecs = ArrayTools.BuildArray(3, Vector3.Zero),
    a._tmpQuat = Quaternion.Identity(),
    a.NoImpostor = 0,
    a.SphereImpostor = 1,
    a.BoxImpostor = 2,
    a.PlaneImpostor = 3,
    a.MeshImpostor = 4,
    a.CapsuleImpostor = 6,
    a.CylinderImpostor = 7,
    a.ParticleImpostor = 8,
    a.HeightmapImpostor = 9,
    a.ConvexHullImpostor = 10,
    a.CustomImpostor = 100,
    a.RopeImpostor = 101,
    a.ClothImpostor = 102,
    a.SoftbodyImpostor = 103,
    a
}()
  , PhysicsEngine = function() {
    function a(e, i) {
        if (i === void 0 && (i = a.DefaultPluginFactory()),
        this._physicsPlugin = i,
        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 a.DefaultPluginFactory = function() {
        throw _WarnImport("CannonJSPlugin")
    }
    ,
    a.prototype.setGravity = function(e) {
        this.gravity = e,
        this._physicsPlugin.setGravity(this.gravity)
    }
    ,
    a.prototype.setTimeStep = function(e) {
        e === void 0 && (e = 1 / 60),
        this._physicsPlugin.setTimeStep(e)
    }
    ,
    a.prototype.getTimeStep = function() {
        return this._physicsPlugin.getTimeStep()
    }
    ,
    a.prototype.setSubTimeStep = function(e) {
        e === void 0 && (e = 0),
        this._subTimeStep = e
    }
    ,
    a.prototype.getSubTimeStep = function() {
        return this._subTimeStep
    }
    ,
    a.prototype.dispose = function() {
        this._impostors.forEach(function(e) {
            e.dispose()
        }),
        this._physicsPlugin.dispose()
    }
    ,
    a.prototype.getPhysicsPluginName = function() {
        return this._physicsPlugin.name
    }
    ,
    a.prototype.addImpostor = function(e) {
        e.uniqueId = this._impostors.push(e),
        e.parent || this._physicsPlugin.generatePhysicsBody(e)
    }
    ,
    a.prototype.removeImpostor = function(e) {
        var i = this._impostors.indexOf(e);
        if (i > -1) {
            var o = this._impostors.splice(i, 1);
            o.length && this.getPhysicsPlugin().removePhysicsBody(e)
        }
    }
    ,
    a.prototype.addJoint = function(e, i, o) {
        var s = {
            mainImpostor: e,
            connectedImpostor: i,
            joint: o
        };
        o.physicsPlugin = this._physicsPlugin,
        this._joints.push(s),
        this._physicsPlugin.generateJoint(s)
    }
    ,
    a.prototype.removeJoint = function(e, i, o) {
        var s = this._joints.filter(function(c) {
            return c.connectedImpostor === i && c.joint === o && c.mainImpostor === e
        });
        s.length && this._physicsPlugin.removeJoint(s[0])
    }
    ,
    a.prototype._step = function(e) {
        var i = this;
        this._impostors.forEach(function(o) {
            o.isBodyInitRequired() && i._physicsPlugin.generatePhysicsBody(o)
        }),
        e > .1 ? e = .1 : e <= 0 && (e = 1 / 60),
        this._physicsPlugin.executeStep(e, this._impostors)
    }
    ,
    a.prototype.getPhysicsPlugin = function() {
        return this._physicsPlugin
    }
    ,
    a.prototype.getImpostors = function() {
        return this._impostors
    }
    ,
    a.prototype.getImpostorForPhysicsObject = function(e) {
        for (var i = 0; i < this._impostors.length; ++i)
            if (this._impostors[i].object === e)
                return this._impostors[i];
        return null
    }
    ,
    a.prototype.getImpostorWithPhysicsBody = function(e) {
        for (var i = 0; i < this._impostors.length; ++i)
            if (this._impostors[i].physicsBody === e)
                return this._impostors[i];
        return null
    }
    ,
    a.prototype.raycast = function(e, i) {
        return this._physicsPlugin.raycast(e, i)
    }
    ,
    a.Epsilon = .001,
    a
}()
  , PhysicsRaycastResult = function() {
    function a() {
        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(a.prototype, "hasHit", {
        get: function() {
            return this._hasHit
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hitDistance", {
        get: function() {
            return this._hitDistance
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hitNormalWorld", {
        get: function() {
            return this._hitNormalWorld
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hitPointWorld", {
        get: function() {
            return this._hitPointWorld
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rayFromWorld", {
        get: function() {
            return this._rayFromWorld
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rayToWorld", {
        get: function() {
            return this._rayToWorld
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setHitData = function(e, i) {
        this._hasHit = !0,
        this._hitNormalWorld = new Vector3(e.x,e.y,e.z),
        this._hitPointWorld = new Vector3(i.x,i.y,i.z)
    }
    ,
    a.prototype.setHitDistance = function(e) {
        this._hitDistance = e
    }
    ,
    a.prototype.calculateHitDistance = function() {
        this._hitDistance = Vector3.Distance(this._rayFromWorld, this._hitPointWorld)
    }
    ,
    a.prototype.reset = function(e, i) {
        e === void 0 && (e = Vector3.Zero()),
        i === void 0 && (i = Vector3.Zero()),
        this._rayFromWorld = e,
        this._rayToWorld = i,
        this._hasHit = !1,
        this._hitDistance = 0,
        this._hitNormalWorld = Vector3.Zero(),
        this._hitPointWorld = Vector3.Zero()
    }
    ,
    a
}()
  , CannonJSPlugin = function() {
    function a(e, i, o) {
        if (e === void 0 && (e = !0),
        i === void 0 && (i = 10),
        o === void 0 && (o = 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 = o,
        !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 = i,
        this._cannonRaycastResult = new this.BJSCANNON.RaycastResult,
        this._raycastResult = new PhysicsRaycastResult
    }
    return a.prototype.setGravity = function(e) {
        var i = e;
        this.world.gravity.set(i.x, i.y, i.z)
    }
    ,
    a.prototype.setTimeStep = function(e) {
        this._fixedTimeStep = e
    }
    ,
    a.prototype.getTimeStep = function() {
        return this._fixedTimeStep
    }
    ,
    a.prototype.executeStep = function(e, i) {
        if (this._firstFrame) {
            this._firstFrame = !1;
            for (var o = 0, s = i; o < s.length; o++) {
                var c = s[o];
                c.type == PhysicsImpostor.HeightmapImpostor || c.type === PhysicsImpostor.PlaneImpostor || c.beforeStep()
            }
        }
        this.world.step(this._useDeltaForWorldStep ? e : this._fixedTimeStep),
        this._removeMarkedPhysicsBodiesFromWorld()
    }
    ,
    a.prototype._removeMarkedPhysicsBodiesFromWorld = function() {
        var e = this;
        this._physicsBodysToRemoveAfterStep.length > 0 && (this._physicsBodysToRemoveAfterStep.forEach(function(i) {
            typeof e.world.removeBody == "function" ? e.world.removeBody(i) : e.world.remove(i)
        }),
        this._physicsBodysToRemoveAfterStep = [])
    }
    ,
    a.prototype.applyImpulse = function(e, i, o) {
        var s = new this.BJSCANNON.Vec3(o.x,o.y,o.z)
          , c = new this.BJSCANNON.Vec3(i.x,i.y,i.z);
        e.physicsBody.applyImpulse(c, s)
    }
    ,
    a.prototype.applyForce = function(e, i, o) {
        var s = new this.BJSCANNON.Vec3(o.x,o.y,o.z)
          , c = new this.BJSCANNON.Vec3(i.x,i.y,i.z);
        e.physicsBody.applyForce(c, s)
    }
    ,
    a.prototype.generatePhysicsBody = function(e) {
        if (this._removeMarkedPhysicsBodiesFromWorld(),
        e.parent) {
            e.physicsBody && (this.removePhysicsBody(e),
            e.forceUpdate());
            return
        }
        if (e.isBodyInitRequired()) {
            var i = this._createShape(e)
              , o = e.physicsBody;
            o && this.removePhysicsBody(e);
            var s = this._addMaterial("mat-" + e.uniqueId, e.getParam("friction"), e.getParam("restitution"))
              , c = {
                mass: e.getParam("mass"),
                material: s
            }
              , d = e.getParam("nativeOptions");
            for (var _ in d)
                d.hasOwnProperty(_) && (c[_] = d[_]);
            e.physicsBody = new this.BJSCANNON.Body(c),
            e.physicsBody.addEventListener("collide", e.onCollide),
            this.world.addEventListener("preStep", e.beforeStep),
            this.world.addEventListener("postStep", e.afterStep),
            e.physicsBody.addShape(i),
            typeof this.world.addBody == "function" ? this.world.addBody(e.physicsBody) : this.world.add(e.physicsBody),
            o && ["force", "torque", "velocity", "angularVelocity"].forEach(function(b) {
                var k = o[b];
                e.physicsBody[b].set(k.x, k.y, k.z)
            }),
            this._processChildMeshes(e)
        }
        this._updatePhysicsBodyTransformation(e)
    }
    ,
    a.prototype._processChildMeshes = function(e) {
        var i = this
          , o = e.object.getChildMeshes ? e.object.getChildMeshes(!0) : []
          , s = e.object.rotationQuaternion;
        if (s ? s.conjugateToRef(this._tmpQuaternion) : this._tmpQuaternion.set(0, 0, 0, 1),
        o.length) {
            var c = function(d) {
                if (!!d.rotationQuaternion) {
                    var _ = d.getPhysicsImpostor();
                    if (_) {
                        var b = _.parent;
                        if (b !== e && d.parent) {
                            var k = d.getAbsolutePosition().subtract(d.parent.getAbsolutePosition())
                              , j = d.rotationQuaternion.multiply(i._tmpQuaternion);
                            _.physicsBody && (i.removePhysicsBody(_),
                            _.physicsBody = null),
                            _.parent = e,
                            _.resetUpdateFlags(),
                            e.physicsBody.addShape(i._createShape(_), new i.BJSCANNON.Vec3(k.x,k.y,k.z), new i.BJSCANNON.Quaternion(j.x,j.y,j.z,j.w)),
                            e.physicsBody.mass += _.getParam("mass")
                        }
                    }
                    d.getChildMeshes(!0).filter(function($) {
                        return !!$.physicsImpostor
                    }).forEach(c)
                }
            };
            o.filter(function(d) {
                return !!d.physicsImpostor
            }).forEach(c)
        }
    }
    ,
    a.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)
    }
    ,
    a.prototype.generateJoint = function(e) {
        var i = e.mainImpostor.physicsBody
          , o = e.connectedImpostor.physicsBody;
        if (!(!i || !o)) {
            var s, c = e.joint.jointData, d = {
                pivotA: c.mainPivot ? new this.BJSCANNON.Vec3().set(c.mainPivot.x, c.mainPivot.y, c.mainPivot.z) : null,
                pivotB: c.connectedPivot ? new this.BJSCANNON.Vec3().set(c.connectedPivot.x, c.connectedPivot.y, c.connectedPivot.z) : null,
                axisA: c.mainAxis ? new this.BJSCANNON.Vec3().set(c.mainAxis.x, c.mainAxis.y, c.mainAxis.z) : null,
                axisB: c.connectedAxis ? new this.BJSCANNON.Vec3().set(c.connectedAxis.x, c.connectedAxis.y, c.connectedAxis.z) : null,
                maxForce: c.nativeParams.maxForce,
                collideConnected: !!c.collision
            };
            switch (e.joint.type) {
            case PhysicsJoint.HingeJoint:
            case PhysicsJoint.Hinge2Joint:
                s = new this.BJSCANNON.HingeConstraint(i,o,d);
                break;
            case PhysicsJoint.DistanceJoint:
                s = new this.BJSCANNON.DistanceConstraint(i,o,c.maxDistance || 2);
                break;
            case PhysicsJoint.SpringJoint:
                var _ = c;
                s = new this.BJSCANNON.Spring(i,o,{
                    restLength: _.length,
                    stiffness: _.stiffness,
                    damping: _.damping,
                    localAnchorA: d.pivotA,
                    localAnchorB: d.pivotB
                });
                break;
            case PhysicsJoint.LockJoint:
                s = new this.BJSCANNON.LockConstraint(i,o,d);
                break;
            case PhysicsJoint.PointToPointJoint:
            case PhysicsJoint.BallAndSocketJoint:
            default:
                s = new this.BJSCANNON.PointToPointConstraint(i,d.pivotA,o,d.pivotB,d.maxForce);
                break
            }
            s.collideConnected = !!c.collision,
            e.joint.physicsJoint = s,
            e.joint.type !== PhysicsJoint.SpringJoint ? this.world.addConstraint(s) : (e.joint.jointData.forceApplicationCallback = e.joint.jointData.forceApplicationCallback || function() {
                s.applyForce()
            }
            ,
            e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))
        }
    }
    ,
    a.prototype.removeJoint = function(e) {
        e.joint.type !== PhysicsJoint.SpringJoint ? this.world.removeConstraint(e.joint.physicsJoint) : e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)
    }
    ,
    a.prototype._addMaterial = function(e, i, o) {
        var s, c;
        for (s = 0; s < this._physicsMaterials.length; s++)
            if (c = this._physicsMaterials[s],
            c.friction === i && c.restitution === o)
                return c;
        var d = new this.BJSCANNON.Material(e);
        return d.friction = i,
        d.restitution = o,
        this._physicsMaterials.push(d),
        d
    }
    ,
    a.prototype._checkWithEpsilon = function(e) {
        return e < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : e
    }
    ,
    a.prototype._createShape = function(e) {
        var i = e.object, o, s = e.getObjectExtendSize();
        switch (e.type) {
        case PhysicsImpostor.SphereImpostor:
            var c = s.x
              , d = s.y
              , _ = s.z;
            o = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(c), this._checkWithEpsilon(d), this._checkWithEpsilon(_)) / 2);
            break;
        case PhysicsImpostor.CylinderImpostor:
            var b = e.getParam("nativeOptions");
            b || (b = {});
            var k = b.radiusTop !== void 0 ? b.radiusTop : this._checkWithEpsilon(s.x) / 2
              , j = b.radiusBottom !== void 0 ? b.radiusBottom : this._checkWithEpsilon(s.x) / 2
              , $ = b.height !== void 0 ? b.height : this._checkWithEpsilon(s.y)
              , _e = b.numSegments !== void 0 ? b.numSegments : 16;
            o = new this.BJSCANNON.Cylinder(k,j,$,_e);
            var et = new this.BJSCANNON.Quaternion;
            et.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0), -Math.PI / 2);
            var tt = new this.BJSCANNON.Vec3(0,0,0);
            o.transformAllPoints(tt, et);
            break;
        case PhysicsImpostor.BoxImpostor:
            var rt = s.scale(.5);
            o = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(rt.x),this._checkWithEpsilon(rt.y),this._checkWithEpsilon(rt.z)));
            break;
        case PhysicsImpostor.PlaneImpostor:
            Logger$2.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),
            o = new this.BJSCANNON.Plane;
            break;
        case PhysicsImpostor.MeshImpostor:
            var it = i.getVerticesData ? i.getVerticesData(VertexBuffer.PositionKind) : []
              , nt = i.getIndices ? i.getIndices() : [];
            if (!it)
                return;
            var ot = i.position.clone()
              , at = i.rotation && i.rotation.clone()
              , st = i.rotationQuaternion && i.rotationQuaternion.clone();
            i.position.copyFromFloats(0, 0, 0),
            i.rotation && i.rotation.copyFromFloats(0, 0, 0),
            i.rotationQuaternion && i.rotationQuaternion.copyFrom(e.getParentsRotation()),
            i.rotationQuaternion && i.parent && i.rotationQuaternion.conjugateInPlace();
            var ut = i.computeWorldMatrix(!0), ct = new Array, lt;
            for (lt = 0; lt < it.length; lt += 3)
                Vector3.TransformCoordinates(Vector3.FromArray(it, lt), ut).toArray(ct, lt);
            Logger$2.Warn("MeshImpostor only collides against spheres."),
            o = new this.BJSCANNON.Trimesh(ct,nt),
            i.position.copyFrom(ot),
            at && i.rotation && i.rotation.copyFrom(at),
            st && i.rotationQuaternion && i.rotationQuaternion.copyFrom(st);
            break;
        case PhysicsImpostor.HeightmapImpostor:
            var ft = i.position.clone()
              , ht = i.rotation && i.rotation.clone()
              , pt = i.rotationQuaternion && i.rotationQuaternion.clone();
            i.position.copyFromFloats(0, 0, 0),
            i.rotation && i.rotation.copyFromFloats(0, 0, 0),
            i.rotationQuaternion && i.rotationQuaternion.copyFrom(e.getParentsRotation()),
            i.rotationQuaternion && i.parent && i.rotationQuaternion.conjugateInPlace(),
            i.rotationQuaternion && i.rotationQuaternion.multiplyInPlace(this._minus90X),
            o = this._createHeightmap(i),
            i.position.copyFrom(ft),
            ht && i.rotation && i.rotation.copyFrom(ht),
            pt && i.rotationQuaternion && i.rotationQuaternion.copyFrom(pt),
            i.computeWorldMatrix(!0);
            break;
        case PhysicsImpostor.ParticleImpostor:
            o = new this.BJSCANNON.Particle;
            break;
        case PhysicsImpostor.NoImpostor:
            o = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0));
            break
        }
        return o
    }
    ,
    a.prototype._createHeightmap = function(e, i) {
        var o = e.getVerticesData(VertexBuffer.PositionKind), s = e.computeWorldMatrix(!0), c = new Array, d;
        for (d = 0; d < o.length; d += 3)
            Vector3.TransformCoordinates(Vector3.FromArray(o, d), s).toArray(c, d);
        o = c;
        for (var _ = new Array, b = i || ~~(Math.sqrt(o.length / 3) - 1), k = e.getBoundingInfo(), j = Math.min(k.boundingBox.extendSizeWorld.x, k.boundingBox.extendSizeWorld.y), $ = k.boundingBox.extendSizeWorld.z, _e = j * 2 / b, et = 0; et < o.length; et = et + 3) {
            var tt = Math.round(o[et + 0] / _e + b / 2)
              , rt = Math.round((o[et + 1] / _e - b / 2) * -1)
              , it = -o[et + 2] + $;
            _[tt] || (_[tt] = []),
            _[tt][rt] || (_[tt][rt] = it),
            _[tt][rt] = Math.max(it, _[tt][rt])
        }
        for (var tt = 0; tt <= b; ++tt) {
            if (!_[tt]) {
                for (var nt = 1; !_[(tt + nt) % b]; )
                    nt++;
                _[tt] = _[(tt + nt) % b].slice()
            }
            for (var rt = 0; rt <= b; ++rt)
                if (!_[tt][rt]) {
                    for (var nt = 1, ot; ot === void 0; )
                        ot = _[tt][(rt + nt++) % b];
                    _[tt][rt] = ot
                }
        }
        var at = new this.BJSCANNON.Heightfield(_,{
            elementSize: _e
        });
        return at.minY = $,
        at
    }
    ,
    a.prototype._updatePhysicsBodyTransformation = function(e) {
        var i = e.object;
        if (i.computeWorldMatrix && i.computeWorldMatrix(!0),
        !!i.getBoundingInfo()) {
            var o = e.getObjectCenter();
            this._tmpDeltaPosition.copyFrom(i.getAbsolutePivotPoint().subtract(o)),
            this._tmpDeltaPosition.divideInPlace(e.object.scaling),
            this._tmpPosition.copyFrom(o);
            var s = i.rotationQuaternion;
            if (!!s) {
                if ((e.type === PhysicsImpostor.PlaneImpostor || e.type === PhysicsImpostor.HeightmapImpostor) && (s = s.multiply(this._minus90X),
                e.setDeltaRotation(this._plus90X)),
                e.type === PhysicsImpostor.HeightmapImpostor) {
                    var c = i
                      , d = c.getBoundingInfo()
                      , _ = c.rotationQuaternion;
                    c.rotationQuaternion = this._tmpUnityRotation,
                    c.computeWorldMatrix(!0);
                    var b = o.clone()
                      , k = c.getPivotMatrix();
                    k ? k = k.clone() : k = Matrix.Identity();
                    var j = Matrix.Translation(d.boundingBox.extendSizeWorld.x, 0, -d.boundingBox.extendSizeWorld.z);
                    c.setPreTransformMatrix(j),
                    c.computeWorldMatrix(!0),
                    d = c.getBoundingInfo();
                    var $ = d.boundingBox.centerWorld.subtract(o).subtract(c.position).negate();
                    this._tmpPosition.copyFromFloats($.x, $.y - d.boundingBox.extendSizeWorld.y, $.z),
                    this._tmpDeltaPosition.copyFrom(d.boundingBox.centerWorld.subtract(b)),
                    this._tmpDeltaPosition.y += d.boundingBox.extendSizeWorld.y,
                    c.rotationQuaternion = _,
                    c.setPreTransformMatrix(k),
                    c.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(s.x, s.y, s.z, s.w)
            }
        }
    }
    ,
    a.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 i = e.physicsBody.quaternion;
            e.object.rotationQuaternion.set(i.x, i.y, i.z, i.w)
        }
    }
    ,
    a.prototype.setPhysicsBodyTransformation = function(e, i, o) {
        e.physicsBody.position.set(i.x, i.y, i.z),
        e.physicsBody.quaternion.set(o.x, o.y, o.z, o.w)
    }
    ,
    a.prototype.isSupported = function() {
        return this.BJSCANNON !== void 0
    }
    ,
    a.prototype.setLinearVelocity = function(e, i) {
        e.physicsBody.velocity.set(i.x, i.y, i.z)
    }
    ,
    a.prototype.setAngularVelocity = function(e, i) {
        e.physicsBody.angularVelocity.set(i.x, i.y, i.z)
    }
    ,
    a.prototype.getLinearVelocity = function(e) {
        var i = e.physicsBody.velocity;
        return i ? new Vector3(i.x,i.y,i.z) : null
    }
    ,
    a.prototype.getAngularVelocity = function(e) {
        var i = e.physicsBody.angularVelocity;
        return i ? new Vector3(i.x,i.y,i.z) : null
    }
    ,
    a.prototype.setBodyMass = function(e, i) {
        e.physicsBody.mass = i,
        e.physicsBody.updateMassProperties()
    }
    ,
    a.prototype.getBodyMass = function(e) {
        return e.physicsBody.mass
    }
    ,
    a.prototype.getBodyFriction = function(e) {
        return e.physicsBody.material.friction
    }
    ,
    a.prototype.setBodyFriction = function(e, i) {
        e.physicsBody.material.friction = i
    }
    ,
    a.prototype.getBodyRestitution = function(e) {
        return e.physicsBody.material.restitution
    }
    ,
    a.prototype.setBodyRestitution = function(e, i) {
        e.physicsBody.material.restitution = i
    }
    ,
    a.prototype.sleepBody = function(e) {
        e.physicsBody.sleep()
    }
    ,
    a.prototype.wakeUpBody = function(e) {
        e.physicsBody.wakeUp()
    }
    ,
    a.prototype.updateDistanceJoint = function(e, i) {
        e.physicsJoint.distance = i
    }
    ,
    a.prototype.setMotor = function(e, i, o, s) {
        s || (e.physicsJoint.enableMotor(),
        e.physicsJoint.setMotorSpeed(i),
        o && this.setLimit(e, o))
    }
    ,
    a.prototype.setLimit = function(e, i, o) {
        e.physicsJoint.motorEquation.maxForce = i,
        e.physicsJoint.motorEquation.minForce = o === void 0 ? -i : o
    }
    ,
    a.prototype.syncMeshWithImpostor = function(e, i) {
        var o = i.physicsBody;
        e.position.x = o.position.x,
        e.position.y = o.position.y,
        e.position.z = o.position.z,
        e.rotationQuaternion && (e.rotationQuaternion.x = o.quaternion.x,
        e.rotationQuaternion.y = o.quaternion.y,
        e.rotationQuaternion.z = o.quaternion.z,
        e.rotationQuaternion.w = o.quaternion.w)
    }
    ,
    a.prototype.getRadius = function(e) {
        var i = e.physicsBody.shapes[0];
        return i.boundingSphereRadius
    }
    ,
    a.prototype.getBoxSizeToRef = function(e, i) {
        var o = e.physicsBody.shapes[0];
        i.x = o.halfExtents.x * 2,
        i.y = o.halfExtents.y * 2,
        i.z = o.halfExtents.z * 2
    }
    ,
    a.prototype.dispose = function() {}
    ,
    a.prototype._extendNamespace = function() {
        var e = new this.BJSCANNON.Vec3
          , i = this.BJSCANNON;
        this.BJSCANNON.World.prototype.step = function(o, s, c) {
            if (c = c || 10,
            s = s || 0,
            s === 0)
                this.internalStep(o),
                this.time += o;
            else {
                var d = Math.floor((this.time + s) / o) - Math.floor(this.time / o);
                d = Math.min(d, c) || 1;
                for (var _ = performance.now(), b = 0; b !== d && (this.internalStep(o),
                !(performance.now() - _ > o * 1e3)); b++)
                    ;
                this.time += s;
                for (var k = this.time % o, j = k / o, $ = e, _e = this.bodies, et = 0; et !== _e.length; et++) {
                    var tt = _e[et];
                    tt.type !== i.Body.STATIC && tt.sleepState !== i.Body.SLEEPING ? (tt.position.vsub(tt.previousPosition, $),
                    $.scale(j, $),
                    tt.position.vadd($, tt.interpolatedPosition)) : (tt.interpolatedPosition.set(tt.position.x, tt.position.y, tt.position.z),
                    tt.interpolatedQuaternion.set(tt.quaternion.x, tt.quaternion.y, tt.quaternion.z, tt.quaternion.w))
                }
            }
        }
    }
    ,
    a.prototype.raycast = function(e, i) {
        return this._cannonRaycastResult.reset(),
        this.world.raycastClosest(e, i, {}, this._cannonRaycastResult),
        this._raycastResult.reset(e, i),
        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
    }
    ,
    a
}();
PhysicsEngine.DefaultPluginFactory = function() {
    return new CannonJSPlugin
}
;
var OimoJSPlugin = function() {
    function a(e, i, o) {
        e === void 0 && (e = !0),
        o === void 0 && (o = OIMO),
        this._useDeltaForWorldStep = e,
        this.name = "OimoJSPlugin",
        this._fixedTimeStep = 1 / 60,
        this._tmpImpostorsArray = [],
        this._tmpPositionVector = Vector3.Zero(),
        this.BJSOIMO = o,
        this.world = new this.BJSOIMO.World({
            iterations: i
        }),
        this.world.clear(),
        this._raycastResult = new PhysicsRaycastResult
    }
    return a.prototype.setGravity = function(e) {
        this.world.gravity.set(e.x, e.y, e.z)
    }
    ,
    a.prototype.setTimeStep = function(e) {
        this.world.timeStep = e
    }
    ,
    a.prototype.getTimeStep = function() {
        return this.world.timeStep
    }
    ,
    a.prototype.executeStep = function(e, i) {
        var o = this;
        i.forEach(function(_) {
            _.beforeStep()
        }),
        this.world.timeStep = this._useDeltaForWorldStep ? e : this._fixedTimeStep,
        this.world.step(),
        i.forEach(function(_) {
            _.afterStep(),
            o._tmpImpostorsArray[_.uniqueId] = _
        });
        for (var s = this.world.contacts; s !== null; ) {
            if (s.touching && !s.body1.sleeping && !s.body2.sleeping) {
                s = s.next;
                continue
            }
            var c = this._tmpImpostorsArray[+s.body1.name]
              , d = this._tmpImpostorsArray[+s.body2.name];
            if (!c || !d) {
                s = s.next;
                continue
            }
            c.onCollide({
                body: d.physicsBody,
                point: null
            }),
            d.onCollide({
                body: c.physicsBody,
                point: null
            }),
            s = s.next
        }
    }
    ,
    a.prototype.applyImpulse = function(e, i, o) {
        var s = e.physicsBody.mass;
        e.physicsBody.applyImpulse(o.scale(this.world.invScale), i.scale(this.world.invScale * s))
    }
    ,
    a.prototype.applyForce = function(e, i, o) {
        Logger$2.Warn("Oimo doesn't support applying force. Using impule instead."),
        this.applyImpulse(e, i, o)
    }
    ,
    a.prototype.generatePhysicsBody = function(e) {
        var i = this;
        if (e.parent) {
            e.physicsBody && (this.removePhysicsBody(e),
            e.forceUpdate());
            return
        }
        if (e.isBodyInitRequired()) {
            var o = {
                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
            }
              , s = [e]
              , c = function(b) {
                !b.getChildMeshes || b.getChildMeshes().forEach(function(k) {
                    k.physicsImpostor && s.push(k.physicsImpostor)
                })
            };
            c(e.object);
            var d = function(b) {
                return Math.max(b, PhysicsEngine.Epsilon)
            }
              , _ = new Quaternion;
            s.forEach(function(b) {
                if (!!b.object.rotationQuaternion) {
                    var k = b.object.rotationQuaternion;
                    _.copyFrom(k),
                    b.object.rotationQuaternion.set(0, 0, 0, 1),
                    b.object.computeWorldMatrix(!0);
                    var j = _.toEulerAngles()
                      , $ = b.getObjectExtendSize()
                      , _e = 57.29577951308232;
                    if (b === e) {
                        var et = e.getObjectCenter();
                        e.object.getAbsolutePivotPoint().subtractToRef(et, i._tmpPositionVector),
                        i._tmpPositionVector.divideInPlace(e.object.scaling),
                        o.pos.push(et.x),
                        o.pos.push(et.y),
                        o.pos.push(et.z),
                        o.posShape.push(0, 0, 0),
                        o.rotShape.push(0, 0, 0)
                    } else {
                        var tt = b.object.position.clone();
                        o.posShape.push(tt.x),
                        o.posShape.push(tt.y),
                        o.posShape.push(tt.z),
                        o.rotShape.push(j.x * _e, j.y * _e, j.z * _e)
                    }
                    switch (b.object.rotationQuaternion.copyFrom(_),
                    b.type) {
                    case PhysicsImpostor.ParticleImpostor:
                        Logger$2.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
                    case PhysicsImpostor.SphereImpostor:
                        var rt = $.x
                          , it = $.y
                          , nt = $.z
                          , ot = Math.max(d(rt), d(it), d(nt)) / 2;
                        o.type.push("sphere"),
                        o.size.push(ot),
                        o.size.push(ot),
                        o.size.push(ot);
                        break;
                    case PhysicsImpostor.CylinderImpostor:
                        var at = d($.x) / 2
                          , st = d($.y);
                        o.type.push("cylinder"),
                        o.size.push(at),
                        o.size.push(st),
                        o.size.push(st);
                        break;
                    case PhysicsImpostor.PlaneImpostor:
                    case PhysicsImpostor.BoxImpostor:
                    default:
                        var at = d($.x)
                          , st = d($.y)
                          , ut = d($.z);
                        o.type.push("box"),
                        o.size.push(at),
                        o.size.push(st),
                        o.size.push(ut);
                        break
                    }
                    b.object.rotationQuaternion = k
                }
            }),
            e.physicsBody = this.world.add(o),
            e.physicsBody.resetQuaternion(_),
            e.physicsBody.updatePosition(0)
        } else
            this._tmpPositionVector.copyFromFloats(0, 0, 0);
        e.setDeltaPosition(this._tmpPositionVector)
    }
    ,
    a.prototype.removePhysicsBody = function(e) {
        this.world.removeRigidBody(e.physicsBody)
    }
    ,
    a.prototype.generateJoint = function(e) {
        var i = e.mainImpostor.physicsBody
          , o = e.connectedImpostor.physicsBody;
        if (!(!i || !o)) {
            var s = e.joint.jointData, c = s.nativeParams || {}, d, _ = {
                body1: i,
                body2: o,
                axe1: c.axe1 || (s.mainAxis ? s.mainAxis.asArray() : null),
                axe2: c.axe2 || (s.connectedAxis ? s.connectedAxis.asArray() : null),
                pos1: c.pos1 || (s.mainPivot ? s.mainPivot.asArray() : null),
                pos2: c.pos2 || (s.connectedPivot ? s.connectedPivot.asArray() : null),
                min: c.min,
                max: c.max,
                collision: c.collision || s.collision,
                spring: c.spring,
                world: this.world
            };
            switch (e.joint.type) {
            case PhysicsJoint.BallAndSocketJoint:
                d = "jointBall";
                break;
            case PhysicsJoint.SpringJoint:
                Logger$2.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
                var b = s;
                _.min = b.length || _.min,
                _.max = Math.max(_.min, _.max);
            case PhysicsJoint.DistanceJoint:
                d = "jointDistance",
                _.max = s.maxDistance;
                break;
            case PhysicsJoint.PrismaticJoint:
                d = "jointPrisme";
                break;
            case PhysicsJoint.SliderJoint:
                d = "jointSlide";
                break;
            case PhysicsJoint.WheelJoint:
                d = "jointWheel";
                break;
            case PhysicsJoint.HingeJoint:
            default:
                d = "jointHinge";
                break
            }
            _.type = d,
            e.joint.physicsJoint = this.world.add(_)
        }
    }
    ,
    a.prototype.removeJoint = function(e) {
        try {
            this.world.removeJoint(e.joint.physicsJoint)
        } catch (i) {
            Logger$2.Warn(i)
        }
    }
    ,
    a.prototype.isSupported = function() {
        return this.BJSOIMO !== void 0
    }
    ,
    a.prototype.setTransformationFromPhysicsBody = function(e) {
        if (!e.physicsBody.sleeping) {
            if (e.physicsBody.shapes.next) {
                for (var i = e.physicsBody.shapes; i.next; )
                    i = i.next;
                e.object.position.set(i.position.x, i.position.y, i.position.z)
            } else {
                var o = e.physicsBody.getPosition();
                e.object.position.set(o.x, o.y, o.z)
            }
            if (e.object.rotationQuaternion) {
                var s = e.physicsBody.getQuaternion();
                e.object.rotationQuaternion.set(s.x, s.y, s.z, s.w)
            }
        }
    }
    ,
    a.prototype.setPhysicsBodyTransformation = function(e, i, o) {
        var s = e.physicsBody;
        e.physicsBody.shapes.next || (s.position.set(i.x, i.y, i.z),
        s.orientation.set(o.x, o.y, o.z, o.w),
        s.syncShapes(),
        s.awake())
    }
    ,
    a.prototype.setLinearVelocity = function(e, i) {
        e.physicsBody.linearVelocity.set(i.x, i.y, i.z)
    }
    ,
    a.prototype.setAngularVelocity = function(e, i) {
        e.physicsBody.angularVelocity.set(i.x, i.y, i.z)
    }
    ,
    a.prototype.getLinearVelocity = function(e) {
        var i = e.physicsBody.linearVelocity;
        return i ? new Vector3(i.x,i.y,i.z) : null
    }
    ,
    a.prototype.getAngularVelocity = function(e) {
        var i = e.physicsBody.angularVelocity;
        return i ? new Vector3(i.x,i.y,i.z) : null
    }
    ,
    a.prototype.setBodyMass = function(e, i) {
        var o = i === 0;
        e.physicsBody.shapes.density = o ? 1 : i,
        e.physicsBody.setupMass(o ? 2 : 1)
    }
    ,
    a.prototype.getBodyMass = function(e) {
        return e.physicsBody.shapes.density
    }
    ,
    a.prototype.getBodyFriction = function(e) {
        return e.physicsBody.shapes.friction
    }
    ,
    a.prototype.setBodyFriction = function(e, i) {
        e.physicsBody.shapes.friction = i
    }
    ,
    a.prototype.getBodyRestitution = function(e) {
        return e.physicsBody.shapes.restitution
    }
    ,
    a.prototype.setBodyRestitution = function(e, i) {
        e.physicsBody.shapes.restitution = i
    }
    ,
    a.prototype.sleepBody = function(e) {
        e.physicsBody.sleep()
    }
    ,
    a.prototype.wakeUpBody = function(e) {
        e.physicsBody.awake()
    }
    ,
    a.prototype.updateDistanceJoint = function(e, i, o) {
        e.physicsJoint.limitMotor.upperLimit = i,
        o !== void 0 && (e.physicsJoint.limitMotor.lowerLimit = o)
    }
    ,
    a.prototype.setMotor = function(e, i, o, s) {
        o !== void 0 ? Logger$2.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter") : o = 1e6,
        i *= -1;
        var c = s ? e.physicsJoint.rotationalLimitMotor2 : e.physicsJoint.rotationalLimitMotor1 || e.physicsJoint.rotationalLimitMotor || e.physicsJoint.limitMotor;
        c && c.setMotor(i, o)
    }
    ,
    a.prototype.setLimit = function(e, i, o, s) {
        var c = s ? e.physicsJoint.rotationalLimitMotor2 : e.physicsJoint.rotationalLimitMotor1 || e.physicsJoint.rotationalLimitMotor || e.physicsJoint.limitMotor;
        c && c.setLimit(i, o === void 0 ? -i : o)
    }
    ,
    a.prototype.syncMeshWithImpostor = function(e, i) {
        var o = i.physicsBody;
        e.position.x = o.position.x,
        e.position.y = o.position.y,
        e.position.z = o.position.z,
        e.rotationQuaternion && (e.rotationQuaternion.x = o.orientation.x,
        e.rotationQuaternion.y = o.orientation.y,
        e.rotationQuaternion.z = o.orientation.z,
        e.rotationQuaternion.w = o.orientation.s)
    }
    ,
    a.prototype.getRadius = function(e) {
        return e.physicsBody.shapes.radius
    }
    ,
    a.prototype.getBoxSizeToRef = function(e, i) {
        var o = e.physicsBody.shapes;
        i.x = o.halfWidth * 2,
        i.y = o.halfHeight * 2,
        i.z = o.halfDepth * 2
    }
    ,
    a.prototype.dispose = function() {
        this.world.clear()
    }
    ,
    a.prototype.raycast = function(e, i) {
        return Logger$2.Warn("raycast is not currently supported by the Oimo physics plugin"),
        this._raycastResult.reset(e, i),
        this._raycastResult
    }
    ,
    a
}()
  , AmmoJSPlugin = function() {
    function a(e, i, o) {
        var s = this;
        if (e === void 0 && (e = !0),
        i === void 0 && (i = Ammo),
        o === void 0 && (o = 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 i == "function") {
            Logger$2.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");
            return
        } else
            this.bjsAMMO = i;
        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 = o || 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(c, d, _, b) {
            c = s.bjsAMMO.wrapPointer(c, s.bjsAMMO.btManifoldPoint);
            var k = c.getPositionWorldOnA();
            s._tmpContactPoint.x = k.x(),
            s._tmpContactPoint.y = k.y(),
            s._tmpContactPoint.z = k.z(),
            s._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 a.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)
    }
    ,
    a.prototype.setTimeStep = function(e) {
        this._timeStep = e
    }
    ,
    a.prototype.setFixedTimeStep = function(e) {
        this._fixedTimeStep = e
    }
    ,
    a.prototype.setMaxSteps = function(e) {
        this._maxSteps = e
    }
    ,
    a.prototype.getTimeStep = function() {
        return this._timeStep
    }
    ,
    a.prototype._isImpostorInContact = function(e) {
        return this._tmpContactCallbackResult = !1,
        this.world.contactTest(e.physicsBody, this._tmpAmmoConcreteContactResultCallback),
        this._tmpContactCallbackResult
    }
    ,
    a.prototype._isImpostorPairInContact = function(e, i) {
        return this._tmpContactCallbackResult = !1,
        this.world.contactPairTest(e.physicsBody, i.physicsBody, this._tmpAmmoConcreteContactResultCallback),
        this._tmpContactCallbackResult
    }
    ,
    a.prototype._stepSimulation = function(e, i, o) {
        if (e === void 0 && (e = 1 / 60),
        i === void 0 && (i = 10),
        o === void 0 && (o = 1 / 60),
        i == 0)
            this.world.stepSimulation(e, 0);
        else
            for (; i > 0 && e > 0; )
                e - o < o ? (this.world.stepSimulation(e, 0),
                e = 0) : (e -= o,
                this.world.stepSimulation(o, 0)),
                i--
    }
    ,
    a.prototype.executeStep = function(e, i) {
        for (var o = 0, s = i; o < s.length; o++) {
            var c = s[o];
            c.soft || c.beforeStep()
        }
        this._stepSimulation(this._useDeltaForWorldStep ? e : this._timeStep, this._maxSteps, this._fixedTimeStep);
        for (var d = 0, _ = i; d < _.length; d++) {
            var b = _[d];
            if (b.soft ? this._afterSoftStep(b) : b.afterStep(),
            b._onPhysicsCollideCallbacks.length > 0 && this._isImpostorInContact(b))
                for (var k = 0, j = b._onPhysicsCollideCallbacks; k < j.length; k++)
                    for (var $ = j[k], _e = 0, et = $.otherImpostors; _e < et.length; _e++) {
                        var tt = et[_e];
                        (b.physicsBody.isActive() || tt.physicsBody.isActive()) && this._isImpostorPairInContact(b, tt) && (b.onCollide({
                            body: tt.physicsBody,
                            point: this._tmpContactPoint
                        }),
                        tt.onCollide({
                            body: b.physicsBody,
                            point: this._tmpContactPoint
                        }))
                    }
        }
    }
    ,
    a.prototype._afterSoftStep = function(e) {
        e.type === PhysicsImpostor.RopeImpostor ? this._ropeStep(e) : this._softbodyOrClothStep(e)
    }
    ,
    a.prototype._ropeStep = function(e) {
        for (var i = e.physicsBody.get_m_nodes(), o = i.size(), s, c, d, _, b, k = new Array, j = 0; j < o; j++)
            s = i.at(j),
            c = s.get_m_x(),
            d = c.x(),
            _ = c.y(),
            b = c.z(),
            k.push(new Vector3(d,_,b));
        var $ = e.object
          , _e = e.getParam("shape");
        e._isFromLine ? e.object = CreateLines("lines", {
            points: k,
            instance: $
        }) : e.object = ExtrudeShape("ext", {
            shape: _e,
            path: k,
            instance: $
        })
    }
    ,
    a.prototype._softbodyOrClothStep = function(e) {
        var i = e.type === PhysicsImpostor.ClothImpostor ? 1 : -1
          , o = e.object
          , s = o.getVerticesData(VertexBuffer.PositionKind);
        s || (s = []);
        var c = o.getVerticesData(VertexBuffer.NormalKind);
        c || (c = []);
        for (var d = s.length / 3, _ = e.physicsBody.get_m_nodes(), b, k, j, $, _e, et, tt, rt, it, nt = 0; nt < d; nt++) {
            b = _.at(nt),
            k = b.get_m_x(),
            $ = k.x(),
            _e = k.y(),
            et = k.z() * i;
            var j = b.get_m_n();
            tt = j.x(),
            rt = j.y(),
            it = j.z() * i,
            s[3 * nt] = $,
            s[3 * nt + 1] = _e,
            s[3 * nt + 2] = et,
            c[3 * nt] = tt,
            c[3 * nt + 1] = rt,
            c[3 * nt + 2] = it
        }
        var ot = new VertexData;
        ot.positions = s,
        ot.normals = c,
        ot.uvs = o.getVerticesData(VertexBuffer.UVKind),
        ot.colors = o.getVerticesData(VertexBuffer.ColorKind),
        o && o.getIndices && (ot.indices = o.getIndices()),
        ot.applyToMesh(o)
    }
    ,
    a.prototype.applyImpulse = function(e, i, o) {
        if (e.soft)
            Logger$2.Warn("Cannot be applied to a soft body");
        else {
            e.physicsBody.activate();
            var s = this._tmpAmmoVectorA
              , c = this._tmpAmmoVectorB;
            e.object && e.object.getWorldMatrix && o.subtractInPlace(e.object.getWorldMatrix().getTranslation()),
            s.setValue(o.x, o.y, o.z),
            c.setValue(i.x, i.y, i.z),
            e.physicsBody.applyImpulse(c, s)
        }
    }
    ,
    a.prototype.applyForce = function(e, i, o) {
        if (e.soft)
            Logger$2.Warn("Cannot be applied to a soft body");
        else {
            e.physicsBody.activate();
            var s = this._tmpAmmoVectorA
              , c = this._tmpAmmoVectorB;
            if (s.setValue(o.x, o.y, o.z),
            e.object && e.object.getWorldMatrix) {
                var d = e.object.getWorldMatrix().getTranslation();
                s.x -= d.x,
                s.y -= d.y,
                s.z -= d.z
            }
            c.setValue(i.x, i.y, i.z),
            e.physicsBody.applyForce(c, s)
        }
    }
    ,
    a.prototype.generatePhysicsBody = function(e) {
        if (e._pluginData.toDispose = [],
        e.parent) {
            e.physicsBody && (this.removePhysicsBody(e),
            e.forceUpdate());
            return
        }
        if (e.isBodyInitRequired()) {
            var i = this._createShape(e)
              , o = e.getParam("mass");
            if (e._pluginData.mass = o,
            e.soft)
                i.get_m_cfg().set_collisions(17),
                i.get_m_cfg().set_kDP(e.getParam("damping")),
                this.bjsAMMO.castObject(i, this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(e.getParam("margin")),
                i.setActivationState(a.DISABLE_DEACTIVATION_FLAG),
                this.world.addSoftBody(i, 1, -1),
                e.physicsBody = i,
                e._pluginData.toDispose.push(i),
                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 s = new this.bjsAMMO.btVector3(0,0,0)
                  , c = new this.bjsAMMO.btTransform;
                e.object.computeWorldMatrix(!0),
                c.setIdentity(),
                o !== 0 && i.calculateLocalInertia(o, s),
                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),
                c.setOrigin(this._tmpAmmoVectorA),
                c.setRotation(this._tmpAmmoQuaternion);
                var d = new this.bjsAMMO.btDefaultMotionState(c)
                  , _ = new this.bjsAMMO.btRigidBodyConstructionInfo(o,d,i,s)
                  , b = new this.bjsAMMO.btRigidBody(_);
                if (o === 0 && (b.setCollisionFlags(b.getCollisionFlags() | a.KINEMATIC_FLAG),
                b.setActivationState(a.DISABLE_DEACTIVATION_FLAG)),
                e.type == PhysicsImpostor.NoImpostor && !i.getChildShape && b.setCollisionFlags(b.getCollisionFlags() | a.DISABLE_COLLISION_FLAG),
                e.type !== PhysicsImpostor.MeshImpostor && e.type !== PhysicsImpostor.NoImpostor) {
                    var k = e.object.getBoundingInfo();
                    this._tmpVec3.copyFrom(e.object.getAbsolutePosition()),
                    this._tmpVec3.subtractInPlace(k.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 j = e.getParam("group")
                  , $ = e.getParam("mask");
                j && $ ? this.world.addRigidBody(b, j, $) : this.world.addRigidBody(b),
                e.physicsBody = b,
                e._pluginData.toDispose = e._pluginData.toDispose.concat([b, _, d, c, s, i])
            }
            this.setBodyRestitution(e, e.getParam("restitution")),
            this.setBodyFriction(e, e.getParam("friction"))
        }
    }
    ,
    a.prototype.removePhysicsBody = function(e) {
        var i = this;
        this.world && (e.soft ? this.world.removeSoftBody(e.physicsBody) : this.world.removeRigidBody(e.physicsBody),
        e._pluginData && (e._pluginData.toDispose.forEach(function(o) {
            i.bjsAMMO.destroy(o)
        }),
        e._pluginData.toDispose = []))
    }
    ,
    a.prototype.generateJoint = function(e) {
        var i = e.mainImpostor.physicsBody
          , o = e.connectedImpostor.physicsBody;
        if (!(!i || !o)) {
            var s = e.joint.jointData;
            s.mainPivot || (s.mainPivot = new Vector3(0,0,0)),
            s.connectedPivot || (s.connectedPivot = new Vector3(0,0,0));
            var c;
            switch (e.joint.type) {
            case PhysicsJoint.DistanceJoint:
                var d = s.maxDistance;
                d && (s.mainPivot = new Vector3(0,-d / 2,0),
                s.connectedPivot = new Vector3(0,d / 2,0)),
                c = new this.bjsAMMO.btPoint2PointConstraint(i,o,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));
                break;
            case PhysicsJoint.HingeJoint:
                s.mainAxis || (s.mainAxis = new Vector3(0,0,0)),
                s.connectedAxis || (s.connectedAxis = new Vector3(0,0,0));
                var _ = new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z)
                  , b = new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);
                c = new this.bjsAMMO.btHingeConstraint(i,o,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),_,b);
                break;
            case PhysicsJoint.BallAndSocketJoint:
                c = new this.bjsAMMO.btPoint2PointConstraint(i,o,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));
                break;
            default:
                Logger$2.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),
                c = new this.bjsAMMO.btPoint2PointConstraint(i,o,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));
                break
            }
            this.world.addConstraint(c, !e.joint.jointData.collision),
            e.joint.physicsJoint = c
        }
    }
    ,
    a.prototype.removeJoint = function(e) {
        this.world && this.world.removeConstraint(e.joint.physicsJoint)
    }
    ,
    a.prototype._addMeshVerts = function(e, i, o) {
        var s = this
          , c = 0;
        if (o && o.getIndices && o.getWorldMatrix && o.getChildMeshes) {
            var d = o.getIndices();
            d || (d = []);
            var _ = o.getVerticesData(VertexBuffer.PositionKind);
            _ || (_ = []);
            var b = void 0;
            if (i && i !== o) {
                var k = void 0;
                i.rotationQuaternion ? k = i.rotationQuaternion : i.rotation ? k = Quaternion.FromEulerAngles(i.rotation.x, i.rotation.y, i.rotation.z) : k = Quaternion.Identity();
                var j = Matrix.Compose(Vector3.One(), k, i.position);
                j.invertToRef(this._tmpMatrix);
                var $ = o.computeWorldMatrix(!1);
                b = $.multiply(this._tmpMatrix)
            } else
                Matrix.ScalingToRef(o.scaling.x, o.scaling.y, o.scaling.z, this._tmpMatrix),
                b = this._tmpMatrix;
            for (var _e = d.length / 3, et = 0; et < _e; et++) {
                for (var tt = [], rt = 0; rt < 3; rt++) {
                    var it = new Vector3(_[d[et * 3 + rt] * 3 + 0],_[d[et * 3 + rt] * 3 + 1],_[d[et * 3 + rt] * 3 + 2]);
                    it = Vector3.TransformCoordinates(it, b);
                    var nt;
                    rt == 0 ? nt = this._tmpAmmoVectorA : rt == 1 ? nt = this._tmpAmmoVectorB : nt = this._tmpAmmoVectorC,
                    nt.setValue(it.x, it.y, it.z),
                    tt.push(nt)
                }
                e.addTriangle(tt[0], tt[1], tt[2]),
                c++
            }
            o.getChildMeshes().forEach(function(ot) {
                c += s._addMeshVerts(e, i, ot)
            })
        }
        return c
    }
    ,
    a.prototype._softVertexData = function(e) {
        var i = e.object;
        if (i && i.getIndices && i.getWorldMatrix && i.getChildMeshes) {
            i.getIndices();
            var o = i.getVerticesData(VertexBuffer.PositionKind);
            o || (o = []);
            var s = i.getVerticesData(VertexBuffer.NormalKind);
            s || (s = []),
            i.computeWorldMatrix(!1);
            for (var c = [], d = [], _ = 0; _ < o.length; _ += 3) {
                var b = new Vector3(o[_],o[_ + 1],o[_ + 2])
                  , k = new Vector3(s[_],s[_ + 1],s[_ + 2]);
                b = Vector3.TransformCoordinates(b, i.getWorldMatrix()),
                k = Vector3.TransformNormal(k, i.getWorldMatrix()),
                c.push(b.x, b.y, b.z),
                d.push(k.x, k.y, k.z)
            }
            var j = new VertexData;
            return j.positions = c,
            j.normals = d,
            j.uvs = i.getVerticesData(VertexBuffer.UVKind),
            j.colors = i.getVerticesData(VertexBuffer.ColorKind),
            i && i.getIndices && (j.indices = i.getIndices()),
            j.applyToMesh(i),
            i.position = Vector3.Zero(),
            i.rotationQuaternion = null,
            i.rotation = Vector3.Zero(),
            i.computeWorldMatrix(!0),
            j
        }
        return VertexData.ExtractFromMesh(i)
    }
    ,
    a.prototype._createSoftbody = function(e) {
        var i = e.object;
        if (i && i.getIndices) {
            var o = i.getIndices();
            o || (o = []);
            var s = this._softVertexData(e)
              , c = s.positions
              , d = s.normals;
            if (c === null || d === null)
                return new this.bjsAMMO.btCompoundShape;
            for (var _ = [], b = [], k = 0; k < c.length; k += 3) {
                var j = new Vector3(c[k],c[k + 1],c[k + 2])
                  , $ = new Vector3(d[k],d[k + 1],d[k + 2]);
                _.push(j.x, j.y, -j.z),
                b.push($.x, $.y, -$.z)
            }
            for (var _e = new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(), _, i.getIndices(), o.length / 3, !0), et = c.length / 3, tt = _e.get_m_nodes(), rt, it, k = 0; k < et; k++) {
                rt = tt.at(k);
                var it = rt.get_m_n();
                it.setX(b[3 * k]),
                it.setY(b[3 * k + 1]),
                it.setZ(b[3 * k + 2])
            }
            return _e
        }
    }
    ,
    a.prototype._createCloth = function(e) {
        var i = e.object;
        if (i && i.getIndices) {
            i.getIndices();
            var o = this._softVertexData(e)
              , s = o.positions
              , c = o.normals;
            if (s === null || c === null)
                return new this.bjsAMMO.btCompoundShape;
            var d = s.length
              , _ = Math.sqrt(d / 3);
            e.segments = _;
            var b = _ - 1;
            this._tmpAmmoVectorA.setValue(s[0], s[1], s[2]),
            this._tmpAmmoVectorB.setValue(s[3 * b], s[3 * b + 1], s[3 * b + 2]),
            this._tmpAmmoVectorD.setValue(s[d - 3], s[d - 2], s[d - 1]),
            this._tmpAmmoVectorC.setValue(s[d - 3 - 3 * b], s[d - 2 - 3 * b], s[d - 1 - 3 * b]);
            var k = new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, this._tmpAmmoVectorC, this._tmpAmmoVectorD, _, _, e.getParam("fixedPoints"), !0);
            return k
        }
    }
    ,
    a.prototype._createRope = function(e) {
        var i, o, s = this._softVertexData(e), c = s.positions, d = s.normals;
        if (c === null || d === null)
            return new this.bjsAMMO.btCompoundShape;
        s.applyToMesh(e.object, !0),
        e._isFromLine = !0;
        var _ = d.map(function(tt) {
            return tt * tt
        })
          , b = function(tt, rt) {
            return tt + rt
        }
          , k = _.reduce(b);
        if (k === 0)
            i = c.length,
            o = i / 3 - 1,
            this._tmpAmmoVectorA.setValue(c[0], c[1], c[2]),
            this._tmpAmmoVectorB.setValue(c[i - 3], c[i - 2], c[i - 1]);
        else {
            e._isFromLine = !1;
            var j = e.getParam("path")
              , $ = e.getParam("shape");
            if ($ === null)
                return Logger$2.Warn("No shape available for extruded mesh"),
                new this.bjsAMMO.btCompoundShape;
            i = j.length,
            o = i - 1,
            this._tmpAmmoVectorA.setValue(j[0].x, j[0].y, j[0].z),
            this._tmpAmmoVectorB.setValue(j[i - 1].x, j[i - 1].y, j[i - 1].z)
        }
        e.segments = o;
        var _e = e.getParam("fixedPoints");
        _e = _e > 3 ? 3 : _e;
        var et = new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, o - 1, _e);
        return et.get_m_cfg().set_collisions(17),
        et
    }
    ,
    a.prototype._createCustom = function(e) {
        var i = null;
        return this.onCreateCustomShape && (i = this.onCreateCustomShape(e)),
        i == null && (i = new this.bjsAMMO.btCompoundShape),
        i
    }
    ,
    a.prototype._addHullVerts = function(e, i, o) {
        var s = this
          , c = 0;
        if (o && o.getIndices && o.getWorldMatrix && o.getChildMeshes) {
            var d = o.getIndices();
            d || (d = []);
            var _ = o.getVerticesData(VertexBuffer.PositionKind);
            _ || (_ = []),
            o.computeWorldMatrix(!1);
            for (var b = d.length / 3, k = 0; k < b; k++) {
                for (var j = [], $ = 0; $ < 3; $++) {
                    var _e = new Vector3(_[d[k * 3 + $] * 3 + 0],_[d[k * 3 + $] * 3 + 1],_[d[k * 3 + $] * 3 + 2]);
                    Matrix.ScalingToRef(o.scaling.x, o.scaling.y, o.scaling.z, this._tmpMatrix),
                    _e = Vector3.TransformCoordinates(_e, this._tmpMatrix);
                    var et;
                    $ == 0 ? et = this._tmpAmmoVectorA : $ == 1 ? et = this._tmpAmmoVectorB : et = this._tmpAmmoVectorC,
                    et.setValue(_e.x, _e.y, _e.z),
                    j.push(et)
                }
                e.addPoint(j[0], !0),
                e.addPoint(j[1], !0),
                e.addPoint(j[2], !0),
                c++
            }
            o.getChildMeshes().forEach(function(tt) {
                c += s._addHullVerts(e, i, tt)
            })
        }
        return c
    }
    ,
    a.prototype._createShape = function(e, i) {
        var o = this;
        i === void 0 && (i = !1);
        var s = e.object, c, d = e.getObjectExtendSize();
        if (!i) {
            var _ = e.object.getChildMeshes ? e.object.getChildMeshes(!0) : [];
            c = new this.bjsAMMO.btCompoundShape;
            var b = 0;
            if (_.forEach(function(it) {
                var nt = it.getPhysicsImpostor();
                if (nt) {
                    if (nt.type == PhysicsImpostor.MeshImpostor)
                        throw "A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";
                    var ot = o._createShape(nt)
                      , at = it.parent.getWorldMatrix().clone()
                      , st = new Vector3;
                    at.decompose(st),
                    o._tmpAmmoTransform.getOrigin().setValue(it.position.x * st.x, it.position.y * st.y, it.position.z * st.z),
                    o._tmpAmmoQuaternion.setValue(it.rotationQuaternion.x, it.rotationQuaternion.y, it.rotationQuaternion.z, it.rotationQuaternion.w),
                    o._tmpAmmoTransform.setRotation(o._tmpAmmoQuaternion),
                    c.addChildShape(o._tmpAmmoTransform, ot),
                    nt.dispose(),
                    b++
                }
            }),
            b > 0) {
                if (e.type != PhysicsImpostor.NoImpostor) {
                    var k = this._createShape(e, !0);
                    k && (this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0),
                    this._tmpAmmoQuaternion.setValue(0, 0, 0, 1),
                    this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),
                    c.addChildShape(this._tmpAmmoTransform, k))
                }
                return c
            } else
                this.bjsAMMO.destroy(c),
                c = null
        }
        switch (e.type) {
        case PhysicsImpostor.SphereImpostor:
            if (Scalar.WithinEpsilon(d.x, d.y, 1e-4) && Scalar.WithinEpsilon(d.x, d.z, 1e-4))
                c = new this.bjsAMMO.btSphereShape(d.x / 2);
            else {
                var j = [new this.bjsAMMO.btVector3(0,0,0)]
                  , $ = [1];
                c = new this.bjsAMMO.btMultiSphereShape(j,$,1),
                c.setLocalScaling(new this.bjsAMMO.btVector3(d.x / 2,d.y / 2,d.z / 2))
            }
            break;
        case PhysicsImpostor.CapsuleImpostor:
            var _e = d.x / 2;
            c = new this.bjsAMMO.btCapsuleShape(_e,d.y - _e * 2);
            break;
        case PhysicsImpostor.CylinderImpostor:
            this._tmpAmmoVectorA.setValue(d.x / 2, d.y / 2, d.z / 2),
            c = new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);
            break;
        case PhysicsImpostor.PlaneImpostor:
        case PhysicsImpostor.BoxImpostor:
            this._tmpAmmoVectorA.setValue(d.x / 2, d.y / 2, d.z / 2),
            c = new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);
            break;
        case PhysicsImpostor.MeshImpostor:
            if (e.getParam("mass") == 0) {
                var et = new this.bjsAMMO.btTriangleMesh;
                e._pluginData.toDispose.push(et);
                var rt = this._addMeshVerts(et, s, s);
                rt == 0 ? c = new this.bjsAMMO.btCompoundShape : c = new this.bjsAMMO.btBvhTriangleMeshShape(et);
                break
            }
        case PhysicsImpostor.ConvexHullImpostor:
            var tt = new this.bjsAMMO.btConvexHullShape
              , rt = this._addHullVerts(tt, s, s);
            rt == 0 ? (e._pluginData.toDispose.push(tt),
            c = new this.bjsAMMO.btCompoundShape) : c = tt;
            break;
        case PhysicsImpostor.NoImpostor:
            c = new this.bjsAMMO.btSphereShape(d.x / 2);
            break;
        case PhysicsImpostor.CustomImpostor:
            c = this._createCustom(e);
            break;
        case PhysicsImpostor.SoftbodyImpostor:
            c = this._createSoftbody(e);
            break;
        case PhysicsImpostor.ClothImpostor:
            c = this._createCloth(e);
            break;
        case PhysicsImpostor.RopeImpostor:
            c = this._createRope(e);
            break;
        default:
            Logger$2.Warn("The impostor type is not currently supported by the ammo plugin.");
            break
        }
        return c
    }
    ,
    a.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))
    }
    ,
    a.prototype.setPhysicsBodyTransformation = function(e, i, o) {
        var s = e.physicsBody.getWorldTransform();
        if (Math.abs(s.getOrigin().x() - i.x) > Epsilon || Math.abs(s.getOrigin().y() - i.y) > Epsilon || Math.abs(s.getOrigin().z() - i.z) > Epsilon || Math.abs(s.getRotation().x() - o.x) > Epsilon || Math.abs(s.getRotation().y() - o.y) > Epsilon || Math.abs(s.getRotation().z() - o.z) > Epsilon || Math.abs(s.getRotation().w() - o.w) > Epsilon)
            if (this._tmpAmmoVectorA.setValue(i.x, i.y, i.z),
            s.setOrigin(this._tmpAmmoVectorA),
            this._tmpAmmoQuaternion.setValue(o.x, o.y, o.z, o.w),
            s.setRotation(this._tmpAmmoQuaternion),
            e.physicsBody.setWorldTransform(s),
            e.mass == 0) {
                var c = e.physicsBody.getMotionState();
                c && c.setWorldTransform(s)
            } else
                e.physicsBody.activate()
    }
    ,
    a.prototype.isSupported = function() {
        return this.bjsAMMO !== void 0
    }
    ,
    a.prototype.setLinearVelocity = function(e, i) {
        this._tmpAmmoVectorA.setValue(i.x, i.y, i.z),
        e.soft ? e.physicsBody.linearVelocity(this._tmpAmmoVectorA) : e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)
    }
    ,
    a.prototype.setAngularVelocity = function(e, i) {
        this._tmpAmmoVectorA.setValue(i.x, i.y, i.z),
        e.soft ? e.physicsBody.angularVelocity(this._tmpAmmoVectorA) : e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)
    }
    ,
    a.prototype.getLinearVelocity = function(e) {
        if (e.soft)
            var i = e.physicsBody.linearVelocity();
        else
            var i = e.physicsBody.getLinearVelocity();
        if (!i)
            return null;
        var o = new Vector3(i.x(),i.y(),i.z());
        return this.bjsAMMO.destroy(i),
        o
    }
    ,
    a.prototype.getAngularVelocity = function(e) {
        if (e.soft)
            var i = e.physicsBody.angularVelocity();
        else
            var i = e.physicsBody.getAngularVelocity();
        if (!i)
            return null;
        var o = new Vector3(i.x(),i.y(),i.z());
        return this.bjsAMMO.destroy(i),
        o
    }
    ,
    a.prototype.setBodyMass = function(e, i) {
        e.soft ? e.physicsBody.setTotalMass(i, !1) : e.physicsBody.setMassProps(i),
        e._pluginData.mass = i
    }
    ,
    a.prototype.getBodyMass = function(e) {
        return e._pluginData.mass || 0
    }
    ,
    a.prototype.getBodyFriction = function(e) {
        return e._pluginData.friction || 0
    }
    ,
    a.prototype.setBodyFriction = function(e, i) {
        e.soft ? e.physicsBody.get_m_cfg().set_kDF(i) : e.physicsBody.setFriction(i),
        e._pluginData.friction = i
    }
    ,
    a.prototype.getBodyRestitution = function(e) {
        return e._pluginData.restitution || 0
    }
    ,
    a.prototype.setBodyRestitution = function(e, i) {
        e.physicsBody.setRestitution(i),
        e._pluginData.restitution = i
    }
    ,
    a.prototype.getBodyPressure = function(e) {
        return e.soft ? e._pluginData.pressure || 0 : (Logger$2.Warn("Pressure is not a property of a rigid body"),
        0)
    }
    ,
    a.prototype.setBodyPressure = function(e, i) {
        e.soft ? e.type === PhysicsImpostor.SoftbodyImpostor ? (e.physicsBody.get_m_cfg().set_kPR(i),
        e._pluginData.pressure = i) : (e.physicsBody.get_m_cfg().set_kPR(0),
        e._pluginData.pressure = 0) : Logger$2.Warn("Pressure can only be applied to a softbody")
    }
    ,
    a.prototype.getBodyStiffness = function(e) {
        return e.soft ? e._pluginData.stiffness || 0 : (Logger$2.Warn("Stiffness is not a property of a rigid body"),
        0)
    }
    ,
    a.prototype.setBodyStiffness = function(e, i) {
        e.soft ? (i = i < 0 ? 0 : i,
        i = i > 1 ? 1 : i,
        e.physicsBody.get_m_materials().at(0).set_m_kLST(i),
        e._pluginData.stiffness = i) : Logger$2.Warn("Stiffness cannot be applied to a rigid body")
    }
    ,
    a.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)
    }
    ,
    a.prototype.setBodyVelocityIterations = function(e, i) {
        e.soft ? (i = i < 0 ? 0 : i,
        e.physicsBody.get_m_cfg().set_viterations(i),
        e._pluginData.velocityIterations = i) : Logger$2.Warn("Velocity iterations cannot be applied to a rigid body")
    }
    ,
    a.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)
    }
    ,
    a.prototype.setBodyPositionIterations = function(e, i) {
        e.soft ? (i = i < 0 ? 0 : i,
        e.physicsBody.get_m_cfg().set_piterations(i),
        e._pluginData.positionIterations = i) : Logger$2.Warn("Position iterations cannot be applied to a rigid body")
    }
    ,
    a.prototype.appendAnchor = function(e, i, o, s, c, d) {
        c === void 0 && (c = 1),
        d === void 0 && (d = !1);
        var _ = e.segments
          , b = Math.round((_ - 1) * o)
          , k = Math.round((_ - 1) * s)
          , j = _ - 1 - k
          , $ = b + _ * j;
        e.physicsBody.appendAnchor($, i.physicsBody, d, c)
    }
    ,
    a.prototype.appendHook = function(e, i, o, s, c) {
        s === void 0 && (s = 1),
        c === void 0 && (c = !1);
        var d = Math.round(e.segments * o);
        e.physicsBody.appendAnchor(d, i.physicsBody, c, s)
    }
    ,
    a.prototype.sleepBody = function(e) {
        e.physicsBody.forceActivationState(0)
    }
    ,
    a.prototype.wakeUpBody = function(e) {
        e.physicsBody.activate()
    }
    ,
    a.prototype.updateDistanceJoint = function(e, i, o) {
        Logger$2.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")
    }
    ,
    a.prototype.setMotor = function(e, i, o, s) {
        e.physicsJoint.enableAngularMotor(!0, i, o)
    }
    ,
    a.prototype.setLimit = function(e, i, o) {
        Logger$2.Warn("setLimit is not currently supported by the Ammo physics plugin")
    }
    ,
    a.prototype.syncMeshWithImpostor = function(e, i) {
        var o = i.physicsBody;
        o.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())
    }
    ,
    a.prototype.getRadius = function(e) {
        var i = e.getObjectExtendSize();
        return i.x / 2
    }
    ,
    a.prototype.getBoxSizeToRef = function(e, i) {
        var o = e.getObjectExtendSize();
        i.x = o.x,
        i.y = o.y,
        i.z = o.z
    }
    ,
    a.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
    }
    ,
    a.prototype.raycast = function(e, i) {
        this._tmpAmmoVectorRCA = new this.bjsAMMO.btVector3(e.x,e.y,e.z),
        this._tmpAmmoVectorRCB = new this.bjsAMMO.btVector3(i.x,i.y,i.z);
        var o = new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);
        return this.world.rayTest(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB, o),
        this._raycastResult.reset(e, i),
        o.hasHit() && (this._raycastResult.setHitData({
            x: o.get_m_hitNormalWorld().x(),
            y: o.get_m_hitNormalWorld().y(),
            z: o.get_m_hitNormalWorld().z()
        }, {
            x: o.get_m_hitPointWorld().x(),
            y: o.get_m_hitPointWorld().y(),
            z: o.get_m_hitPointWorld().z()
        }),
        this._raycastResult.calculateHitDistance()),
        this.bjsAMMO.destroy(o),
        this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),
        this.bjsAMMO.destroy(this._tmpAmmoVectorRCB),
        this._raycastResult
    }
    ,
    a.DISABLE_COLLISION_FLAG = 4,
    a.KINEMATIC_FLAG = 2,
    a.DISABLE_DEACTIVATION_FLAG = 4,
    a
}();
AbstractScene.prototype.removeReflectionProbe = function(a) {
    if (!this.reflectionProbes)
        return -1;
    var e = this.reflectionProbes.indexOf(a);
    return e !== -1 && this.reflectionProbes.splice(e, 1),
    e
}
;
AbstractScene.prototype.addReflectionProbe = function(a) {
    this.reflectionProbes || (this.reflectionProbes = []),
    this.reflectionProbes.push(a)
}
;
var ReflectionProbe = function() {
    function a(e, i, o, s, c, d) {
        var _ = this;
        if (s === void 0 && (s = !0),
        c === void 0 && (c = !1),
        d === void 0 && (d = !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 = o,
        o.getEngine().supportsUniformBuffers) {
            this._sceneUBOs = [];
            for (var b = 0; b < 6; ++b)
                this._sceneUBOs.push(o.createSceneUniformBuffer('Scene for Reflection Probe (name "' + e + '") face #' + b))
        }
        this._scene.reflectionProbes || (this._scene.reflectionProbes = new Array),
        this._scene.reflectionProbes.push(this);
        var k = 0;
        if (c) {
            var j = this._scene.getEngine().getCaps();
            j.textureHalfFloatRender ? k = 2 : j.textureFloatRender && (k = 1)
        }
        this._renderTargetTexture = new RenderTargetTexture(e,i,o,s,!0,k,!0),
        this._renderTargetTexture.gammaSpace = !d;
        var $ = o.getEngine().useReverseDepthBuffer;
        this._renderTargetTexture.onBeforeRenderObservable.add(function(et) {
            switch (_._sceneUBOs && (o.setSceneUniformBuffer(_._sceneUBOs[et]),
            o.getSceneUniformBuffer().unbindEffect()),
            et) {
            case 0:
                _._add.copyFromFloats(1, 0, 0);
                break;
            case 1:
                _._add.copyFromFloats(-1, 0, 0);
                break;
            case 2:
                _._add.copyFromFloats(0, _._invertYAxis ? 1 : -1, 0);
                break;
            case 3:
                _._add.copyFromFloats(0, _._invertYAxis ? -1 : 1, 0);
                break;
            case 4:
                _._add.copyFromFloats(0, 0, o.useRightHandedSystem ? -1 : 1);
                break;
            case 5:
                _._add.copyFromFloats(0, 0, o.useRightHandedSystem ? 1 : -1);
                break
            }
            _._attachedMesh && _.position.copyFrom(_._attachedMesh.getAbsolutePosition()),
            _.position.addToRef(_._add, _._target);
            var tt = o.useRightHandedSystem ? Matrix.LookAtRHToRef : Matrix.LookAtLHToRef
              , rt = o.useRightHandedSystem ? Matrix.PerspectiveFovRH : Matrix.PerspectiveFovLH;
            tt(_.position, _._target, Vector3.Up(), _._viewMatrix),
            o.activeCamera && (_._projectionMatrix = rt(Math.PI / 2, 1, $ ? o.activeCamera.maxZ : o.activeCamera.minZ, $ ? o.activeCamera.minZ : o.activeCamera.maxZ, _._scene.getEngine().isNDCHalfZRange),
            o.setTransformMatrix(_._viewMatrix, _._projectionMatrix),
            o.activeCamera.isRigCamera && !_._renderTargetTexture.activeCamera && (_._renderTargetTexture.activeCamera = o.activeCamera.rigParent || null)),
            o._forcedViewPosition = _.position
        });
        var _e;
        this._renderTargetTexture.onBeforeBindObservable.add(function() {
            var et, tt;
            _._currentSceneUBO = o.getSceneUniformBuffer(),
            (tt = (et = o.getEngine())._debugPushGroup) === null || tt === void 0 || tt.call(et, "reflection probe generation for " + e, 1),
            _e = _._scene.imageProcessingConfiguration.applyByPostProcess,
            d && (o.imageProcessingConfiguration.applyByPostProcess = !0)
        }),
        this._renderTargetTexture.onAfterUnbindObservable.add(function() {
            var et, tt;
            o.imageProcessingConfiguration.applyByPostProcess = _e,
            o._forcedViewPosition = null,
            _._sceneUBOs && o.setSceneUniformBuffer(_._currentSceneUBO),
            o.updateTransformMatrix(!0),
            (tt = (et = o.getEngine())._debugPopGroup) === null || tt === void 0 || tt.call(et, 1)
        })
    }
    return Object.defineProperty(a.prototype, "samples", {
        get: function() {
            return this._renderTargetTexture.samples
        },
        set: function(e) {
            this._renderTargetTexture.samples = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "refreshRate", {
        get: function() {
            return this._renderTargetTexture.refreshRate
        },
        set: function(e) {
            this._renderTargetTexture.refreshRate = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getScene = function() {
        return this._scene
    }
    ,
    Object.defineProperty(a.prototype, "cubeTexture", {
        get: function() {
            return this._renderTargetTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "renderList", {
        get: function() {
            return this._renderTargetTexture.renderList
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.attachToMesh = function(e) {
        this._attachedMesh = e
    }
    ,
    a.prototype.setRenderingAutoClearDepthStencil = function(e, i) {
        this._renderTargetTexture.setRenderingAutoClearDepthStencil(e, i)
    }
    ,
    a.prototype.dispose = function() {
        var e = this._scene.reflectionProbes.indexOf(this);
        if (e !== -1 && this._scene.reflectionProbes.splice(e, 1),
        this._parentContainer) {
            var i = this._parentContainer.reflectionProbes.indexOf(this);
            i > -1 && this._parentContainer.reflectionProbes.splice(i, 1),
            this._parentContainer = null
        }
        if (this._renderTargetTexture && (this._renderTargetTexture.dispose(),
        this._renderTargetTexture = null),
        this._sceneUBOs) {
            for (var o = 0, s = this._sceneUBOs; o < s.length; o++) {
                var c = s[o];
                c.dispose()
            }
            this._sceneUBOs = []
        }
    }
    ,
    a.prototype.toString = function(e) {
        var i = "Name: " + this.name;
        return e && (i += ", position: " + this.position.toString(),
        this._attachedMesh && (i += ", attached mesh: " + this._attachedMesh.name)),
        i
    }
    ,
    a.prototype.getClassName = function() {
        return "ReflectionProbe"
    }
    ,
    a.prototype.serialize = function() {
        var e = SerializationHelper.Serialize(this, this._renderTargetTexture.serialize());
        return e.isReflectionProbe = !0,
        e
    }
    ,
    a.Parse = function(e, i, o) {
        var s = null;
        if (i.reflectionProbes)
            for (var c = 0; c < i.reflectionProbes.length; c++) {
                var d = i.reflectionProbes[c];
                if (d.name === e.name) {
                    s = d;
                    break
                }
            }
        return s = SerializationHelper.Parse(function() {
            return s || new a(e.name,e.renderTargetSize,i,e._generateMipMaps)
        }, e, i, o),
        s.cubeTexture._waitingRenderList = e.renderList,
        e._attachedMesh && s.attachToMesh(i.getMeshById(e._attachedMesh)),
        s
    }
    ,
    __decorate([serializeAsMeshReference()], a.prototype, "_attachedMesh", void 0),
    __decorate([serializeAsVector3()], a.prototype, "position", void 0),
    a
}()
  , BabylonFileLoaderConfiguration = function() {
    function a() {}
    return a.LoaderInjectedPhysicsEngine = void 0,
    a
}()
  , tempIndexContainer = {}
  , parseMaterialById = function(a, e, i, o) {
    if (!e.materials)
        return null;
    for (var s = 0, c = e.materials.length; s < c; s++) {
        var d = e.materials[s];
        if (d.id === a)
            return Material.Parse(d, i, o)
    }
    return null
}
  , isDescendantOf = function(a, e, i) {
    for (var o in e)
        if (a.name === e[o])
            return i.push(a.id),
            !0;
    return a.parentId && i.indexOf(a.parentId) !== -1 ? (i.push(a.id),
    !0) : !1
}
  , logOperation = function(a, e) {
    return a + " of " + (e ? e.file + " from " + e.name + " version: " + e.version + ", exporter version: " + e.exporter_version : "unknown")
}
  , loadDetailLevels = function(a, e) {
    var i = e;
    if (e._waitingData.lods) {
        if (e._waitingData.lods.ids && e._waitingData.lods.ids.length > 0) {
            var o = e._waitingData.lods.ids
              , s = i.isEnabled(!1);
            if (e._waitingData.lods.distances) {
                var c = e._waitingData.lods.distances;
                if (c.length >= o.length) {
                    var d = c.length > o.length ? c[c.length - 1] : 0;
                    i.setEnabled(!1);
                    for (var _ = 0; _ < o.length; _++) {
                        var b = o[_]
                          , k = a.getMeshById(b);
                        k != null && i.addLODLevel(c[_], k)
                    }
                    d > 0 && i.addLODLevel(d, null),
                    s === !0 && i.setEnabled(!0)
                } else
                    Tools.Warn("Invalid level of detail distances for " + e.name)
            }
        }
        e._waitingData.lods = null
    }
}
  , findParent = function(a, e) {
    if (typeof a != "number")
        return e.getLastEntryById(a);
    var i = tempIndexContainer[a];
    return i
}
  , loadAssetContainer = function(a, e, i, o, s) {
    s === void 0 && (s = !1);
    var c = new AssetContainer(a)
      , d = "importScene has failed JSON parse";
    try {
        var _ = JSON.parse(e);
        d = "";
        var b = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING, k, j;
        if (_.environmentTexture !== void 0 && _.environmentTexture !== null) {
            var $ = _.isPBR !== void 0 ? _.isPBR : !0;
            if (_.environmentTextureType && _.environmentTextureType === "BABYLON.HDRCubeTexture") {
                var _e = _.environmentTextureSize ? _.environmentTextureSize : 128
                  , et = new HDRCubeTexture((_.environmentTexture.match(/https?:\/\//g) ? "" : i) + _.environmentTexture,a,_e,!0,!$);
                _.environmentTextureRotationY && (et.rotationY = _.environmentTextureRotationY),
                a.environmentTexture = et
            } else if (EndsWith(_.environmentTexture, ".env")) {
                var tt = new CubeTexture((_.environmentTexture.match(/https?:\/\//g) ? "" : i) + _.environmentTexture,a);
                _.environmentTextureRotationY && (tt.rotationY = _.environmentTextureRotationY),
                a.environmentTexture = tt
            } else {
                var rt = CubeTexture.CreateFromPrefilteredData((_.environmentTexture.match(/https?:\/\//g) ? "" : i) + _.environmentTexture, a);
                _.environmentTextureRotationY && (rt.rotationY = _.environmentTextureRotationY),
                a.environmentTexture = rt
            }
            if (_.createDefaultSkybox === !0) {
                var it = a.activeCamera !== void 0 && a.activeCamera !== null ? (a.activeCamera.maxZ - a.activeCamera.minZ) / 2 : 1e3
                  , nt = _.skyboxBlurLevel || 0;
                a.createDefaultSkybox(a.environmentTexture, $, it, nt)
            }
            c.environmentTexture = a.environmentTexture
        }
        if (_.environmentIntensity !== void 0 && _.environmentIntensity !== null && (a.environmentIntensity = _.environmentIntensity),
        _.lights !== void 0 && _.lights !== null)
            for (k = 0,
            j = _.lights.length; k < j; k++) {
                var ot = _.lights[k]
                  , at = Light.Parse(ot, a);
                at && (tempIndexContainer[ot.uniqueId] = at,
                c.lights.push(at),
                at._parentContainer = c,
                d += k === 0 ? `
	Lights:` : "",
                d += `
		` + at.toString(b))
            }
        if (_.reflectionProbes !== void 0 && _.reflectionProbes !== null)
            for (k = 0,
            j = _.reflectionProbes.length; k < j; k++) {
                var st = _.reflectionProbes[k]
                  , ut = ReflectionProbe.Parse(st, a, i);
                ut && (c.reflectionProbes.push(ut),
                ut._parentContainer = c,
                d += k === 0 ? `
	Reflection Probes:` : "",
                d += `
		` + ut.toString(b))
            }
        if (_.animations !== void 0 && _.animations !== null)
            for (k = 0,
            j = _.animations.length; k < j; k++) {
                var ct = _.animations[k]
                  , lt = GetClass("BABYLON.Animation");
                if (lt) {
                    var ft = lt.Parse(ct);
                    a.animations.push(ft),
                    c.animations.push(ft),
                    d += k === 0 ? `
	Animations:` : "",
                    d += `
		` + ft.toString(b)
                }
            }
        if (_.materials !== void 0 && _.materials !== null)
            for (k = 0,
            j = _.materials.length; k < j; k++) {
                var ht = _.materials[k]
                  , pt = Material.Parse(ht, a, i);
                if (pt) {
                    c.materials.push(pt),
                    pt._parentContainer = c,
                    d += k === 0 ? `
	Materials:` : "",
                    d += `
		` + pt.toString(b);
                    var dt = pt.getActiveTextures();
                    dt.forEach(function(jt) {
                        c.textures.indexOf(jt) == -1 && (c.textures.push(jt),
                        jt._parentContainer = c)
                    })
                }
            }
        if (_.multiMaterials !== void 0 && _.multiMaterials !== null)
            for (k = 0,
            j = _.multiMaterials.length; k < j; k++) {
                var _t = _.multiMaterials[k]
                  , mt = MultiMaterial.ParseMultiMaterial(_t, a);
                c.multiMaterials.push(mt),
                mt._parentContainer = c,
                d += k === 0 ? `
	MultiMaterials:` : "",
                d += `
		` + mt.toString(b);
                var dt = mt.getActiveTextures();
                dt.forEach(function(Xt) {
                    c.textures.indexOf(Xt) == -1 && (c.textures.push(Xt),
                    Xt._parentContainer = c)
                })
            }
        if (_.morphTargetManagers !== void 0 && _.morphTargetManagers !== null)
            for (var vt = 0, yt = _.morphTargetManagers; vt < yt.length; vt++) {
                var Et = yt[vt]
                  , At = MorphTargetManager.Parse(Et, a);
                c.morphTargetManagers.push(At),
                At._parentContainer = c
            }
        if (_.skeletons !== void 0 && _.skeletons !== null)
            for (k = 0,
            j = _.skeletons.length; k < j; k++) {
                var gt = _.skeletons[k]
                  , St = Skeleton.Parse(gt, a);
                c.skeletons.push(St),
                St._parentContainer = c,
                d += k === 0 ? `
	Skeletons:` : "",
                d += `
		` + St.toString(b)
            }
        var xt = _.geometries;
        if (xt != null) {
            var bt = new Array
              , Rt = xt.vertexData;
            if (Rt != null)
                for (k = 0,
                j = Rt.length; k < j; k++) {
                    var Mt = Rt[k];
                    bt.push(Geometry.Parse(Mt, a, i))
                }
            bt.forEach(function(jt) {
                jt && (c.geometries.push(jt),
                jt._parentContainer = c)
            })
        }
        if (_.transformNodes !== void 0 && _.transformNodes !== null)
            for (k = 0,
            j = _.transformNodes.length; k < j; k++) {
                var Pt = _.transformNodes[k]
                  , It = TransformNode.Parse(Pt, a, i);
                tempIndexContainer[Pt.uniqueId] = It,
                c.transformNodes.push(It),
                It._parentContainer = c
            }
        if (_.meshes !== void 0 && _.meshes !== null)
            for (k = 0,
            j = _.meshes.length; k < j; k++) {
                var Dt = _.meshes[k]
                  , Ct = Mesh.Parse(Dt, a, i);
                if (tempIndexContainer[Dt.uniqueId] = Ct,
                c.meshes.push(Ct),
                Ct._parentContainer = c,
                Ct.hasInstances)
                    for (var Ot = 0, wt = Ct.instances; Ot < wt.length; Ot++) {
                        var Nt = wt[Ot];
                        c.meshes.push(Nt),
                        Nt._parentContainer = c
                    }
                d += k === 0 ? `
	Meshes:` : "",
                d += `
		` + Ct.toString(b)
            }
        if (_.cameras !== void 0 && _.cameras !== null)
            for (k = 0,
            j = _.cameras.length; k < j; k++) {
                var Ft = _.cameras[k]
                  , Vt = Camera$1.Parse(Ft, a);
                tempIndexContainer[Ft.uniqueId] = Vt,
                c.cameras.push(Vt),
                Vt._parentContainer = c,
                d += k === 0 ? `
	Cameras:` : "",
                d += `
		` + Vt.toString(b)
            }
        if (_.postProcesses !== void 0 && _.postProcesses !== null)
            for (k = 0,
            j = _.postProcesses.length; k < j; k++) {
                var Lt = _.postProcesses[k]
                  , kt = PostProcess.Parse(Lt, a, i);
                kt && (c.postProcesses.push(kt),
                kt._parentContainer = c,
                d += k === 0 ? `
Postprocesses:` : "",
                d += `
		` + kt.toString())
            }
        if (_.animationGroups !== void 0 && _.animationGroups !== null)
            for (k = 0,
            j = _.animationGroups.length; k < j; k++) {
                var Bt = _.animationGroups[k]
                  , Ut = AnimationGroup.Parse(Bt, a);
                c.animationGroups.push(Ut),
                Ut._parentContainer = c,
                d += k === 0 ? `
	AnimationGroups:` : "",
                d += `
		` + Ut.toString(b)
            }
        for (k = 0,
        j = a.cameras.length; k < j; k++) {
            var Vt = a.cameras[k];
            Vt._waitingParentId && (Vt.parent = findParent(Vt._waitingParentId, a),
            Vt._waitingParentId = null)
        }
        for (k = 0,
        j = a.lights.length; k < j; k++) {
            var Gt = a.lights[k];
            Gt && Gt._waitingParentId && (Gt.parent = findParent(Gt._waitingParentId, a),
            Gt._waitingParentId = null)
        }
        for (k = 0,
        j = a.transformNodes.length; k < j; k++) {
            var Ht = a.transformNodes[k];
            Ht._waitingParentId && (Ht.parent = findParent(Ht._waitingParentId, a),
            Ht._waitingParentId = null)
        }
        for (k = 0,
        j = a.meshes.length; k < j; k++) {
            var Ct = a.meshes[k];
            Ct._waitingParentId && (Ct.parent = findParent(Ct._waitingParentId, a),
            Ct._waitingParentId = null),
            Ct._waitingData.lods && loadDetailLevels(a, Ct)
        }
        for (k = 0,
        j = a.skeletons.length; k < j; k++) {
            var St = a.skeletons[k];
            St._hasWaitingData && (St.bones != null && St.bones.forEach(function(Xt) {
                if (Xt._waitingTransformNodeId) {
                    var nr = a.getLastEntryById(Xt._waitingTransformNodeId);
                    nr && Xt.linkTransformNode(nr),
                    Xt._waitingTransformNodeId = null
                }
            }),
            St._waitingOverrideMeshId && (St.overrideMesh = a.getMeshById(St._waitingOverrideMeshId),
            St._waitingOverrideMeshId = null),
            St._hasWaitingData = null)
        }
        for (k = 0,
        j = a.meshes.length; k < j; k++) {
            var zt = a.meshes[k];
            zt._waitingData.freezeWorldMatrix ? (zt.freezeWorldMatrix(),
            zt._waitingData.freezeWorldMatrix = null) : zt.computeWorldMatrix(!0)
        }
        for (k = 0,
        j = a.lights.length; k < j; k++) {
            var Wt = a.lights[k];
            if (Wt._excludedMeshesIds.length > 0) {
                for (var Kt = 0; Kt < Wt._excludedMeshesIds.length; Kt++) {
                    var Qt = a.getMeshById(Wt._excludedMeshesIds[Kt]);
                    Qt && Wt.excludedMeshes.push(Qt)
                }
                Wt._excludedMeshesIds = []
            }
            if (Wt._includedOnlyMeshesIds.length > 0) {
                for (var qt = 0; qt < Wt._includedOnlyMeshesIds.length; qt++) {
                    var Yt = a.getMeshById(Wt._includedOnlyMeshesIds[qt]);
                    Yt && Wt.includedOnlyMeshes.push(Yt)
                }
                Wt._includedOnlyMeshesIds = []
            }
        }
        for (AbstractScene.Parse(_, a, c, i),
        k = 0,
        j = a.meshes.length; k < j; k++) {
            var Ct = a.meshes[k];
            Ct._waitingData.actions && (ActionManager.Parse(Ct._waitingData.actions, Ct, a),
            Ct._waitingData.actions = null)
        }
        _.actions !== void 0 && _.actions !== null && ActionManager.Parse(_.actions, null, a)
    } catch (jt) {
        var Jt = logOperation("loadAssets", _ ? _.producer : "Unknown") + d;
        if (o)
            o(Jt, jt);
        else
            throw Logger$2.Log(Jt),
            jt
    } finally {
        tempIndexContainer = {},
        s || c.removeAllFromScene(),
        d !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING && Logger$2.Log(logOperation("loadAssets", _ ? _.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? d : ""))
    }
    return c
};
SceneLoader.RegisterPlugin({
    name: "babylon.js",
    extensions: ".babylon",
    canDirectLoad: function(a) {
        return a.indexOf("babylon") !== -1
    },
    importMesh: function(a, e, i, o, s, c, d, _) {
        var b = "importMesh has failed JSON parse";
        try {
            var k = JSON.parse(i);
            b = "";
            var j = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;
            a ? Array.isArray(a) || (a = [a]) : a = null;
            var $ = new Array;
            if (k.meshes !== void 0 && k.meshes !== null) {
                var _e = [], et = [], tt, rt;
                for (tt = 0,
                rt = k.meshes.length; tt < rt; tt++) {
                    var it = k.meshes[tt];
                    if (a === null || isDescendantOf(it, a, $)) {
                        if (a !== null && delete a[a.indexOf(it.name)],
                        it.geometryId !== void 0 && it.geometryId !== null && k.geometries !== void 0 && k.geometries !== null) {
                            var nt = !1;
                            ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function(Pt) {
                                nt === !0 || !k.geometries[Pt] || !Array.isArray(k.geometries[Pt]) || k.geometries[Pt].forEach(function(It) {
                                    if (It.id === it.geometryId) {
                                        switch (Pt) {
                                        case "vertexData":
                                            Geometry.Parse(It, e, o);
                                            break
                                        }
                                        nt = !0
                                    }
                                })
                            }),
                            nt === !1 && Logger$2.Warn("Geometry not found for mesh " + it.id)
                        }
                        if (it.materialId) {
                            var ot = et.indexOf(it.materialId) !== -1;
                            if (ot === !1 && k.multiMaterials !== void 0 && k.multiMaterials !== null)
                                for (var at = 0, st = k.multiMaterials.length; at < st; at++) {
                                    var ut = k.multiMaterials[at];
                                    if (ut.id === it.materialId) {
                                        for (var ct = 0, lt = ut.materials.length; ct < lt; ct++) {
                                            var ft = ut.materials[ct];
                                            et.push(ft);
                                            var ht = parseMaterialById(ft, k, e, o);
                                            ht && (b += `
	Material ` + ht.toString(j))
                                        }
                                        et.push(ut.id);
                                        var pt = MultiMaterial.ParseMultiMaterial(ut, e);
                                        pt && (ot = !0,
                                        b += `
	Multi-Material ` + pt.toString(j));
                                        break
                                    }
                                }
                            if (ot === !1) {
                                et.push(it.materialId);
                                var ht = parseMaterialById(it.materialId, k, e, o);
                                ht ? b += `
	Material ` + ht.toString(j) : Logger$2.Warn("Material not found for mesh " + it.id)
                            }
                        }
                        if (it.skeletonId > -1 && k.skeletons !== void 0 && k.skeletons !== null) {
                            var dt = _e.indexOf(it.skeletonId) > -1;
                            if (dt === !1)
                                for (var _t = 0, mt = k.skeletons.length; _t < mt; _t++) {
                                    var vt = k.skeletons[_t];
                                    if (vt.id === it.skeletonId) {
                                        var yt = Skeleton.Parse(vt, e);
                                        d.push(yt),
                                        _e.push(vt.id),
                                        b += `
	Skeleton ` + yt.toString(j)
                                    }
                                }
                        }
                        if (k.morphTargetManagers !== void 0 && k.morphTargetManagers !== null)
                            for (var Et = 0, At = k.morphTargetManagers; Et < At.length; Et++) {
                                var gt = At[Et];
                                MorphTargetManager.Parse(gt, e)
                            }
                        var St = Mesh.Parse(it, e, o);
                        s.push(St),
                        b += `
	Mesh ` + St.toString(j)
                    }
                }
                var xt;
                for (tt = 0,
                rt = e.meshes.length; tt < rt; tt++)
                    xt = e.meshes[tt],
                    xt._waitingParentId && (xt.parent = e.getLastEntryById(xt._waitingParentId),
                    xt._waitingParentId = null),
                    xt._waitingData.lods && loadDetailLevels(e, xt);
                for (tt = 0,
                rt = e.skeletons.length; tt < rt; tt++) {
                    var yt = e.skeletons[tt];
                    yt._hasWaitingData && (yt.bones != null && yt.bones.forEach(function(It) {
                        if (It._waitingTransformNodeId) {
                            var Dt = e.getLastEntryById(It._waitingTransformNodeId);
                            Dt && It.linkTransformNode(Dt),
                            It._waitingTransformNodeId = null
                        }
                    }),
                    yt._waitingOverrideMeshId && (yt.overrideMesh = e.getMeshById(yt._waitingOverrideMeshId),
                    yt._waitingOverrideMeshId = null),
                    yt._hasWaitingData = null)
                }
                for (tt = 0,
                rt = e.meshes.length; tt < rt; tt++)
                    xt = e.meshes[tt],
                    xt._waitingData.freezeWorldMatrix ? (xt.freezeWorldMatrix(),
                    xt._waitingData.freezeWorldMatrix = null) : xt.computeWorldMatrix(!0)
            }
            if (k.particleSystems !== void 0 && k.particleSystems !== null) {
                var bt = AbstractScene.GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM);
                if (bt)
                    for (tt = 0,
                    rt = k.particleSystems.length; tt < rt; tt++) {
                        var Rt = k.particleSystems[tt];
                        $.indexOf(Rt.emitterId) !== -1 && c.push(bt(Rt, e, o))
                    }
            }
            return !0
        } catch (Pt) {
            var Mt = logOperation("importMesh", k ? k.producer : "Unknown") + b;
            if (_)
                _(Mt, Pt);
            else
                throw Logger$2.Log(Mt),
                Pt
        } finally {
            b !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING && Logger$2.Log(logOperation("importMesh", k ? k.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? b : ""))
        }
        return !1
    },
    load: function(a, e, i, o) {
        var s = "importScene has failed JSON parse";
        try {
            var c = JSON.parse(e);
            if (s = "",
            c.useDelayedTextureLoading !== void 0 && c.useDelayedTextureLoading !== null && (a.useDelayedTextureLoading = c.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental),
            c.autoClear !== void 0 && c.autoClear !== null && (a.autoClear = c.autoClear),
            c.clearColor !== void 0 && c.clearColor !== null && (a.clearColor = Color4.FromArray(c.clearColor)),
            c.ambientColor !== void 0 && c.ambientColor !== null && (a.ambientColor = Color3.FromArray(c.ambientColor)),
            c.gravity !== void 0 && c.gravity !== null && (a.gravity = Vector3.FromArray(c.gravity)),
            c.fogMode && c.fogMode !== 0)
                switch (a.fogMode = c.fogMode,
                a.fogColor = Color3.FromArray(c.fogColor),
                a.fogStart = c.fogStart,
                a.fogEnd = c.fogEnd,
                a.fogDensity = c.fogDensity,
                s += "	Fog mode for scene:  ",
                a.fogMode) {
                case 1:
                    s += `exp
`;
                    break;
                case 2:
                    s += `exp2
`;
                    break;
                case 3:
                    s += `linear
`;
                    break
                }
            if (c.physicsEnabled) {
                var d;
                c.physicsEngine === "cannon" ? d = new CannonJSPlugin(void 0,void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine) : c.physicsEngine === "oimo" ? d = new OimoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine) : c.physicsEngine === "ammo" && (d = new AmmoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine,void 0)),
                s = "	Physics engine " + (c.physicsEngine ? c.physicsEngine : "oimo") + ` enabled
`;
                var _ = c.physicsGravity ? Vector3.FromArray(c.physicsGravity) : null;
                a.enablePhysics(_, d)
            }
            c.metadata !== void 0 && c.metadata !== null && (a.metadata = c.metadata),
            c.collisionsEnabled !== void 0 && c.collisionsEnabled !== null && (a.collisionsEnabled = c.collisionsEnabled);
            var b = loadAssetContainer(a, e, i, o, !0);
            return b ? (c.autoAnimate && a.beginAnimation(a, c.autoAnimateFrom, c.autoAnimateTo, c.autoAnimateLoop, c.autoAnimateSpeed || 1),
            c.activeCameraID !== void 0 && c.activeCameraID !== null && a.setActiveCameraById(c.activeCameraID),
            !0) : !1
        } catch (j) {
            var k = logOperation("importScene", c ? c.producer : "Unknown") + s;
            if (o)
                o(k, j);
            else
                throw Logger$2.Log(k),
                j
        } finally {
            s !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING && Logger$2.Log(logOperation("importScene", c ? c.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? s : ""))
        }
        return !1
    },
    loadAssetContainer: function(a, e, i, o) {
        var s = loadAssetContainer(a, e, i, o);
        return s
    }
});
var name$a = "depthPixelShader"
  , shader$a = `#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$a] = shader$a;
var name$9 = "depthVertexShader"
  , shader$9 = `
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$9] = shader$9;
var DepthRenderer = function() {
    function a(e, i, o, s, c) {
        var d = this;
        i === void 0 && (i = 1),
        o === void 0 && (o = null),
        s === void 0 && (s = !1),
        c === void 0 && (c = Texture.TRILINEAR_SAMPLINGMODE),
        this.enabled = !0,
        this.forceDepthWriteTransparentMeshes = !1,
        this.useOnlyInActiveCamera = !1,
        this._scene = e,
        this._storeNonLinearDepth = s,
        this.isPacked = i === 0,
        this.isPacked ? this._clearColor = new Color4(1,1,1,1) : this._clearColor = new Color4(1,0,0,1),
        a._SceneComponentInitialization(this._scene);
        var _ = e.getEngine();
        this._camera = o,
        c !== Texture.NEAREST_SAMPLINGMODE && (i === 1 && !_._caps.textureFloatLinearFiltering && (c = Texture.NEAREST_SAMPLINGMODE),
        i === 2 && !_._caps.textureHalfFloatLinearFiltering && (c = Texture.NEAREST_SAMPLINGMODE));
        var b = this.isPacked || !_._features.supportExtendedTextureFormats ? 5 : 6;
        this._depthMap = new RenderTargetTexture("DepthRenderer",{
            width: _.getRenderWidth(),
            height: _.getRenderHeight()
        },this._scene,!1,!0,i,!1,c,void 0,void 0,void 0,b),
        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(j) {
            j.clear(d._clearColor, !0, !0, !0)
        }),
        this._depthMap.onBeforeBindObservable.add(function() {
            var j;
            (j = _._debugPushGroup) === null || j === void 0 || j.call(_, "depth renderer", 1)
        }),
        this._depthMap.onAfterUnbindObservable.add(function() {
            var j;
            (j = _._debugPopGroup) === null || j === void 0 || j.call(_, 1)
        });
        var k = function(j) {
            var $, _e, et = j.getRenderingMesh(), tt = j.getEffectiveMesh(), rt = d._scene, it = rt.getEngine(), nt = j.getMaterial();
            if (tt._internalAbstractMeshDataInfo._isActiveIntermediate = !1,
            !(!nt || tt.infiniteDistance || nt.disableDepthWrite || j.verticesCount === 0 || j._renderId === rt.getRenderId())) {
                var ot = tt._getWorldMatrixDeterminant() < 0
                  , at = ($ = et.overrideMaterialSideOrientation) !== null && $ !== void 0 ? $ : nt.sideOrientation;
                (rt.useRightHandedSystem && !ot || !rt.useRightHandedSystem && ot) && (at = at === 0 ? 1 : 0);
                var st = at === 0;
                it.setState(nt.backFaceCulling, 0, !1, st, nt.cullBackFaces);
                var ut = et._getInstancesRenderList(j._id, !!j.getReplacementMesh());
                if (!ut.mustReturn) {
                    var ct = it.getCaps().instancedArrays && (ut.visibleInstances[j._id] !== null && ut.visibleInstances[j._id] !== void 0 || et.hasThinInstances)
                      , lt = d._camera || rt.activeCamera;
                    if (d.isReady(j, ct) && lt) {
                        j._renderId = rt.getRenderId();
                        var ft = (_e = tt._internalAbstractMeshDataInfo._materialForRenderPass) === null || _e === void 0 ? void 0 : _e[it.currentRenderPassId]
                          , ht = j._getDrawWrapper();
                        !ht && ft && (ht = ft._getDrawWrapper());
                        var pt = lt.mode === Camera$1.ORTHOGRAPHIC_CAMERA;
                        if (!ht)
                            return;
                        var dt = ht.effect;
                        it.enableEffect(ht),
                        ct || et._bind(j, dt, nt.fillMode),
                        ft ? ft.bindForSubMesh(tt.getWorldMatrix(), tt, j) : (dt.setMatrix("viewProjection", rt.getTransformMatrix()),
                        dt.setMatrix("world", tt.getWorldMatrix()));
                        var _t = void 0
                          , mt = void 0;
                        if (pt ? (_t = !it.useReverseDepthBuffer && it.isNDCHalfZRange ? 0 : 1,
                        mt = it.useReverseDepthBuffer && it.isNDCHalfZRange ? 0 : 1) : (_t = it.useReverseDepthBuffer && it.isNDCHalfZRange ? lt.minZ : it.isNDCHalfZRange ? 0 : lt.minZ,
                        mt = it.useReverseDepthBuffer && it.isNDCHalfZRange ? 0 : lt.maxZ),
                        dt.setFloat2("depthValues", _t, _t + mt),
                        !ft) {
                            if (nt && nt.needAlphaTesting()) {
                                var vt = nt.getAlphaTestTexture();
                                vt && (dt.setTexture("diffuseSampler", vt),
                                dt.setMatrix("diffuseMatrix", vt.getTextureMatrix()))
                            }
                            if (et.useBones && et.computeBonesUsingShaders && et.skeleton) {
                                var yt = et.skeleton;
                                if (yt.isUsingTextureForMatrices) {
                                    var Et = yt.getTransformMatrixTexture(et);
                                    if (!Et)
                                        return;
                                    dt.setTexture("boneSampler", Et),
                                    dt.setFloat("boneTextureWidth", 4 * (yt.bones.length + 1))
                                } else
                                    dt.setMatrices("mBones", yt.getTransformMatrices(et))
                            }
                            MaterialHelper.BindMorphTargetParameters(et, dt),
                            et.morphTargetManager && et.morphTargetManager.isUsingTextureForTargets && et.morphTargetManager._bind(dt)
                        }
                        et._processRendering(tt, j, dt, nt.fillMode, ut, ct, function(At, gt) {
                            return dt.setMatrix("world", gt)
                        })
                    }
                }
            }
        };
        this._depthMap.customRenderFunction = function(j, $, _e, et) {
            var tt;
            if (et.length)
                for (tt = 0; tt < et.length; tt++)
                    k(et.data[tt]);
            for (tt = 0; tt < j.length; tt++)
                k(j.data[tt]);
            for (tt = 0; tt < $.length; tt++)
                k($.data[tt]);
            if (d.forceDepthWriteTransparentMeshes)
                for (tt = 0; tt < _e.length; tt++)
                    k(_e.data[tt]);
            else
                for (tt = 0; tt < _e.length; tt++)
                    _e.data[tt].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = !1
        }
    }
    return a.prototype.setMaterialForRendering = function(e, i) {
        this._depthMap.setMaterialForRendering(e, i)
    }
    ,
    a.prototype.isReady = function(e, i) {
        var o, s = this._scene.getEngine(), c = e.getMesh(), d = (o = c._internalAbstractMeshDataInfo._materialForRenderPass) === null || o === void 0 ? void 0 : o[s.currentRenderPassId];
        if (d)
            return d.isReadyForSubMesh(c, e, i);
        var _ = e.getMaterial();
        if (!_ || _.disableDepthWrite)
            return !1;
        var b = []
          , k = [VertexBuffer.PositionKind];
        if (_ && _.needAlphaTesting() && _.getAlphaTestTexture() && (b.push("#define ALPHATEST"),
        c.isVerticesDataPresent(VertexBuffer.UVKind) && (k.push(VertexBuffer.UVKind),
        b.push("#define UV1")),
        c.isVerticesDataPresent(VertexBuffer.UV2Kind) && (k.push(VertexBuffer.UV2Kind),
        b.push("#define UV2"))),
        c.useBones && c.computeBonesUsingShaders) {
            k.push(VertexBuffer.MatricesIndicesKind),
            k.push(VertexBuffer.MatricesWeightsKind),
            c.numBoneInfluencers > 4 && (k.push(VertexBuffer.MatricesIndicesExtraKind),
            k.push(VertexBuffer.MatricesWeightsExtraKind)),
            b.push("#define NUM_BONE_INFLUENCERS " + c.numBoneInfluencers),
            b.push("#define BonesPerMesh " + (c.skeleton ? c.skeleton.bones.length + 1 : 0));
            var j = e.getRenderingMesh().skeleton;
            j != null && j.isUsingTextureForMatrices && b.push("#define BONETEXTURE")
        } else
            b.push("#define NUM_BONE_INFLUENCERS 0");
        var $ = c.morphTargetManager
          , _e = 0;
        $ && $.numInfluencers > 0 && (_e = $.numInfluencers,
        b.push("#define MORPHTARGETS"),
        b.push("#define NUM_MORPH_INFLUENCERS " + _e),
        $.isUsingTextureForTargets && b.push("#define MORPHTARGETS_TEXTURE"),
        MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(k, c, _e)),
        i && (b.push("#define INSTANCES"),
        MaterialHelper.PushAttributesForInstances(k),
        e.getRenderingMesh().hasThinInstances && b.push("#define THIN_INSTANCES")),
        this._storeNonLinearDepth && b.push("#define NONLINEARDEPTH"),
        this.isPacked && b.push("#define PACKED");
        var et = e._getDrawWrapper(void 0, !0)
          , tt = et.defines
          , rt = b.join(`
`);
        return tt !== rt && et.setEffect(s.createEffect("depth", k, ["world", "mBones", "boneTextureWidth", "viewProjection", "diffuseMatrix", "depthValues", "morphTargetInfluences", "morphTargetTextureInfo", "morphTargetTextureIndices"], ["diffuseSampler", "morphTargets", "boneSampler"], rt, void 0, void 0, void 0, {
            maxSimultaneousMorphTargets: _e
        }), rt),
        et.effect.isReady()
    }
    ,
    a.prototype.getDepthMap = function() {
        return this._depthMap
    }
    ,
    a.prototype.dispose = function() {
        var e = [];
        for (var i in this._scene._depthRenderer) {
            var o = this._scene._depthRenderer[i];
            o === this && e.push(i)
        }
        if (e.length > 0) {
            this._depthMap.dispose();
            for (var s = 0, c = e; s < c.length; s++) {
                var d = c[s];
                delete this._scene._depthRenderer[d]
            }
        }
    }
    ,
    a._SceneComponentInitialization = function(e) {
        throw _WarnImport("DepthRendererSceneComponent")
    }
    ,
    a
}()
  , name$8 = "minmaxReduxPixelShader"
  , shader$8 = `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$8] = shader$8;
var MinMaxReducer = function() {
    function a(e) {
        var i = 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() {
            i._postProcessManager._rebuild()
        })
    }
    return Object.defineProperty(a.prototype, "sourceTexture", {
        get: function() {
            return this._sourceTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.setSourceTexture = function(e, i, o, s) {
        var c = this;
        if (o === void 0 && (o = 2),
        s === void 0 && (s = !0),
        e !== this._sourceTexture) {
            this.dispose(!1),
            this._sourceTexture = e,
            this._reductionSteps = [],
            this._forceFullscreenViewport = s;
            var d = this._camera.getScene()
              , _ = new PostProcess("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,d.getEngine(),!1,"#define INITIAL" + (i ? `
#define DEPTH_REDUX` : ""),o,void 0,void 0,void 0,7);
            _.autoClear = !1,
            _.forceFullscreenViewport = s;
            var b = this._sourceTexture.getRenderWidth()
              , k = this._sourceTexture.getRenderHeight();
            _.onApply = function(et, tt) {
                return function(rt) {
                    rt.setTexture("sourceTexture", c._sourceTexture),
                    rt.setFloat2("texSize", et, tt)
                }
            }(b, k),
            this._reductionSteps.push(_);
            for (var j = 1; b > 1 || k > 1; ) {
                b = Math.max(Math.round(b / 2), 1),
                k = Math.max(Math.round(k / 2), 1);
                var $ = new PostProcess("Reduction phase " + j,"minmaxRedux",["texSize"],null,{
                    width: b,
                    height: k
                },null,1,d.getEngine(),!1,"#define " + (b == 1 && k == 1 ? "LAST" : b == 1 || k == 1 ? "ONEBEFORELAST" : "MAIN"),o,void 0,void 0,void 0,7);
                if ($.autoClear = !1,
                $.forceFullscreenViewport = s,
                $.onApply = function(et, tt) {
                    return function(rt) {
                        et == 1 || tt == 1 ? rt.setInt2("texSize", et, tt) : rt.setFloat2("texSize", et, tt)
                    }
                }(b, k),
                this._reductionSteps.push($),
                j++,
                b == 1 && k == 1) {
                    var _e = function(et, tt, rt) {
                        var it = new Float32Array(4 * et * tt)
                          , nt = {
                            min: 0,
                            max: 0
                        };
                        return function() {
                            d.getEngine()._readTexturePixels(rt.inputTexture.texture, et, tt, -1, 0, it, !1),
                            nt.min = it[0],
                            nt.max = it[1],
                            c.onAfterReductionPerformed.notifyObservers(nt)
                        }
                    };
                    $.onAfterRenderObservable.add(_e(b, k, $))
                }
            }
        }
    }
    ,
    Object.defineProperty(a.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(a.prototype, "activated", {
        get: function() {
            return this._activated
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.activate = function() {
        var e = this;
        this._onAfterUnbindObserver || !this._sourceTexture || (this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(function() {
            var i, o, s = e._camera.getScene().getEngine();
            (i = s._debugPushGroup) === null || i === void 0 || i.call(s, "min max reduction", 1),
            e._reductionSteps[0].activate(e._camera),
            e._postProcessManager.directRender(e._reductionSteps, e._reductionSteps[0].inputTexture, e._forceFullscreenViewport),
            s.unBindFramebuffer(e._reductionSteps[0].inputTexture, !1),
            (o = s._debugPopGroup) === null || o === void 0 || o.call(s, 1)
        }),
        this._activated = !0)
    }
    ,
    a.prototype.deactivate = function() {
        !this._onAfterUnbindObserver || !this._sourceTexture || (this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),
        this._onAfterUnbindObserver = null,
        this._activated = !1)
    }
    ,
    a.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 i = 0; i < this._reductionSteps.length; ++i)
                this._reductionSteps[i].dispose();
            this._reductionSteps = null
        }
        this._postProcessManager && e && this._postProcessManager.dispose(),
        this._sourceTexture = null
    }
    ,
    a
}()
  , DepthReducer = function(a) {
    __extends(e, a);
    function e(i) {
        return a.call(this, i) || this
    }
    return Object.defineProperty(e.prototype, "depthRenderer", {
        get: function() {
            return this._depthRenderer
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setDepthRenderer = function(i, o, s) {
        i === void 0 && (i = null),
        o === void 0 && (o = 2),
        s === void 0 && (s = !0);
        var c = this._camera.getScene();
        this._depthRenderer && (delete c._depthRenderer[this._depthRendererId],
        this._depthRenderer.dispose(),
        this._depthRenderer = null),
        i === null && (c._depthRenderer || (c._depthRenderer = {}),
        i = this._depthRenderer = new DepthRenderer(c,o,this._camera,!1,1),
        i.enabled = !1,
        this._depthRendererId = "minmax" + this._camera.id,
        c._depthRenderer[this._depthRendererId] = i),
        a.prototype.setSourceTexture.call(this, i.getDepthMap(), !0, o, s)
    }
    ,
    e.prototype.setSourceTexture = function(i, o, s, c) {
        s === void 0 && (s = 2),
        c === void 0 && (c = !0),
        a.prototype.setSourceTexture.call(this, i, o, s, c)
    }
    ,
    e.prototype.activate = function() {
        this._depthRenderer && (this._depthRenderer.enabled = !0),
        a.prototype.activate.call(this)
    }
    ,
    e.prototype.deactivate = function() {
        a.prototype.deactivate.call(this),
        this._depthRenderer && (this._depthRenderer.enabled = !1)
    }
    ,
    e.prototype.dispose = function(i) {
        if (i === void 0 && (i = !0),
        a.prototype.dispose.call(this, i),
        this._depthRenderer && i) {
            var o = this._depthRenderer.getDepthMap().getScene();
            o && delete o._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(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = this;
        if (!e.IsSupported) {
            Logger$2.Error("CascadedShadowMap is not supported by the current engine.");
            return
        }
        return c = a.call(this, i, o, s) || this,
        c.usePercentageCloserFiltering = !0,
        c
    }
    return e.prototype._validateFilter = function(i) {
        return i === ShadowGenerator.FILTER_NONE || i === ShadowGenerator.FILTER_PCF || i === ShadowGenerator.FILTER_PCSS ? i : (console.error('Unsupported filter "' + i + '"!'),
        ShadowGenerator.FILTER_NONE)
    }
    ,
    Object.defineProperty(e.prototype, "numCascades", {
        get: function() {
            return this._numCascades
        },
        set: function(i) {
            i = Math.min(Math.max(i, e.MIN_CASCADES_COUNT), e.MAX_CASCADES_COUNT),
            i !== this._numCascades && (this._numCascades = i,
            this.recreateShadowMap(),
            this._recreateSceneUBOs())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "freezeShadowCastersBoundingInfo", {
        get: function() {
            return this._freezeShadowCastersBoundingInfo
        },
        set: function(i) {
            this._freezeShadowCastersBoundingInfoObservable && i && (this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),
            this._freezeShadowCastersBoundingInfoObservable = null),
            !this._freezeShadowCastersBoundingInfoObservable && !i && (this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this))),
            this._freezeShadowCastersBoundingInfo = i,
            i && 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 i = this._shadowMap.renderList, o = 0; o < i.length; o++) {
                var s = i[o];
                if (!!s) {
                    var c = s.getBoundingInfo()
                      , d = c.boundingBox;
                    this._scbiMin.minimizeInPlace(d.minimumWorld),
                    this._scbiMax.maximizeInPlace(d.maximumWorld)
                }
            }
            for (var _ = this._scene.meshes, o = 0; o < _.length; o++) {
                var s = _[o];
                if (!(!s || !s.isVisible || !s.isEnabled || !s.receiveShadows)) {
                    var c = s.getBoundingInfo()
                      , d = c.boundingBox;
                    this._scbiMin.minimizeInPlace(d.minimumWorld),
                    this._scbiMax.maximizeInPlace(d.maximumWorld)
                }
            }
        }
        this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax)
    }
    ,
    Object.defineProperty(e.prototype, "shadowCastersBoundingInfo", {
        get: function() {
            return this._shadowCastersBoundingInfo
        },
        set: function(i) {
            this._shadowCastersBoundingInfo = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setMinMaxDistance = function(i, o) {
        this._minDistance === i && this._maxDistance === o || (i > o && (i = 0,
        o = 1),
        i < 0 && (i = 0),
        o > 1 && (o = 1),
        this._minDistance = i,
        this._maxDistance = o,
        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(i) {
        return i >= 0 && i < this._numCascades ? this._cascadeMinExtents[i] : null
    }
    ,
    e.prototype.getCascadeMaxExtents = function(i) {
        return i >= 0 && i < this._numCascades ? this._cascadeMaxExtents[i] : null
    }
    ,
    Object.defineProperty(e.prototype, "shadowMaxZ", {
        get: function() {
            return !this._scene || !this._scene.activeCamera ? 0 : this._shadowMaxZ
        },
        set: function(i) {
            if (!this._scene || !this._scene.activeCamera) {
                this._shadowMaxZ = i;
                return
            }
            this._shadowMaxZ === i || i < this._scene.activeCamera.minZ || i > this._scene.activeCamera.maxZ || (this._shadowMaxZ = i,
            this._light._markMeshesAsLightDirty(),
            this._breaksAreDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "debug", {
        get: function() {
            return this._debug
        },
        set: function(i) {
            this._debug = i,
            this._light._markMeshesAsLightDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthClamp", {
        get: function() {
            return this._depthClamp
        },
        set: function(i) {
            this._depthClamp = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cascadeBlendPercentage", {
        get: function() {
            return this._cascadeBlendPercentage
        },
        set: function(i) {
            this._cascadeBlendPercentage = i,
            this._light._markMeshesAsLightDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lambda", {
        get: function() {
            return this._lambda
        },
        set: function(i) {
            var o = Math.min(Math.max(i, 0), 1);
            this._lambda != o && (this._lambda = o,
            this._breaksAreDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getCascadeViewMatrix = function(i) {
        return i >= 0 && i < this._numCascades ? this._viewMatrices[i] : null
    }
    ,
    e.prototype.getCascadeProjectionMatrix = function(i) {
        return i >= 0 && i < this._numCascades ? this._projectionMatrices[i] : null
    }
    ,
    e.prototype.getCascadeTransformMatrix = function(i) {
        return i >= 0 && i < this._numCascades ? this._transformMatrices[i] : null
    }
    ,
    e.prototype.setDepthRenderer = function(i) {
        this._depthRenderer = i,
        this._depthReducer && this._depthReducer.setDepthRenderer(this._depthRenderer)
    }
    ,
    Object.defineProperty(e.prototype, "autoCalcDepthBounds", {
        get: function() {
            return this._autoCalcDepthBounds
        },
        set: function(i) {
            var o = this
              , s = this._scene.activeCamera;
            if (!!s) {
                if (this._autoCalcDepthBounds = i,
                !i) {
                    this._depthReducer && this._depthReducer.deactivate(),
                    this.setMinMaxDistance(0, 1);
                    return
                }
                this._depthReducer || (this._depthReducer = new DepthReducer(s),
                this._depthReducer.onAfterReductionPerformed.add(function(c) {
                    var d = c.min
                      , _ = c.max;
                    d >= _ && (d = 0,
                    _ = 1),
                    (d != o._minDistance || _ != o._maxDistance) && o.setMinMaxDistance(d, _)
                }),
                this._depthReducer.setDepthRenderer(this._depthRenderer)),
                this._depthReducer.activate()
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "autoCalcDepthBoundsRefreshRate", {
        get: function() {
            var i, o, s;
            return (s = (o = (i = this._depthReducer) === null || i === void 0 ? void 0 : i.depthRenderer) === null || o === void 0 ? void 0 : o.getDepthMap().refreshRate) !== null && s !== void 0 ? s : -1
        },
        set: function(i) {
            var o;
            !((o = this._depthReducer) === null || o === void 0) && o.depthRenderer && (this._depthReducer.depthRenderer.getDepthMap().refreshRate = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.splitFrustum = function() {
        this._breaksAreDirty = !0
    }
    ,
    e.prototype._splitFrustum = function() {
        var i = this._scene.activeCamera;
        if (!!i) {
            for (var o = i.minZ, s = i.maxZ, c = s - o, d = this._minDistance, _ = this._shadowMaxZ < s && this._shadowMaxZ >= o ? Math.min((this._shadowMaxZ - o) / (s - o), this._maxDistance) : this._maxDistance, b = o + d * c, k = o + _ * c, j = k - b, $ = k / b, _e = 0; _e < this._cascades.length; ++_e) {
                var et = (_e + 1) / this._numCascades
                  , tt = b * Math.pow($, et)
                  , rt = b + j * et
                  , it = this._lambda * (tt - rt) + rt;
                this._cascades[_e].prevBreakDistance = _e === 0 ? d : this._cascades[_e - 1].breakDistance,
                this._cascades[_e].breakDistance = (it - o) / c,
                this._viewSpaceFrustumsZ[_e] = it,
                this._frustumLengths[_e] = (this._cascades[_e].breakDistance - this._cascades[_e].prevBreakDistance) * c
            }
            this._breaksAreDirty = !1
        }
    }
    ,
    e.prototype._computeMatrices = function() {
        var i = this._scene
          , o = i.activeCamera;
        if (!!o) {
            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 s = i.getEngine().useReverseDepthBuffer, c = 0; c < this._numCascades; ++c) {
                this._computeFrustumInWorldSpace(c),
                this._computeCascadeFrustum(c),
                this._cascadeMaxExtents[c].subtractToRef(this._cascadeMinExtents[c], tmpv1),
                this._frustumCenter[c].addToRef(this._lightDirection.scale(this._cascadeMinExtents[c].z), this._shadowCameraPos[c]),
                Matrix.LookAtLHToRef(this._shadowCameraPos[c], this._frustumCenter[c], UpDir, this._viewMatrices[c]);
                var d = 0
                  , _ = tmpv1.z
                  , b = this._shadowCastersBoundingInfo;
                b.update(this._viewMatrices[c]),
                _ = Math.min(_, b.boundingBox.maximumWorld.z),
                !this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS ? d = Math.min(d, b.boundingBox.minimumWorld.z) : d = Math.max(d, b.boundingBox.minimumWorld.z),
                Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[c].x, this._cascadeMaxExtents[c].x, this._cascadeMinExtents[c].y, this._cascadeMaxExtents[c].y, s ? _ : d, s ? d : _, this._projectionMatrices[c], i.getEngine().isNDCHalfZRange),
                this._cascadeMinExtents[c].z = d,
                this._cascadeMaxExtents[c].z = _,
                this._viewMatrices[c].multiplyToRef(this._projectionMatrices[c], this._transformMatrices[c]),
                Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[c], 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[c].multiplyToRef(tmpMatrix, this._projectionMatrices[c]),
                this._viewMatrices[c].multiplyToRef(this._projectionMatrices[c], this._transformMatrices[c]),
                this._transformMatrices[c].copyToArray(this._transformMatricesAsArray, c * 16)
            }
        }
    }
    ,
    e.prototype._computeFrustumInWorldSpace = function(i) {
        if (!!this._scene.activeCamera) {
            var o = this._cascades[i].prevBreakDistance
              , s = this._cascades[i].breakDistance
              , c = this._scene.getEngine().isNDCHalfZRange;
            this._scene.activeCamera.getViewMatrix();
            for (var d = Matrix.Invert(this._scene.activeCamera.getTransformationMatrix()), _ = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0, b = 0; b < e.frustumCornersNDCSpace.length; ++b)
                tmpv1.copyFrom(e.frustumCornersNDCSpace[(b + _) % e.frustumCornersNDCSpace.length]),
                c && tmpv1.z === -1 && (tmpv1.z = 0),
                Vector3.TransformCoordinatesToRef(tmpv1, d, this._frustumCornersWorldSpace[i][b]);
            for (var b = 0; b < e.frustumCornersNDCSpace.length / 2; ++b)
                tmpv1.copyFrom(this._frustumCornersWorldSpace[i][b + 4]).subtractInPlace(this._frustumCornersWorldSpace[i][b]),
                tmpv2.copyFrom(tmpv1).scaleInPlace(o),
                tmpv1.scaleInPlace(s),
                tmpv1.addInPlace(this._frustumCornersWorldSpace[i][b]),
                this._frustumCornersWorldSpace[i][b + 4].copyFrom(tmpv1),
                this._frustumCornersWorldSpace[i][b].addInPlace(tmpv2)
        }
    }
    ,
    e.prototype._computeCascadeFrustum = function(i) {
        this._cascadeMinExtents[i].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE),
        this._cascadeMaxExtents[i].copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE),
        this._frustumCenter[i].copyFromFloats(0, 0, 0);
        var o = this._scene.activeCamera;
        if (!!o) {
            for (var s = 0; s < this._frustumCornersWorldSpace[i].length; ++s)
                this._frustumCenter[i].addInPlace(this._frustumCornersWorldSpace[i][s]);
            if (this._frustumCenter[i].scaleInPlace(1 / this._frustumCornersWorldSpace[i].length),
            this.stabilizeCascades) {
                for (var c = 0, s = 0; s < this._frustumCornersWorldSpace[i].length; ++s) {
                    var d = this._frustumCornersWorldSpace[i][s].subtractToRef(this._frustumCenter[i], tmpv1).length();
                    c = Math.max(c, d)
                }
                c = Math.ceil(c * 16) / 16,
                this._cascadeMaxExtents[i].copyFromFloats(c, c, c),
                this._cascadeMinExtents[i].copyFromFloats(-c, -c, -c)
            } else {
                var _ = this._frustumCenter[i];
                this._frustumCenter[i].addToRef(this._lightDirection, tmpv1),
                Matrix.LookAtLHToRef(_, tmpv1, UpDir, tmpMatrix);
                for (var s = 0; s < this._frustumCornersWorldSpace[i].length; ++s)
                    Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[i][s], tmpMatrix, tmpv1),
                    this._cascadeMinExtents[i].minimizeInPlace(tmpv1),
                    this._cascadeMaxExtents[i].maximizeInPlace(tmpv1)
            }
        }
    }
    ,
    e.prototype._recreateSceneUBOs = function() {
        if (this._disposeSceneUBOs(),
        this._sceneUBOs)
            for (var i = 0; i < this._numCascades; ++i)
                this._sceneUBOs.push(this._scene.createSceneUniformBuffer('Scene for CSM Shadow Generator (light "' + this._light.name + '" cascade #' + i + ")"))
    }
    ,
    Object.defineProperty(e, "IsSupported", {
        get: function() {
            var i = EngineStore.LastCreatedEngine;
            return i ? i._features.supportCSM : !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._initializeGenerator = function() {
        var i, o, s, c, d, _, b, k, j, $, _e, et, tt, rt, it, nt, ot, at, st, ut;
        this.penumbraDarkness = (i = this.penumbraDarkness) !== null && i !== void 0 ? i : 1,
        this._numCascades = (o = this._numCascades) !== null && o !== void 0 ? o : e.DEFAULT_CASCADES_COUNT,
        this.stabilizeCascades = (s = this.stabilizeCascades) !== null && s !== void 0 ? s : !1,
        this._freezeShadowCastersBoundingInfoObservable = (c = this._freezeShadowCastersBoundingInfoObservable) !== null && c !== void 0 ? c : null,
        this.freezeShadowCastersBoundingInfo = (d = this.freezeShadowCastersBoundingInfo) !== null && d !== void 0 ? d : !1,
        this._scbiMin = (_ = this._scbiMin) !== null && _ !== void 0 ? _ : new Vector3(0,0,0),
        this._scbiMax = (b = this._scbiMax) !== null && b !== void 0 ? b : new Vector3(0,0,0),
        this._shadowCastersBoundingInfo = (k = this._shadowCastersBoundingInfo) !== null && k !== void 0 ? k : new BoundingInfo(new Vector3(0,0,0),new Vector3(0,0,0)),
        this._breaksAreDirty = (j = this._breaksAreDirty) !== null && j !== void 0 ? j : !0,
        this._minDistance = ($ = this._minDistance) !== null && $ !== void 0 ? $ : 0,
        this._maxDistance = (_e = this._maxDistance) !== null && _e !== void 0 ? _e : 1,
        this._currentLayer = (et = this._currentLayer) !== null && et !== void 0 ? et : 0,
        this._shadowMaxZ = (it = (tt = this._shadowMaxZ) !== null && tt !== void 0 ? tt : (rt = this._scene.activeCamera) === null || rt === void 0 ? void 0 : rt.maxZ) !== null && it !== void 0 ? it : 1e4,
        this._debug = (nt = this._debug) !== null && nt !== void 0 ? nt : !1,
        this._depthClamp = (ot = this._depthClamp) !== null && ot !== void 0 ? ot : !0,
        this._cascadeBlendPercentage = (at = this._cascadeBlendPercentage) !== null && at !== void 0 ? at : .1,
        this._lambda = (st = this._lambda) !== null && st !== void 0 ? st : .5,
        this._autoCalcDepthBounds = (ut = this._autoCalcDepthBounds) !== null && ut !== void 0 ? ut : !1,
        this._recreateSceneUBOs(),
        a.prototype._initializeGenerator.call(this)
    }
    ,
    e.prototype._createTargetRenderTexture = function() {
        var i = this._scene.getEngine()
          , o = {
            width: this._mapSize,
            height: this._mapSize,
            layers: this.numCascades
        };
        this._shadowMap = new RenderTargetTexture(this._light.name + "_CSMShadowMap",o,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0),
        this._shadowMap.createDepthStencilTexture(i.useReverseDepthBuffer ? 516 : 513, !0)
    }
    ,
    e.prototype._initializeShadowMap = function() {
        var i = this;
        if (a.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 o = 0; o < this._numCascades; ++o) {
                this._cascades[o] = {
                    prevBreakDistance: 0,
                    breakDistance: 0
                },
                this._viewMatrices[o] = Matrix.Zero(),
                this._projectionMatrices[o] = Matrix.Zero(),
                this._transformMatrices[o] = Matrix.Zero(),
                this._cascadeMinExtents[o] = new Vector3,
                this._cascadeMaxExtents[o] = new Vector3,
                this._frustumCenter[o] = new Vector3,
                this._shadowCameraPos[o] = new Vector3,
                this._frustumCornersWorldSpace[o] = new Array(e.frustumCornersNDCSpace.length);
                for (var s = 0; s < e.frustumCornersNDCSpace.length; ++s)
                    this._frustumCornersWorldSpace[o][s] = new Vector3
            }
            var c = this._scene.getEngine();
            this._shadowMap.onBeforeBindObservable.clear(),
            this._shadowMap.onBeforeRenderObservable.clear(),
            this._shadowMap.onBeforeRenderObservable.add(function(d) {
                i._sceneUBOs && i._scene.setSceneUniformBuffer(i._sceneUBOs[d]),
                i._currentLayer = d,
                i._filter === ShadowGenerator.FILTER_PCF && c.setColorWrite(!1),
                i._scene.setTransformMatrix(i.getCascadeViewMatrix(d), i.getCascadeProjectionMatrix(d)),
                i._useUBO && (i._scene.getSceneUniformBuffer().unbindEffect(),
                i._scene.finalizeSceneUbo())
            }),
            this._shadowMap.onBeforeBindObservable.add(function() {
                var d;
                i._currentSceneUBO = i._scene.getSceneUniformBuffer(),
                (d = c._debugPushGroup) === null || d === void 0 || d.call(c, "cascaded shadow map generation for pass id " + c.currentRenderPassId, 1),
                i._breaksAreDirty && i._splitFrustum(),
                i._computeMatrices()
            }),
            this._splitFrustum()
        }
    }
    ,
    e.prototype._bindCustomEffectForRenderSubMeshForShadowMap = function(i, o, s) {
        o.setMatrix("viewProjection", this.getCascadeTransformMatrix(this._currentLayer))
    }
    ,
    e.prototype._isReadyCustomDefines = function(i, o, s) {
        i.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? "1" : "0"))
    }
    ,
    e.prototype.prepareDefines = function(i, o) {
        a.prototype.prepareDefines.call(this, i, o);
        var s = this._scene
          , c = this._light;
        if (!(!s.shadowsEnabled || !c.shadowEnabled)) {
            i["SHADOWCSM" + o] = !0,
            i["SHADOWCSMDEBUG" + o] = this.debug,
            i["SHADOWCSMNUM_CASCADES" + o] = this.numCascades,
            i["SHADOWCSM_RIGHTHANDED" + o] = s.useRightHandedSystem;
            var d = s.activeCamera;
            d && this._shadowMaxZ < d.maxZ && (i["SHADOWCSMUSESHADOWMAXZ" + o] = !0),
            this.cascadeBlendPercentage === 0 && (i["SHADOWCSMNOBLEND" + o] = !0)
        }
    }
    ,
    e.prototype.bindShadowLight = function(i, o) {
        var s = this._light
          , c = this._scene;
        if (!(!c.shadowsEnabled || !s.shadowEnabled)) {
            var d = c.activeCamera;
            if (!!d) {
                var _ = this.getShadowMap();
                if (!!_) {
                    var b = _.getSize().width;
                    if (o.setMatrices("lightMatrix" + i, this._transformMatricesAsArray),
                    o.setArray("viewFrustumZ" + i, this._viewSpaceFrustumsZ),
                    o.setFloat("cascadeBlendFactor" + i, this.cascadeBlendPercentage === 0 ? 1e4 : 1 / this.cascadeBlendPercentage),
                    o.setArray("frustumLengths" + i, this._frustumLengths),
                    this._filter === ShadowGenerator.FILTER_PCF)
                        o.setDepthStencilTexture("shadowSampler" + i, _),
                        s._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), b, 1 / b, this.frustumEdgeFalloff, i);
                    else if (this._filter === ShadowGenerator.FILTER_PCSS) {
                        for (var k = 0; k < this._numCascades; ++k)
                            this._lightSizeUVCorrection[k * 2 + 0] = k === 0 ? 1 : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[k].x - this._cascadeMinExtents[k].x),
                            this._lightSizeUVCorrection[k * 2 + 1] = k === 0 ? 1 : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[k].y - this._cascadeMinExtents[k].y),
                            this._depthCorrection[k] = k === 0 ? 1 : (this._cascadeMaxExtents[k].z - this._cascadeMinExtents[k].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z);
                        o.setDepthStencilTexture("shadowSampler" + i, _),
                        o.setTexture("depthSampler" + i, _),
                        o.setArray2("lightSizeUVCorrection" + i, this._lightSizeUVCorrection),
                        o.setArray("depthCorrection" + i, this._depthCorrection),
                        o.setFloat("penumbraDarkness" + i, this.penumbraDarkness),
                        s._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / b, this._contactHardeningLightSizeUVRatio * b, this.frustumEdgeFalloff, i)
                    } else
                        o.setTexture("shadowSampler" + i, _),
                        s._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), b, 1 / b, this.frustumEdgeFalloff, i);
                    s._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(d), this.getLight().getDepthMinZ(d) + this.getLight().getDepthMaxZ(d), i)
                }
            }
        }
    }
    ,
    e.prototype.getTransformMatrix = function() {
        return this.getCascadeTransformMatrix(0)
    }
    ,
    e.prototype.dispose = function() {
        a.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 i = a.prototype.serialize.call(this)
          , o = this.getShadowMap();
        if (!o)
            return i;
        if (i.numCascades = this._numCascades,
        i.debug = this._debug,
        i.stabilizeCascades = this.stabilizeCascades,
        i.lambda = this._lambda,
        i.cascadeBlendPercentage = this.cascadeBlendPercentage,
        i.depthClamp = this._depthClamp,
        i.autoCalcDepthBounds = this.autoCalcDepthBounds,
        i.shadowMaxZ = this._shadowMaxZ,
        i.penumbraDarkness = this.penumbraDarkness,
        i.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo,
        i.minDistance = this.minDistance,
        i.maxDistance = this.maxDistance,
        i.renderList = [],
        o.renderList)
            for (var s = 0; s < o.renderList.length; s++) {
                var c = o.renderList[s];
                i.renderList.push(c.id)
            }
        return i
    }
    ,
    e.Parse = function(i, o) {
        var s = ShadowGenerator.Parse(i, o, function(c, d) {
            return new e(c,d)
        });
        return i.numCascades !== void 0 && (s.numCascades = i.numCascades),
        i.debug !== void 0 && (s.debug = i.debug),
        i.stabilizeCascades !== void 0 && (s.stabilizeCascades = i.stabilizeCascades),
        i.lambda !== void 0 && (s.lambda = i.lambda),
        i.cascadeBlendPercentage !== void 0 && (s.cascadeBlendPercentage = i.cascadeBlendPercentage),
        i.depthClamp !== void 0 && (s.depthClamp = i.depthClamp),
        i.autoCalcDepthBounds !== void 0 && (s.autoCalcDepthBounds = i.autoCalcDepthBounds),
        i.shadowMaxZ !== void 0 && (s.shadowMaxZ = i.shadowMaxZ),
        i.penumbraDarkness !== void 0 && (s.penumbraDarkness = i.penumbraDarkness),
        i.freezeShadowCastersBoundingInfo !== void 0 && (s.freezeShadowCastersBoundingInfo = i.freezeShadowCastersBoundingInfo),
        i.minDistance !== void 0 && i.maxDistance !== void 0 && s.setMinMaxDistance(i.minDistance, i.maxDistance),
        s
    }
    ,
    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(i) {
        throw _WarnImport("ShadowGeneratorSceneComponent")
    }
    ,
    e
}(ShadowGenerator);
AbstractScene.AddParser(SceneComponentConstants.NAME_SHADOWGENERATOR, function(a, e) {
    if (a.shadowGenerators !== void 0 && a.shadowGenerators !== null)
        for (var i = 0, o = a.shadowGenerators.length; i < o; i++) {
            var s = a.shadowGenerators[i];
            s.className === CascadedShadowGenerator.CLASSNAME ? CascadedShadowGenerator.Parse(s, e) : ShadowGenerator.Parse(s, e)
        }
});
var ShadowGeneratorSceneComponent = function() {
    function a(e) {
        this.name = SceneComponentConstants.NAME_SHADOWGENERATOR,
        this.scene = e
    }
    return a.prototype.register = function() {
        this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets)
    }
    ,
    a.prototype.rebuild = function() {}
    ,
    a.prototype.serialize = function(e) {
        e.shadowGenerators = [];
        for (var i = this.scene.lights, o = 0, s = i; o < s.length; o++) {
            var c = s[o]
              , d = c.getShadowGenerator();
            d && e.shadowGenerators.push(d.serialize())
        }
    }
    ,
    a.prototype.addFromContainer = function(e) {}
    ,
    a.prototype.removeFromContainer = function(e, i) {}
    ,
    a.prototype.dispose = function() {}
    ,
    a.prototype._gatherRenderTargets = function(e) {
        var i = this.scene;
        if (this.scene.shadowsEnabled)
            for (var o = 0; o < i.lights.length; o++) {
                var s = i.lights[o]
                  , c = s.getShadowGenerator();
                if (s.isEnabled() && s.shadowEnabled && c) {
                    var d = c.getShadowMap();
                    i.textures.indexOf(d) !== -1 && e.push(d)
                }
            }
    }
    ,
    a
}();
ShadowGenerator._SceneComponentInitialization = function(a) {
    var e = a._getComponent(SceneComponentConstants.NAME_SHADOWGENERATOR);
    e || (e = new ShadowGeneratorSceneComponent(a),
    a._addComponent(e))
}
;
var DDS_MAGIC = 542327876
  , DDSD_MIPMAPCOUNT = 131072
  , DDSCAPS2_CUBEMAP = 512
  , DDPF_FOURCC = 4
  , DDPF_RGB = 64
  , DDPF_LUMINANCE = 131072;
function FourCCToInt32(a) {
    return a.charCodeAt(0) + (a.charCodeAt(1) << 8) + (a.charCodeAt(2) << 16) + (a.charCodeAt(3) << 24)
}
function Int32ToFourCC(a) {
    return String.fromCharCode(a & 255, a >> 8 & 255, a >> 16 & 255, a >> 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 a() {}
    return a.GetDDSInfo = function(e) {
        var i = new Int32Array(e.buffer,e.byteOffset,headerLengthInt)
          , o = new Int32Array(e.buffer,e.byteOffset,headerLengthInt + 4)
          , s = 1;
        i[off_flags] & DDSD_MIPMAPCOUNT && (s = Math.max(1, i[off_mipmapCount]));
        var c = i[off_pfFourCC]
          , d = c === FOURCC_DX10 ? o[off_dxgiFormat] : 0
          , _ = 0;
        switch (c) {
        case FOURCC_D3DFMT_R16G16B16A16F:
            _ = 2;
            break;
        case FOURCC_D3DFMT_R32G32B32A32F:
            _ = 1;
            break;
        case FOURCC_DX10:
            if (d === DXGI_FORMAT_R16G16B16A16_FLOAT) {
                _ = 2;
                break
            }
            if (d === DXGI_FORMAT_R32G32B32A32_FLOAT) {
                _ = 1;
                break
            }
        }
        return {
            width: i[off_width],
            height: i[off_height],
            mipmapCount: s,
            isFourCC: (i[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
            isRGB: (i[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
            isLuminance: (i[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
            isCube: (i[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
            isCompressed: c === FOURCC_DXT1 || c === FOURCC_DXT3 || c === FOURCC_DXT5,
            dxgiFormat: d,
            textureType: _
        }
    }
    ,
    a._GetHalfFloatAsFloatRGBAArrayBuffer = function(e, i, o, s, c, d) {
        for (var _ = new Float32Array(s), b = new Uint16Array(c,o), k = 0, j = 0; j < i; j++)
            for (var $ = 0; $ < e; $++) {
                var _e = ($ + j * e) * 4;
                _[k] = FromHalfFloat(b[_e]),
                _[k + 1] = FromHalfFloat(b[_e + 1]),
                _[k + 2] = FromHalfFloat(b[_e + 2]),
                a.StoreLODInAlphaChannel ? _[k + 3] = d : _[k + 3] = FromHalfFloat(b[_e + 3]),
                k += 4
            }
        return _
    }
    ,
    a._GetHalfFloatRGBAArrayBuffer = function(e, i, o, s, c, d) {
        if (a.StoreLODInAlphaChannel) {
            for (var _ = new Uint16Array(s), b = new Uint16Array(c,o), k = 0, j = 0; j < i; j++)
                for (var $ = 0; $ < e; $++) {
                    var _e = ($ + j * e) * 4;
                    _[k] = b[_e],
                    _[k + 1] = b[_e + 1],
                    _[k + 2] = b[_e + 2],
                    _[k + 3] = ToHalfFloat(d),
                    k += 4
                }
            return _
        }
        return new Uint16Array(c,o,s)
    }
    ,
    a._GetFloatRGBAArrayBuffer = function(e, i, o, s, c, d) {
        if (a.StoreLODInAlphaChannel) {
            for (var _ = new Float32Array(s), b = new Float32Array(c,o), k = 0, j = 0; j < i; j++)
                for (var $ = 0; $ < e; $++) {
                    var _e = ($ + j * e) * 4;
                    _[k] = b[_e],
                    _[k + 1] = b[_e + 1],
                    _[k + 2] = b[_e + 2],
                    _[k + 3] = d,
                    k += 4
                }
            return _
        }
        return new Float32Array(c,o,s)
    }
    ,
    a._GetFloatAsHalfFloatRGBAArrayBuffer = function(e, i, o, s, c, d) {
        for (var _ = new Uint16Array(s), b = new Float32Array(c,o), k = 0, j = 0; j < i; j++)
            for (var $ = 0; $ < e; $++)
                _[k] = ToHalfFloat(b[k]),
                _[k + 1] = ToHalfFloat(b[k + 1]),
                _[k + 2] = ToHalfFloat(b[k + 2]),
                a.StoreLODInAlphaChannel ? _[k + 3] = ToHalfFloat(d) : _[k + 3] = ToHalfFloat(b[k + 3]),
                k += 4;
        return _
    }
    ,
    a._GetFloatAsUIntRGBAArrayBuffer = function(e, i, o, s, c, d) {
        for (var _ = new Uint8Array(s), b = new Float32Array(c,o), k = 0, j = 0; j < i; j++)
            for (var $ = 0; $ < e; $++) {
                var _e = ($ + j * e) * 4;
                _[k] = Scalar.Clamp(b[_e]) * 255,
                _[k + 1] = Scalar.Clamp(b[_e + 1]) * 255,
                _[k + 2] = Scalar.Clamp(b[_e + 2]) * 255,
                a.StoreLODInAlphaChannel ? _[k + 3] = d : _[k + 3] = Scalar.Clamp(b[_e + 3]) * 255,
                k += 4
            }
        return _
    }
    ,
    a._GetHalfFloatAsUIntRGBAArrayBuffer = function(e, i, o, s, c, d) {
        for (var _ = new Uint8Array(s), b = new Uint16Array(c,o), k = 0, j = 0; j < i; j++)
            for (var $ = 0; $ < e; $++) {
                var _e = ($ + j * e) * 4;
                _[k] = Scalar.Clamp(FromHalfFloat(b[_e])) * 255,
                _[k + 1] = Scalar.Clamp(FromHalfFloat(b[_e + 1])) * 255,
                _[k + 2] = Scalar.Clamp(FromHalfFloat(b[_e + 2])) * 255,
                a.StoreLODInAlphaChannel ? _[k + 3] = d : _[k + 3] = Scalar.Clamp(FromHalfFloat(b[_e + 3])) * 255,
                k += 4
            }
        return _
    }
    ,
    a._GetRGBAArrayBuffer = function(e, i, o, s, c, d, _, b, k) {
        for (var j = new Uint8Array(s), $ = new Uint8Array(c,o), _e = 0, et = 0; et < i; et++)
            for (var tt = 0; tt < e; tt++) {
                var rt = (tt + et * e) * 4;
                j[_e] = $[rt + d],
                j[_e + 1] = $[rt + _],
                j[_e + 2] = $[rt + b],
                j[_e + 3] = $[rt + k],
                _e += 4
            }
        return j
    }
    ,
    a._ExtractLongWordOrder = function(e) {
        return e === 0 || e === 255 || e === -16777216 ? 0 : 1 + a._ExtractLongWordOrder(e >> 8)
    }
    ,
    a._GetRGBArrayBuffer = function(e, i, o, s, c, d, _, b) {
        for (var k = new Uint8Array(s), j = new Uint8Array(c,o), $ = 0, _e = 0; _e < i; _e++)
            for (var et = 0; et < e; et++) {
                var tt = (et + _e * e) * 3;
                k[$] = j[tt + d],
                k[$ + 1] = j[tt + _],
                k[$ + 2] = j[tt + b],
                $ += 3
            }
        return k
    }
    ,
    a._GetLuminanceArrayBuffer = function(e, i, o, s, c) {
        for (var d = new Uint8Array(s), _ = new Uint8Array(c,o), b = 0, k = 0; k < i; k++)
            for (var j = 0; j < e; j++) {
                var $ = j + k * e;
                d[b] = _[$],
                b++
            }
        return d
    }
    ,
    a.UploadDDSLevels = function(e, i, o, s, c, d, _, b, k) {
        _ === void 0 && (_ = -1),
        k === void 0 && (k = !0);
        var j = null;
        s.sphericalPolynomial && (j = new Array);
        var $ = !!e.getCaps().s3tc;
        i.generateMipMaps = c;
        var _e = new Int32Array(o.buffer,o.byteOffset,headerLengthInt), et, tt, rt, it = 0, nt, ot, at, st, ut = 0, ct = 1;
        if (_e[off_magic] !== DDS_MAGIC) {
            Logger$2.Error("Invalid magic number in DDS header");
            return
        }
        if (!s.isFourCC && !s.isRGB && !s.isLuminance) {
            Logger$2.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
            return
        }
        if (s.isCompressed && !$) {
            Logger$2.Error("Compressed textures are not supported on this platform.");
            return
        }
        var lt = _e[off_RGBbpp];
        nt = _e[off_size] + 4;
        var ft = !1;
        if (s.isFourCC)
            switch (et = _e[off_pfFourCC],
            et) {
            case FOURCC_DXT1:
                ct = 8,
                ut = 33777;
                break;
            case FOURCC_DXT3:
                ct = 16,
                ut = 33778;
                break;
            case FOURCC_DXT5:
                ct = 16,
                ut = 33779;
                break;
            case FOURCC_D3DFMT_R16G16B16A16F:
                ft = !0;
                break;
            case FOURCC_D3DFMT_R32G32B32A32F:
                ft = !0;
                break;
            case FOURCC_DX10:
                nt += 5 * 4;
                var ht = !1;
                switch (s.dxgiFormat) {
                case DXGI_FORMAT_R16G16B16A16_FLOAT:
                case DXGI_FORMAT_R32G32B32A32_FLOAT:
                    ft = !0,
                    ht = !0;
                    break;
                case DXGI_FORMAT_B8G8R8X8_UNORM:
                    s.isRGB = !0,
                    s.isFourCC = !1,
                    lt = 32,
                    ht = !0;
                    break
                }
                if (ht)
                    break;
            default:
                console.error("Unsupported FourCC code:", Int32ToFourCC(et));
                return
            }
        var pt = a._ExtractLongWordOrder(_e[off_RMask])
          , dt = a._ExtractLongWordOrder(_e[off_GMask])
          , _t = a._ExtractLongWordOrder(_e[off_BMask])
          , mt = a._ExtractLongWordOrder(_e[off_AMask]);
        ft && (ut = e._getRGBABufferInternalSizedFormat(s.textureType)),
        at = 1,
        _e[off_flags] & DDSD_MIPMAPCOUNT && c !== !1 && (at = Math.max(1, _e[off_mipmapCount]));
        for (var vt = b || 0, yt = e.getCaps(), Et = vt; Et < d; Et++) {
            for (tt = _e[off_width],
            rt = _e[off_height],
            st = 0; st < at; ++st) {
                if (_ === -1 || _ === st) {
                    var At = _ === -1 ? st : 0;
                    if (!s.isCompressed && s.isFourCC) {
                        i.format = 5,
                        it = tt * rt * 4;
                        var gt = null;
                        if (e._badOS || e._badDesktopOS || !yt.textureHalfFloat && !yt.textureFloat)
                            lt === 128 ? (gt = a._GetFloatAsUIntRGBAArrayBuffer(tt, rt, o.byteOffset + nt, it, o.buffer, At),
                            j && At == 0 && j.push(a._GetFloatRGBAArrayBuffer(tt, rt, o.byteOffset + nt, it, o.buffer, At))) : lt === 64 && (gt = a._GetHalfFloatAsUIntRGBAArrayBuffer(tt, rt, o.byteOffset + nt, it, o.buffer, At),
                            j && At == 0 && j.push(a._GetHalfFloatAsFloatRGBAArrayBuffer(tt, rt, o.byteOffset + nt, it, o.buffer, At))),
                            i.type = 0;
                        else {
                            var St = yt.textureFloat && (k && yt.textureFloatLinearFiltering || !k)
                              , xt = yt.textureHalfFloat && (k && yt.textureHalfFloatLinearFiltering || !k)
                              , bt = (lt === 128 || lt === 64 && !xt) && St ? 1 : (lt === 64 || lt === 128 && !St) && xt ? 2 : 0
                              , Rt = void 0
                              , Mt = null;
                            switch (lt) {
                            case 128:
                                {
                                    switch (bt) {
                                    case 1:
                                        Rt = a._GetFloatRGBAArrayBuffer,
                                        Mt = null;
                                        break;
                                    case 2:
                                        Rt = a._GetFloatAsHalfFloatRGBAArrayBuffer,
                                        Mt = a._GetFloatRGBAArrayBuffer;
                                        break;
                                    case 0:
                                        Rt = a._GetFloatAsUIntRGBAArrayBuffer,
                                        Mt = a._GetFloatRGBAArrayBuffer;
                                        break
                                    }
                                    break
                                }
                            default:
                                {
                                    switch (bt) {
                                    case 1:
                                        Rt = a._GetHalfFloatAsFloatRGBAArrayBuffer,
                                        Mt = null;
                                        break;
                                    case 2:
                                        Rt = a._GetHalfFloatRGBAArrayBuffer,
                                        Mt = a._GetHalfFloatAsFloatRGBAArrayBuffer;
                                        break;
                                    case 0:
                                        Rt = a._GetHalfFloatAsUIntRGBAArrayBuffer,
                                        Mt = a._GetHalfFloatAsFloatRGBAArrayBuffer;
                                        break
                                    }
                                    break
                                }
                            }
                            i.type = bt,
                            gt = Rt(tt, rt, o.byteOffset + nt, it, o.buffer, At),
                            j && At == 0 && j.push(Mt ? Mt(tt, rt, o.byteOffset + nt, it, o.buffer, At) : gt)
                        }
                        gt && e._uploadDataToTextureDirectly(i, gt, Et, At)
                    } else if (s.isRGB)
                        i.type = 0,
                        lt === 24 ? (i.format = 4,
                        it = tt * rt * 3,
                        ot = a._GetRGBArrayBuffer(tt, rt, o.byteOffset + nt, it, o.buffer, pt, dt, _t),
                        e._uploadDataToTextureDirectly(i, ot, Et, At)) : (i.format = 5,
                        it = tt * rt * 4,
                        ot = a._GetRGBAArrayBuffer(tt, rt, o.byteOffset + nt, it, o.buffer, pt, dt, _t, mt),
                        e._uploadDataToTextureDirectly(i, ot, Et, At));
                    else if (s.isLuminance) {
                        var Pt = e._getUnpackAlignement()
                          , It = tt
                          , Dt = Math.floor((tt + Pt - 1) / Pt) * Pt;
                        it = Dt * (rt - 1) + It,
                        ot = a._GetLuminanceArrayBuffer(tt, rt, o.byteOffset + nt, it, o.buffer),
                        i.format = 1,
                        i.type = 0,
                        e._uploadDataToTextureDirectly(i, ot, Et, At)
                    } else
                        it = Math.max(4, tt) / 4 * Math.max(4, rt) / 4 * ct,
                        ot = new Uint8Array(o.buffer,o.byteOffset + nt,it),
                        i.type = 0,
                        e._uploadCompressedDataToTextureDirectly(i, ut, tt, rt, ot, Et, At)
                }
                nt += lt ? tt * rt * (lt / 8) : it,
                tt *= .5,
                rt *= .5,
                tt = Math.max(1, tt),
                rt = Math.max(1, rt)
            }
            if (b !== void 0)
                break
        }
        j && j.length > 0 ? s.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
            size: _e[off_width],
            right: j[0],
            left: j[1],
            up: j[2],
            down: j[3],
            front: j[4],
            back: j[5],
            format: 5,
            type: 1,
            gammaSpace: !1
        }) : s.sphericalPolynomial = void 0
    }
    ,
    a.StoreLODInAlphaChannel = !1,
    a
}();
ThinEngine.prototype.createPrefilteredCubeTexture = function(a, e, i, o, s, c, d, _, b) {
    var k = this;
    s === void 0 && (s = null),
    c === void 0 && (c = null),
    _ === void 0 && (_ = null),
    b === void 0 && (b = !0);
    var j = function($) {
        if (!$) {
            s && s(null);
            return
        }
        var _e = $.texture;
        if (b ? $.info.sphericalPolynomial && (_e._sphericalPolynomial = $.info.sphericalPolynomial) : _e._sphericalPolynomial = new SphericalPolynomial,
        _e._source = InternalTextureSource.CubePrefiltered,
        k.getCaps().textureLOD) {
            s && s(_e);
            return
        }
        var et = 3
          , tt = k._gl
          , rt = $.width;
        if (!!rt) {
            for (var it = [], nt = 0; nt < et; nt++) {
                var ot = nt / (et - 1)
                  , at = 1 - ot
                  , st = o
                  , ut = Scalar.Log2(rt) * i + o
                  , ct = st + (ut - st) * at
                  , lt = Math.round(Math.min(Math.max(ct, 0), ut))
                  , ft = new InternalTexture(k,InternalTextureSource.Temp);
                if (ft.type = _e.type,
                ft.format = _e.format,
                ft.width = Math.pow(2, Math.max(Scalar.Log2(rt) - lt, 0)),
                ft.height = ft.width,
                ft.isCube = !0,
                ft._cachedWrapU = 0,
                ft._cachedWrapV = 0,
                k._bindTextureDirectly(tt.TEXTURE_CUBE_MAP, ft, !0),
                ft.samplingMode = 2,
                tt.texParameteri(tt.TEXTURE_CUBE_MAP, tt.TEXTURE_MAG_FILTER, tt.LINEAR),
                tt.texParameteri(tt.TEXTURE_CUBE_MAP, tt.TEXTURE_MIN_FILTER, tt.LINEAR),
                tt.texParameteri(tt.TEXTURE_CUBE_MAP, tt.TEXTURE_WRAP_S, tt.CLAMP_TO_EDGE),
                tt.texParameteri(tt.TEXTURE_CUBE_MAP, tt.TEXTURE_WRAP_T, tt.CLAMP_TO_EDGE),
                $.isDDS) {
                    var ht = $.info
                      , pt = $.data;
                    k._unpackFlipY(ht.isCompressed),
                    DDSTools.UploadDDSLevels(k, ft, pt, ht, !0, 6, lt)
                } else
                    Logger$2.Warn("DDS is the only prefiltered cube map supported so far.");
                k._bindTextureDirectly(tt.TEXTURE_CUBE_MAP, null);
                var dt = new BaseTexture(e);
                dt.isCube = !0,
                dt._texture = ft,
                ft.isReady = !0,
                it.push(dt)
            }
            _e._lodTextureHigh = it[2],
            _e._lodTextureMid = it[1],
            _e._lodTextureLow = it[0],
            s && s(_e)
        }
    };
    return this.createCubeTexture(a, e, null, !1, j, c, d, _, b, i, o)
}
;
var _DDSTextureLoader = function() {
    function a() {
        this.supportCascades = !0
    }
    return a.prototype.canLoad = function(e) {
        return EndsWith(e, ".dds")
    }
    ,
    a.prototype.loadCubeData = function(e, i, o, s, c) {
        var d = i.getEngine(), _, b = !1;
        if (Array.isArray(e))
            for (var k = 0; k < e.length; k++) {
                var j = e[k];
                _ = DDSTools.GetDDSInfo(j),
                i.width = _.width,
                i.height = _.height,
                b = (_.isRGB || _.isLuminance || _.mipmapCount > 1) && i.generateMipMaps,
                d._unpackFlipY(_.isCompressed),
                DDSTools.UploadDDSLevels(d, i, j, _, b, 6, -1, k),
                !_.isFourCC && _.mipmapCount === 1 && d.generateMipMapsForCubemap(i)
            }
        else {
            var $ = e;
            _ = DDSTools.GetDDSInfo($),
            i.width = _.width,
            i.height = _.height,
            o && (_.sphericalPolynomial = new SphericalPolynomial),
            b = (_.isRGB || _.isLuminance || _.mipmapCount > 1) && i.generateMipMaps,
            d._unpackFlipY(_.isCompressed),
            DDSTools.UploadDDSLevels(d, i, $, _, b, 6),
            !_.isFourCC && _.mipmapCount === 1 && d.generateMipMapsForCubemap(i, !1)
        }
        d._setCubeMapTextureParams(i, b),
        i.isReady = !0,
        i.onLoadedObservable.notifyObservers(i),
        i.onLoadedObservable.clear(),
        s && s({
            isDDS: !0,
            width: i.width,
            info: _,
            data: e,
            texture: i
        })
    }
    ,
    a.prototype.loadData = function(e, i, o) {
        var s = DDSTools.GetDDSInfo(e)
          , c = (s.isRGB || s.isLuminance || s.mipmapCount > 1) && i.generateMipMaps && s.width >> s.mipmapCount - 1 === 1;
        o(s.width, s.height, c, s.isFourCC, function() {
            DDSTools.UploadDDSLevels(i.getEngine(), i, e, s, c, 1)
        })
    }
    ,
    a
}();
Engine._TextureLoaders.push(new _DDSTextureLoader);
var MirrorTexture = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d, _, b) {
        d === void 0 && (d = 0),
        _ === void 0 && (_ = Texture.BILINEAR_SAMPLINGMODE),
        b === void 0 && (b = !0);
        var k = a.call(this, i, o, s, c, !0, d, !1, _, b) || this;
        k.scene = s,
        k.mirrorPlane = new Plane(0,1,0,1),
        k._transformMatrix = Matrix.Zero(),
        k._mirrorMatrix = Matrix.Zero(),
        k._adaptiveBlurKernel = 0,
        k._blurKernelX = 0,
        k._blurKernelY = 0,
        k._blurRatio = 1,
        k.ignoreCameraViewport = !0,
        k._updateGammaSpace(),
        k._imageProcessingConfigChangeObserver = s.imageProcessingConfiguration.onUpdateParameters.add(function() {
            k._updateGammaSpace()
        });
        var j = k.getScene().getEngine();
        j.supportsUniformBuffers && (k._sceneUBO = s.createSceneUniformBuffer('Scene for Mirror Texture (name "' + i + '")')),
        k.onBeforeBindObservable.add(function() {
            var _e;
            (_e = j._debugPushGroup) === null || _e === void 0 || _e.call(j, "mirror generation for " + i, 1)
        }),
        k.onAfterUnbindObservable.add(function() {
            var _e;
            (_e = j._debugPopGroup) === null || _e === void 0 || _e.call(j, 1)
        });
        var $;
        return k.onBeforeRenderObservable.add(function() {
            k._sceneUBO && (k._currentSceneUBO = s.getSceneUniformBuffer(),
            s.setSceneUniformBuffer(k._sceneUBO),
            s.getSceneUniformBuffer().unbindEffect()),
            Matrix.ReflectionToRef(k.mirrorPlane, k._mirrorMatrix),
            k._mirrorMatrix.multiplyToRef(s.getViewMatrix(), k._transformMatrix),
            s.setTransformMatrix(k._transformMatrix, s.getProjectionMatrix()),
            $ = s.clipPlane,
            s.clipPlane = k.mirrorPlane,
            s.getEngine().cullBackFaces = !1,
            s._mirroredCameraPosition = Vector3.TransformCoordinates(s.activeCamera.globalPosition, k._mirrorMatrix)
        }),
        k.onAfterRenderObservable.add(function() {
            k._sceneUBO && s.setSceneUniformBuffer(k._currentSceneUBO),
            s.updateTransformMatrix(),
            s.getEngine().cullBackFaces = null,
            s._mirroredCameraPosition = null,
            s.clipPlane = $
        }),
        k
    }
    return Object.defineProperty(e.prototype, "blurRatio", {
        get: function() {
            return this._blurRatio
        },
        set: function(i) {
            this._blurRatio !== i && (this._blurRatio = i,
            this._preparePostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "adaptiveBlurKernel", {
        set: function(i) {
            this._adaptiveBlurKernel = i,
            this._autoComputeBlurKernel()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blurKernel", {
        set: function(i) {
            this.blurKernelX = i,
            this.blurKernelY = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blurKernelX", {
        get: function() {
            return this._blurKernelX
        },
        set: function(i) {
            this._blurKernelX !== i && (this._blurKernelX = i,
            this._preparePostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blurKernelY", {
        get: function() {
            return this._blurKernelY
        },
        set: function(i) {
            this._blurKernelY !== i && (this._blurKernelY = i,
            this._preparePostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._autoComputeBlurKernel = function() {
        var i = this.getScene().getEngine()
          , o = this.getRenderWidth() / i.getRenderWidth()
          , s = this.getRenderHeight() / i.getRenderHeight();
        this.blurKernelX = this._adaptiveBlurKernel * o,
        this.blurKernelY = this._adaptiveBlurKernel * s
    }
    ,
    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 i = this.getScene().getEngine()
              , o = i.getCaps().textureFloatRender && i.getCaps().textureFloatLinearFiltering ? 1 : 2;
            this._blurX = new BlurPostProcess("horizontal blur",new Vector2(1,0),this._blurKernelX,this._blurRatio,null,Texture.BILINEAR_SAMPLINGMODE,i,!1,o),
            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,i,!1,o),
            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 i = this.getScene();
        if (!i)
            return this;
        var o = this.getSize()
          , s = new e(this.name,o.width,i,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);
        return s.hasAlpha = this.hasAlpha,
        s.level = this.level,
        s.mirrorPlane = this.mirrorPlane.clone(),
        this.renderList && (s.renderList = this.renderList.slice(0)),
        s
    }
    ,
    e.prototype.serialize = function() {
        if (!this.name)
            return null;
        var i = a.prototype.serialize.call(this);
        return i.mirrorPlane = this.mirrorPlane.asArray(),
        i
    }
    ,
    e.prototype.dispose = function() {
        var i;
        a.prototype.dispose.call(this),
        this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),
        (i = this._sceneUBO) === null || i === void 0 || i.dispose()
    }
    ,
    e
}(RenderTargetTexture);
Texture._CreateMirror = function(a, e, i, o) {
    return new MirrorTexture(a,e,i,o)
}
;
var name$7 = "backgroundFragmentDeclaration"
  , shader$7 = ` 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$7] = shader$7;
var name$6 = "backgroundUboDeclaration"
  , shader$6 = `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$6] = shader$6;
var name$5 = "backgroundPixelShader"
  , shader$5 = `#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$5] = shader$5;
var name$4 = "backgroundVertexDeclaration"
  , shader$4 = `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$4] = shader$4;
var name$3 = "backgroundVertexShader"
  , shader$3 = `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$3] = shader$3;
var BackgroundMaterialDefines = function(a) {
    __extends(e, a);
    function e() {
        var i = a.call(this) || this;
        return i.DIFFUSE = !1,
        i.DIFFUSEDIRECTUV = 0,
        i.GAMMADIFFUSE = !1,
        i.DIFFUSEHASALPHA = !1,
        i.OPACITYFRESNEL = !1,
        i.REFLECTIONBLUR = !1,
        i.REFLECTIONFRESNEL = !1,
        i.REFLECTIONFALLOFF = !1,
        i.TEXTURELODSUPPORT = !1,
        i.PREMULTIPLYALPHA = !1,
        i.USERGBCOLOR = !1,
        i.USEHIGHLIGHTANDSHADOWCOLORS = !1,
        i.BACKMAT_SHADOWONLY = !1,
        i.NOISE = !1,
        i.REFLECTIONBGR = !1,
        i.IMAGEPROCESSING = !1,
        i.VIGNETTE = !1,
        i.VIGNETTEBLENDMODEMULTIPLY = !1,
        i.VIGNETTEBLENDMODEOPAQUE = !1,
        i.TONEMAPPING = !1,
        i.TONEMAPPING_ACES = !1,
        i.CONTRAST = !1,
        i.COLORCURVES = !1,
        i.COLORGRADING = !1,
        i.COLORGRADING3D = !1,
        i.SAMPLER3DGREENDEPTH = !1,
        i.SAMPLER3DBGRMAP = !1,
        i.IMAGEPROCESSINGPOSTPROCESS = !1,
        i.SKIPFINALCOLORCLAMP = !1,
        i.EXPOSURE = !1,
        i.MULTIVIEW = !1,
        i.REFLECTION = !1,
        i.REFLECTIONMAP_3D = !1,
        i.REFLECTIONMAP_SPHERICAL = !1,
        i.REFLECTIONMAP_PLANAR = !1,
        i.REFLECTIONMAP_CUBIC = !1,
        i.REFLECTIONMAP_PROJECTION = !1,
        i.REFLECTIONMAP_SKYBOX = !1,
        i.REFLECTIONMAP_EXPLICIT = !1,
        i.REFLECTIONMAP_EQUIRECTANGULAR = !1,
        i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
        i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
        i.INVERTCUBICMAP = !1,
        i.REFLECTIONMAP_OPPOSITEZ = !1,
        i.LODINREFLECTIONALPHA = !1,
        i.GAMMAREFLECTION = !1,
        i.RGBDREFLECTION = !1,
        i.EQUIRECTANGULAR_RELFECTION_FOV = !1,
        i.MAINUV1 = !1,
        i.MAINUV2 = !1,
        i.UV1 = !1,
        i.UV2 = !1,
        i.CLIPPLANE = !1,
        i.CLIPPLANE2 = !1,
        i.CLIPPLANE3 = !1,
        i.CLIPPLANE4 = !1,
        i.CLIPPLANE5 = !1,
        i.CLIPPLANE6 = !1,
        i.POINTSIZE = !1,
        i.FOG = !1,
        i.NORMAL = !1,
        i.NUM_BONE_INFLUENCERS = 0,
        i.BonesPerMesh = 0,
        i.INSTANCES = !1,
        i.SHADOWFLOAT = !1,
        i.LOGARITHMICDEPTH = !1,
        i.NONUNIFORMSCALING = !1,
        i.ALPHATEST = !1,
        i.rebuild(),
        i
    }
    return e
}(MaterialDefines)
  , BackgroundMaterial = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i, o) || this;
        return s.primaryColor = Color3.White(),
        s._primaryColorShadowLevel = 0,
        s._primaryColorHighlightLevel = 0,
        s.reflectionTexture = null,
        s.reflectionBlur = 0,
        s.diffuseTexture = null,
        s._shadowLights = null,
        s.shadowLights = null,
        s.shadowLevel = 0,
        s.sceneCenter = Vector3.Zero(),
        s.opacityFresnel = !0,
        s.reflectionFresnel = !1,
        s.reflectionFalloffDistance = 0,
        s.reflectionAmount = 1,
        s.reflectionReflectance0 = .05,
        s.reflectionReflectance90 = .5,
        s.useRGBColor = !0,
        s.enableNoise = !1,
        s._fovMultiplier = 1,
        s.useEquirectangularFOV = !1,
        s._maxSimultaneousLights = 4,
        s.maxSimultaneousLights = 4,
        s._shadowOnly = !1,
        s.shadowOnly = !1,
        s._imageProcessingObserver = null,
        s.switchToBGR = !1,
        s._renderTargets = new SmartArray(16),
        s._reflectionControls = Vector4.Zero(),
        s._white = Color3.White(),
        s._primaryShadowColor = Color3.Black(),
        s._primaryHighlightColor = Color3.Black(),
        s._attachImageProcessingConfiguration(null),
        s.getRenderTargetTextures = function() {
            return s._renderTargets.reset(),
            s._diffuseTexture && s._diffuseTexture.isRenderTarget && s._renderTargets.push(s._diffuseTexture),
            s._reflectionTexture && s._reflectionTexture.isRenderTarget && s._renderTargets.push(s._reflectionTexture),
            s._renderTargets
        }
        ,
        s
    }
    return Object.defineProperty(e.prototype, "_perceptualColor", {
        get: function() {
            return this.__perceptualColor
        },
        set: function(i) {
            this.__perceptualColor = i,
            this._computePrimaryColorFromPerceptualColor(),
            this._markAllSubMeshesAsLightsDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "primaryColorShadowLevel", {
        get: function() {
            return this._primaryColorShadowLevel
        },
        set: function(i) {
            this._primaryColorShadowLevel = i,
            this._computePrimaryColors(),
            this._markAllSubMeshesAsLightsDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "primaryColorHighlightLevel", {
        get: function() {
            return this._primaryColorHighlightLevel
        },
        set: function(i) {
            this._primaryColorHighlightLevel = i,
            this._computePrimaryColors(),
            this._markAllSubMeshesAsLightsDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "reflectionStandardFresnelWeight", {
        set: function(i) {
            var o = i;
            o < .5 ? (o = o * 2,
            this.reflectionReflectance0 = e.StandardReflectance0 * o,
            this.reflectionReflectance90 = e.StandardReflectance90 * o) : (o = o * 2 - 1,
            this.reflectionReflectance0 = e.StandardReflectance0 + (1 - e.StandardReflectance0) * o,
            this.reflectionReflectance90 = e.StandardReflectance90 + (1 - e.StandardReflectance90) * o)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fovMultiplier", {
        get: function() {
            return this._fovMultiplier
        },
        set: function(i) {
            isNaN(i) && (i = 1),
            this._fovMultiplier = Math.max(0, Math.min(2, i))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachImageProcessingConfiguration = function(i) {
        var o = this;
        i !== this._imageProcessingConfiguration && (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        i ? this._imageProcessingConfiguration = i : this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration,
        this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
            o._computePrimaryColorFromPerceptualColor(),
            o._markAllSubMeshesAsImageProcessingDirty()
        })))
    }
    ,
    Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(i) {
            this._attachImageProcessingConfiguration(i),
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurvesEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurvesEnabled
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorCurvesEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingEnabled
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorGradingEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraToneMappingEnabled", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingEnabled
        },
        set: function(i) {
            this._imageProcessingConfiguration.toneMappingEnabled = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraExposure", {
        get: function() {
            return this._imageProcessingConfiguration.exposure
        },
        set: function(i) {
            this._imageProcessingConfiguration.exposure = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraContrast", {
        get: function() {
            return this._imageProcessingConfiguration.contrast
        },
        set: function(i) {
            this._imageProcessingConfiguration.contrast = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingTexture", {
        get: function() {
            return this._imageProcessingConfiguration.colorGradingTexture
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorGradingTexture = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurves", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurves
        },
        set: function(i) {
            this.imageProcessingConfiguration.colorCurves = i
        },
        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(i, o, s) {
        if (s === void 0 && (s = !1),
        o.effect && this.isFrozen && o.effect._wasPreviouslyReady)
            return !0;
        o.materialDefines || (o.materialDefines = new BackgroundMaterialDefines);
        var c = this.getScene()
          , d = o.materialDefines;
        if (this._isReadyForSubMesh(o))
            return !0;
        var _ = c.getEngine();
        if (MaterialHelper.PrepareDefinesForLights(c, i, d, !1, this._maxSimultaneousLights),
        d._needNormals = !0,
        MaterialHelper.PrepareDefinesForMultiview(c, d),
        d._areTexturesDirty) {
            if (d._needUVs = !1,
            c.texturesEnabled) {
                if (c.getEngine().getCaps().textureLOD && (d.TEXTURELODSUPPORT = !0),
                this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {
                    if (!this._diffuseTexture.isReadyOrNotBlocking())
                        return !1;
                    MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, d, "DIFFUSE"),
                    d.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha,
                    d.GAMMADIFFUSE = this._diffuseTexture.gammaSpace,
                    d.OPACITYFRESNEL = this._opacityFresnel
                } else
                    d.DIFFUSE = !1,
                    d.DIFFUSEHASALPHA = !1,
                    d.GAMMADIFFUSE = !1,
                    d.OPACITYFRESNEL = !1;
                var b = this._reflectionTexture;
                if (b && MaterialFlags.ReflectionTextureEnabled) {
                    if (!b.isReadyOrNotBlocking())
                        return !1;
                    switch (d.REFLECTION = !0,
                    d.GAMMAREFLECTION = b.gammaSpace,
                    d.RGBDREFLECTION = b.isRGBD,
                    d.REFLECTIONBLUR = this._reflectionBlur > 0,
                    d.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !b.invertZ : b.invertZ,
                    d.LODINREFLECTIONALPHA = b.lodLevelInAlpha,
                    d.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV,
                    d.REFLECTIONBGR = this.switchToBGR,
                    b.coordinatesMode === Texture.INVCUBIC_MODE && (d.INVERTCUBICMAP = !0),
                    d.REFLECTIONMAP_3D = b.isCube,
                    b.coordinatesMode) {
                    case Texture.EXPLICIT_MODE:
                        d.REFLECTIONMAP_EXPLICIT = !0;
                        break;
                    case Texture.PLANAR_MODE:
                        d.REFLECTIONMAP_PLANAR = !0;
                        break;
                    case Texture.PROJECTION_MODE:
                        d.REFLECTIONMAP_PROJECTION = !0;
                        break;
                    case Texture.SKYBOX_MODE:
                        d.REFLECTIONMAP_SKYBOX = !0;
                        break;
                    case Texture.SPHERICAL_MODE:
                        d.REFLECTIONMAP_SPHERICAL = !0;
                        break;
                    case Texture.EQUIRECTANGULAR_MODE:
                        d.REFLECTIONMAP_EQUIRECTANGULAR = !0;
                        break;
                    case Texture.FIXED_EQUIRECTANGULAR_MODE:
                        d.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !0;
                        break;
                    case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                        d.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !0;
                        break;
                    case Texture.CUBIC_MODE:
                    case Texture.INVCUBIC_MODE:
                    default:
                        d.REFLECTIONMAP_CUBIC = !0;
                        break
                    }
                    this.reflectionFresnel ? (d.REFLECTIONFRESNEL = !0,
                    d.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) : (d.REFLECTIONFRESNEL = !1,
                    d.REFLECTIONFALLOFF = !1)
                } else
                    d.REFLECTION = !1,
                    d.REFLECTIONFRESNEL = !1,
                    d.REFLECTIONFALLOFF = !1,
                    d.REFLECTIONBLUR = !1,
                    d.REFLECTIONMAP_3D = !1,
                    d.REFLECTIONMAP_SPHERICAL = !1,
                    d.REFLECTIONMAP_PLANAR = !1,
                    d.REFLECTIONMAP_CUBIC = !1,
                    d.REFLECTIONMAP_PROJECTION = !1,
                    d.REFLECTIONMAP_SKYBOX = !1,
                    d.REFLECTIONMAP_EXPLICIT = !1,
                    d.REFLECTIONMAP_EQUIRECTANGULAR = !1,
                    d.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
                    d.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
                    d.INVERTCUBICMAP = !1,
                    d.REFLECTIONMAP_OPPOSITEZ = !1,
                    d.LODINREFLECTIONALPHA = !1,
                    d.GAMMAREFLECTION = !1,
                    d.RGBDREFLECTION = !1
            }
            d.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8,
            d.USERGBCOLOR = this._useRGBColor,
            d.NOISE = this._enableNoise
        }
        if (d._areLightsDirty && (d.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0),
        d.BACKMAT_SHADOWONLY = this._shadowOnly),
        d._areImageProcessingDirty && this._imageProcessingConfiguration) {
            if (!this._imageProcessingConfiguration.isReady())
                return !1;
            this._imageProcessingConfiguration.prepareDefines(d)
        }
        if (MaterialHelper.PrepareDefinesForMisc(i, c, !1, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(i), d),
        MaterialHelper.PrepareDefinesForFrameBoundValues(c, _, d, s, null, o.getRenderingMesh().hasThinInstances),
        MaterialHelper.PrepareDefinesForAttributes(i, d, !1, !0, !1) && i && !c.getEngine().getCaps().standardDerivatives && !i.isVerticesDataPresent(VertexBuffer.NormalKind) && (i.createNormals(!0),
        Logger$2.Warn("BackgroundMaterial: Normals have been created for the mesh: " + i.name)),
        d.isDirty) {
            d.markAsProcessed(),
            c.resetCachedMaterial();
            var k = new EffectFallbacks;
            d.FOG && k.addFallback(0, "FOG"),
            d.POINTSIZE && k.addFallback(1, "POINTSIZE"),
            d.MULTIVIEW && k.addFallback(0, "MULTIVIEW"),
            MaterialHelper.HandleFallbacksForShadows(d, k, this._maxSimultaneousLights);
            var j = [VertexBuffer.PositionKind];
            d.NORMAL && j.push(VertexBuffer.NormalKind),
            d.UV1 && j.push(VertexBuffer.UVKind),
            d.UV2 && j.push(VertexBuffer.UV2Kind),
            MaterialHelper.PrepareAttributesForBones(j, i, d, k),
            MaterialHelper.PrepareAttributesForInstances(j, d);
            var $ = ["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"]
              , _e = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"]
              , et = ["Material", "Scene"];
            ImageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms($, d),
            ImageProcessingConfiguration.PrepareSamplers(_e, d)),
            MaterialHelper.PrepareUniformsAndSamplersList({
                uniformsNames: $,
                uniformBuffersNames: et,
                samplers: _e,
                defines: d,
                maxSimultaneousLights: this._maxSimultaneousLights
            });
            var tt = d.toString()
              , rt = c.getEngine().createEffect("background", {
                attributes: j,
                uniformsNames: $,
                uniformBuffersNames: et,
                samplers: _e,
                defines: tt,
                fallbacks: k,
                onCompiled: this.onCompiled,
                onError: this.onError,
                indexParameters: {
                    maxSimultaneousLights: this._maxSimultaneousLights
                }
            }, _);
            o.setEffect(rt, d, this._materialContext),
            this.buildUniformLayout()
        }
        return !o.effect || !o.effect.isReady() ? !1 : (d._renderId = c.getRenderId(),
        o.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),
        a.prototype.unbind.call(this)
    }
    ,
    e.prototype.bindOnlyWorldMatrix = function(i) {
        this._activeEffect.setMatrix("world", i)
    }
    ,
    e.prototype.bindForSubMesh = function(i, o, s) {
        var c = this.getScene()
          , d = s.materialDefines;
        if (!!d) {
            var _ = s.effect;
            if (!!_) {
                this._activeEffect = _,
                this.bindOnlyWorldMatrix(i),
                MaterialHelper.BindBonesParameters(o, this._activeEffect);
                var b = this._mustRebind(c, _, o.visibility);
                if (b) {
                    this._uniformBuffer.bindToEffect(_, "Material"),
                    this.bindViewProjection(_);
                    var k = this._reflectionTexture;
                    (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) && (c.texturesEnabled && (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled && (this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level),
                    MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse")),
                    k && MaterialFlags.ReflectionTextureEnabled && (this._uniformBuffer.updateMatrix("reflectionMatrix", k.getReflectionTextureMatrix()),
                    this._uniformBuffer.updateFloat2("vReflectionInfos", k.level, this._reflectionBlur),
                    this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", k.getSize().width, k.lodGenerationScale, k.lodGenerationOffset))),
                    this.shadowLevel > 0 && this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel),
                    this._uniformBuffer.updateFloat("alpha", this.alpha),
                    this.pointsCloud && this._uniformBuffer.updateFloat("pointSize", this.pointSize),
                    d.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),
                    c.texturesEnabled && (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled && this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture),
                    k && MaterialFlags.ReflectionTextureEnabled && (d.REFLECTIONBLUR && d.TEXTURELODSUPPORT ? this._uniformBuffer.setTexture("reflectionSampler", k) : d.REFLECTIONBLUR ? (this._uniformBuffer.setTexture("reflectionSampler", k._lodTextureMid || k),
                    this._uniformBuffer.setTexture("reflectionSamplerLow", k._lodTextureLow || k),
                    this._uniformBuffer.setTexture("reflectionSamplerHigh", k._lodTextureHigh || k)) : this._uniformBuffer.setTexture("reflectionSampler", k),
                    d.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, c),
                    c.bindEyePosition(_)
                } else
                    c.getEngine()._features.needToAlwaysBindUniformBuffers && (this._uniformBuffer.bindToEffect(_, "Material"),
                    this._needToBindSceneUbo = !0);
                (b || !this.isFrozen) && (c.lightsEnabled && MaterialHelper.BindLights(c, o, this._activeEffect, d, this._maxSimultaneousLights),
                this.bindView(_),
                MaterialHelper.BindFogParameters(c, o, this._activeEffect, !0),
                this._imageProcessingConfiguration && this._imageProcessingConfiguration.bind(this._activeEffect)),
                this._afterBind(o, this._activeEffect),
                this._uniformBuffer.update()
            }
        }
    }
    ,
    e.prototype.hasTexture = function(i) {
        return !!(a.prototype.hasTexture.call(this, i) || this._reflectionTexture === i || this._diffuseTexture === i)
    }
    ,
    e.prototype.dispose = function(i, o) {
        i === void 0 && (i = !1),
        o === void 0 && (o = !1),
        o && (this.diffuseTexture && this.diffuseTexture.dispose(),
        this.reflectionTexture && this.reflectionTexture.dispose()),
        this._renderTargets.dispose(),
        this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        a.prototype.dispose.call(this, i)
    }
    ,
    e.prototype.clone = function(i) {
        var o = this;
        return SerializationHelper.Clone(function() {
            return new e(i,o.getScene())
        }, this)
    }
    ,
    e.prototype.serialize = function() {
        var i = SerializationHelper.Serialize(this);
        return i.customType = "BABYLON.BackgroundMaterial",
        i
    }
    ,
    e.prototype.getClassName = function() {
        return "BackgroundMaterial"
    }
    ,
    e.Parse = function(i, o, s) {
        return SerializationHelper.Parse(function() {
            return new e(i.name,o)
        }, i, o, s)
    }
    ,
    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 a(e, i) {
        var o = this;
        this._errorHandler = function(s, c) {
            o.onErrorObservable.notifyObservers({
                message: s,
                exception: c
            })
        }
        ,
        this._options = __assign(__assign({}, a._getDefaultOptions()), e),
        this._scene = i,
        this.onErrorObservable = new Observable,
        this._setupBackground(),
        this._setupImageProcessing()
    }
    return a._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(a.prototype, "rootMesh", {
        get: function() {
            return this._rootMesh
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "skybox", {
        get: function() {
            return this._skybox
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "skyboxTexture", {
        get: function() {
            return this._skyboxTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "skyboxMaterial", {
        get: function() {
            return this._skyboxMaterial
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "ground", {
        get: function() {
            return this._ground
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "groundTexture", {
        get: function() {
            return this._groundTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "groundMirror", {
        get: function() {
            return this._groundMirror
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "groundMirrorRenderList", {
        get: function() {
            return this._groundMirror ? this._groundMirror.renderList : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "groundMaterial", {
        get: function() {
            return this._groundMaterial
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.updateOptions = function(e) {
        var i = __assign(__assign({}, this._options), e);
        this._ground && !i.createGround && (this._ground.dispose(),
        this._ground = null),
        this._groundMaterial && !i.createGround && (this._groundMaterial.dispose(),
        this._groundMaterial = null),
        this._groundTexture && this._options.groundTexture != i.groundTexture && (this._groundTexture.dispose(),
        this._groundTexture = null),
        this._skybox && !i.createSkybox && (this._skybox.dispose(),
        this._skybox = null),
        this._skyboxMaterial && !i.createSkybox && (this._skyboxMaterial.dispose(),
        this._skyboxMaterial = null),
        this._skyboxTexture && this._options.skyboxTexture != i.skyboxTexture && (this._skyboxTexture.dispose(),
        this._skyboxTexture = null),
        this._groundMirror && !i.enableGroundMirror && (this._groundMirror.dispose(),
        this._groundMirror = null),
        this._scene.environmentTexture && this._options.environmentTexture != i.environmentTexture && this._scene.environmentTexture.dispose(),
        this._options = i,
        this._setupBackground(),
        this._setupImageProcessing()
    }
    ,
    a.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))
    }
    ,
    a.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())
    }
    ,
    a.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
        }
    }
    ,
    a.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
    }
    ,
    a.prototype._getSceneSize = function() {
        var e = this
          , i = this._options.groundSize
          , o = this._options.skyboxSize
          , s = this._options.rootPosition;
        if (!this._scene.meshes || this._scene.meshes.length === 1)
            return {
                groundSize: i,
                skyboxSize: o,
                rootPosition: s
            };
        var c = this._scene.getWorldExtends(function(b) {
            return b !== e._ground && b !== e._rootMesh && b !== e._skybox
        })
          , d = c.max.subtract(c.min);
        if (this._options.sizeAuto) {
            this._scene.activeCamera instanceof ArcRotateCamera && this._scene.activeCamera.upperRadiusLimit && (i = this._scene.activeCamera.upperRadiusLimit * 2,
            o = i);
            var _ = d.length();
            _ > i && (i = _ * 2,
            o = i),
            i *= 1.1,
            o *= 1.5,
            s = c.min.add(d.scale(.5)),
            s.y = c.min.y - this._options.groundYBias
        }
        return {
            groundSize: i,
            skyboxSize: o,
            rootPosition: s
        }
    }
    ,
    a.prototype._setupGround = function(e) {
        var i = 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() {
            i._ground = null
        })),
        this._ground.receiveShadows = this._options.enableGroundShadow
    }
    ,
    a.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)
    }
    ,
    a.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
        }
    }
    ,
    a.prototype._setupGroundMirrorTexture = function(e) {
        var i = 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 = i,
        this._groundMirror.wrapV = i,
        this._groundMirror.gammaSpace = !1,
        this._groundMirror.renderList))
            for (var o = 0; o < this._scene.meshes.length; o++) {
                var s = this._scene.meshes[o];
                s !== this._ground && s !== this._skybox && s !== this._rootMesh && this._groundMirror.renderList.push(s)
            }
        this._groundMirror.clearColor = new Color4(this._options.groundColor.r,this._options.groundColor.g,this._options.groundColor.b,1),
        this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel
    }
    ,
    a.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)
    }
    ,
    a.prototype._setupSkybox = function(e) {
        var i = this;
        (!this._skybox || this._skybox.isDisposed()) && (this._skybox = CreateBox("BackgroundSkybox", {
            size: e.skyboxSize,
            sideOrientation: Mesh.BACKSIDE
        }, this._scene),
        this._skybox.onDisposeObservable.add(function() {
            i._skybox = null
        })),
        this._skybox.parent = this._rootMesh
    }
    ,
    a.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)
    }
    ,
    a.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
        }
    }
    ,
    a.prototype.dispose = function() {
        this._groundMaterial && this._groundMaterial.dispose(!0, !0),
        this._skyboxMaterial && this._skyboxMaterial.dispose(!0, !0),
        this._rootMesh.dispose(!1)
    }
    ,
    a._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png",
    a._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds",
    a._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env",
    a
}();
FreeCameraInputsManager.prototype.addDeviceOrientation = function() {
    return this._deviceOrientationInput || (this._deviceOrientationInput = new FreeCameraDeviceOrientationInput,
    this.add(this._deviceOrientationInput)),
    this
}
;
var FreeCameraDeviceOrientationInput = function() {
    function a() {
        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(i) {
            e._alpha = i.alpha !== null ? i.alpha : 0,
            e._beta = i.beta !== null ? i.beta : 0,
            e._gamma = i.gamma !== null ? i.gamma : 0,
            i.alpha !== null && e._onDeviceOrientationChangedObservable.notifyObservers()
        }
        ,
        this._constantTranform = new Quaternion(-Math.sqrt(.5),0,0,Math.sqrt(.5)),
        this._orientationChanged()
    }
    return a.WaitForOrientationChangeAsync = function(e) {
        return new Promise(function(i, o) {
            var s = !1
              , c = function() {
                window.removeEventListener("deviceorientation", c),
                s = !0,
                i()
            };
            e && setTimeout(function() {
                s || (window.removeEventListener("deviceorientation", c),
                o("WaitForOrientationChangeAsync timed out"))
            }, e),
            typeof DeviceOrientationEvent != "undefined" && typeof DeviceOrientationEvent.requestPermission == "function" ? DeviceOrientationEvent.requestPermission().then(function(d) {
                d == "granted" ? window.addEventListener("deviceorientation", c) : Tools.Warn("Permission not granted.")
            }).catch(function(d) {
                Tools.Error(d)
            }) : window.addEventListener("deviceorientation", c)
        }
        )
    }
    ,
    Object.defineProperty(a.prototype, "camera", {
        get: function() {
            return this._camera
        },
        set: function(e) {
            var i = this;
            this._camera = e,
            this._camera != null && !this._camera.rotationQuaternion && (this._camera.rotationQuaternion = new Quaternion),
            this._camera && this._camera.onDisposeObservable.add(function() {
                i._onDeviceOrientationChangedObservable.clear()
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.attachControl = function() {
        var e = this
          , i = this.camera.getScene().getEngine().getHostWindow();
        if (i) {
            var o = function() {
                i.addEventListener("orientationchange", e._orientationChanged),
                i.addEventListener("deviceorientation", e._deviceOrientation),
                e._orientationChanged()
            };
            typeof DeviceOrientationEvent != "undefined" && typeof DeviceOrientationEvent.requestPermission == "function" ? DeviceOrientationEvent.requestPermission().then(function(s) {
                s === "granted" ? o() : Tools.Warn("Permission not granted.")
            }).catch(function(s) {
                Tools.Error(s)
            }) : o()
        }
    }
    ,
    a.prototype.detachControl = function(e) {
        window.removeEventListener("orientationchange", this._orientationChanged),
        window.removeEventListener("deviceorientation", this._deviceOrientation),
        this._alpha = 0
    }
    ,
    a.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)
    }
    ,
    a.prototype.getClassName = function() {
        return "FreeCameraDeviceOrientationInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "deviceOrientation"
    }
    ,
    a
}();
CameraInputTypes.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
Node$2.AddNodeConstructor("DeviceOrientationCamera", function(a, e) {
    return function() {
        return new DeviceOrientationCamera(a,Vector3.Zero(),e)
    }
});
var DeviceOrientationCamera = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, o, s) || this;
        return c._tmpDragQuaternion = new Quaternion,
        c._disablePointerInputWhenUsingDeviceOrientation = !0,
        c._dragFactor = 0,
        c._quaternionCache = new Quaternion,
        c.inputs.addDeviceOrientation(),
        c.inputs._deviceOrientationInput && c.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function() {
            c._disablePointerInputWhenUsingDeviceOrientation && c.inputs._mouseInput && (c.inputs._mouseInput._allowCameraRotation = !1,
            c.inputs._mouseInput.onPointerMovedObservable.add(function(d) {
                c._dragFactor != 0 && (c._initialQuaternion || (c._initialQuaternion = new Quaternion),
                Quaternion.FromEulerAnglesToRef(0, d.offsetX * c._dragFactor, 0, c._tmpDragQuaternion),
                c._initialQuaternion.multiplyToRef(c._tmpDragQuaternion, c._initialQuaternion))
            }))
        }),
        c
    }
    return Object.defineProperty(e.prototype, "disablePointerInputWhenUsingDeviceOrientation", {
        get: function() {
            return this._disablePointerInputWhenUsingDeviceOrientation
        },
        set: function(i) {
            this._disablePointerInputWhenUsingDeviceOrientation = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.enableHorizontalDragging = function(i) {
        i === void 0 && (i = 1 / 300),
        this._dragFactor = i
    }
    ,
    e.prototype.getClassName = function() {
        return "DeviceOrientationCamera"
    }
    ,
    e.prototype._checkInputs = function() {
        a.prototype._checkInputs.call(this),
        this._quaternionCache.copyFrom(this.rotationQuaternion),
        this._initialQuaternion && this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion)
    }
    ,
    e.prototype.resetToCurrentRotation = function(i) {
        var o = this;
        i === void 0 && (i = Axis.Y),
        this.rotationQuaternion && (this._initialQuaternion || (this._initialQuaternion = new Quaternion),
        this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion),
        ["x", "y", "z"].forEach(function(s) {
            i[s] ? o._initialQuaternion[s] *= -1 : o._initialQuaternion[s] = 0
        }),
        this._initialQuaternion.normalize(),
        this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion))
    }
    ,
    e
}(FreeCamera)
  , VRCameraMetrics = function() {
    function a() {
        this.compensateDistortion = !0,
        this.multiviewEnabled = !1
    }
    return Object.defineProperty(a.prototype, "aspectRatio", {
        get: function() {
            return this.hResolution / (2 * this.vResolution)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "aspectRatioFov", {
        get: function() {
            return 2 * Math.atan(this.postProcessScaleFactor * this.vScreenSize / (2 * this.eyeToScreenDistance))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "leftHMatrix", {
        get: function() {
            var e = this.hScreenSize / 4 - this.lensSeparationDistance / 2
              , i = 4 * e / this.hScreenSize;
            return Matrix.Translation(i, 0, 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rightHMatrix", {
        get: function() {
            var e = this.hScreenSize / 4 - this.lensSeparationDistance / 2
              , i = 4 * e / this.hScreenSize;
            return Matrix.Translation(-i, 0, 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "leftPreViewMatrix", {
        get: function() {
            return Matrix.Translation(.5 * this.interpupillaryDistance, 0, 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rightPreViewMatrix", {
        get: function() {
            return Matrix.Translation(-.5 * this.interpupillaryDistance, 0, 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.GetDefault = function() {
        var e = new a;
        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
    }
    ,
    a
}()
  , name$2 = "vrDistortionCorrectionPixelShader"
  , shader$2 = `
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$2] = shader$2;
var VRDistortionCorrectionPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        var d = a.call(this, i, "vrDistortionCorrection", ["LensCenter", "Scale", "ScaleIn", "HmdWarpParam"], null, c.postProcessScaleFactor, o, Texture.BILINEAR_SAMPLINGMODE) || this;
        return d._isRightEye = s,
        d._distortionFactors = c.distortionK,
        d._postProcessScaleFactor = c.postProcessScaleFactor,
        d._lensCenterOffset = c.lensCenterOffset,
        d.adaptScaleToCurrentViewport = !0,
        d.onSizeChangedObservable.add(function() {
            d._scaleIn = new Vector2(2,2 / d.aspectRatio),
            d._scaleFactor = new Vector2(.5 * (1 / d._postProcessScaleFactor),.5 * (1 / d._postProcessScaleFactor) * d.aspectRatio),
            d._lensCenter = new Vector2(d._isRightEye ? .5 - d._lensCenterOffset * .5 : .5 + d._lensCenterOffset * .5,.5)
        }),
        d.onApplyObservable.add(function(_) {
            _.setFloat2("LensCenter", d._lensCenter.x, d._lensCenter.y),
            _.setFloat2("Scale", d._scaleFactor.x, d._scaleFactor.y),
            _.setFloat2("ScaleIn", d._scaleIn.x, d._scaleIn.y),
            _.setFloat4("HmdWarpParam", d._distortionFactors[0], d._distortionFactors[1], d._distortionFactors[2], d._distortionFactors[3])
        }),
        d
    }
    return e.prototype.getClassName = function() {
        return "VRDistortionCorrectionPostProcess"
    }
    ,
    e
}(PostProcess)
  , name$1 = "vrMultiviewToSingleviewPixelShader"
  , shader$1 = `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$1] = shader$1;
var VRMultiviewToSingleviewPostProcess = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, "vrMultiviewToSingleview", ["imageIndex"], ["multiviewSampler"], s, o, Texture.BILINEAR_SAMPLINGMODE) || this;
        return c.onSizeChangedObservable.add(function() {}),
        c.onApplyObservable.add(function(d) {
            o._scene.activeCamera && o._scene.activeCamera.isLeftCamera ? d.setInt("imageIndex", 0) : d.setInt("imageIndex", 1),
            d.setTexture("multiviewSampler", o._multiviewTexture)
        }),
        c
    }
    return e.prototype.getClassName = function() {
        return "VRMultiviewToSingleviewPostProcess"
    }
    ,
    e
}(PostProcess);
function setVRRigMode(a, e) {
    var i = e.vrCameraMetrics || VRCameraMetrics.GetDefault();
    a._rigCameras[0]._cameraRigParams.vrMetrics = i,
    a._rigCameras[0].viewport = new Viewport(0,0,.5,1),
    a._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix,
    a._rigCameras[0]._cameraRigParams.vrHMatrix = i.leftHMatrix,
    a._rigCameras[0]._cameraRigParams.vrPreViewMatrix = i.leftPreViewMatrix,
    a._rigCameras[0].getProjectionMatrix = a._rigCameras[0]._getVRProjectionMatrix,
    a._rigCameras[1]._cameraRigParams.vrMetrics = i,
    a._rigCameras[1].viewport = new Viewport(.5,0,.5,1),
    a._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix,
    a._rigCameras[1]._cameraRigParams.vrHMatrix = i.rightHMatrix,
    a._rigCameras[1]._cameraRigParams.vrPreViewMatrix = i.rightPreViewMatrix,
    a._rigCameras[1].getProjectionMatrix = a._rigCameras[1]._getVRProjectionMatrix,
    i.multiviewEnabled && (a.getScene().getEngine().getCaps().multiview ? (a._useMultiviewToSingleView = !0,
    a._rigPostProcess = new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",a,i.postProcessScaleFactor)) : (Logger$2.Warn("Multiview is not supported, falling back to standard rendering"),
    i.multiviewEnabled = !1)),
    i.compensateDistortion && (a._rigCameras[0]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",a._rigCameras[0],!1,i),
    a._rigCameras[1]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",a._rigCameras[1],!0,i))
}
Node$2.AddNodeConstructor("VRDeviceOrientationFreeCamera", function(a, e) {
    return function() {
        return new VRDeviceOrientationFreeCamera(a,Vector3.Zero(),e)
    }
});
var VRDeviceOrientationFreeCamera = function(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        c === void 0 && (c = !0),
        d === void 0 && (d = VRCameraMetrics.GetDefault());
        var _ = a.call(this, i, o, s) || this;
        return _._setRigMode = setVRRigMode.bind(null, _),
        d.compensateDistortion = c,
        _.setCameraRigMode(Camera$1.RIG_MODE_VR, {
            vrCameraMetrics: d
        }),
        _
    }
    return e.prototype.getClassName = function() {
        return "VRDeviceOrientationFreeCamera"
    }
    ,
    e
}(DeviceOrientationCamera), Gamepad = function() {
    function a(e, i, o, s, c, d, _) {
        s === void 0 && (s = 0),
        c === void 0 && (c = 1),
        d === void 0 && (d = 2),
        _ === void 0 && (_ = 3),
        this.id = e,
        this.index = i,
        this.browserGamepad = o,
        this._leftStick = {
            x: 0,
            y: 0
        },
        this._rightStick = {
            x: 0,
            y: 0
        },
        this._isConnected = !0,
        this._invertLeftStickY = !1,
        this.type = a.GAMEPAD,
        this._leftStickAxisX = s,
        this._leftStickAxisY = c,
        this._rightStickAxisX = d,
        this._rightStickAxisY = _,
        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(a.prototype, "isConnected", {
        get: function() {
            return this._isConnected
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.onleftstickchanged = function(e) {
        this._onleftstickchanged = e
    }
    ,
    a.prototype.onrightstickchanged = function(e) {
        this._onrightstickchanged = e
    }
    ,
    Object.defineProperty(a.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(a.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
    }),
    a.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]
        })
    }
    ,
    a.prototype.dispose = function() {}
    ,
    a.GAMEPAD = 0,
    a.GENERIC = 1,
    a.XBOX = 2,
    a.POSE_ENABLED = 3,
    a.DUALSHOCK = 4,
    a
}(), GenericPad = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, o, s) || this;
        return c.onButtonDownObservable = new Observable,
        c.onButtonUpObservable = new Observable,
        c.type = Gamepad.GENERIC,
        c._buttons = new Array(s.buttons.length),
        c
    }
    return e.prototype.onbuttondown = function(i) {
        this._onbuttondown = i
    }
    ,
    e.prototype.onbuttonup = function(i) {
        this._onbuttonup = i
    }
    ,
    e.prototype._setButtonValue = function(i, o, s) {
        return i !== o && (i === 1 && (this._onbuttondown && this._onbuttondown(s),
        this.onButtonDownObservable.notifyObservers(s)),
        i === 0 && (this._onbuttonup && this._onbuttonup(s),
        this.onButtonUpObservable.notifyObservers(s))),
        i
    }
    ,
    e.prototype.update = function() {
        a.prototype.update.call(this);
        for (var i = 0; i < this._buttons.length; i++)
            this._buttons[i] = this._setButtonValue(this.browserGamepad.buttons[i].value, this._buttons[i], i)
    }
    ,
    e.prototype.dispose = function() {
        a.prototype.dispose.call(this),
        this.onButtonDownObservable.clear(),
        this.onButtonUpObservable.clear()
    }
    ,
    e
}(Gamepad), PoseEnabledControllerType;
(function(a) {
    a[a.VIVE = 0] = "VIVE",
    a[a.OCULUS = 1] = "OCULUS",
    a[a.WINDOWS = 2] = "WINDOWS",
    a[a.GEAR_VR = 3] = "GEAR_VR",
    a[a.DAYDREAM = 4] = "DAYDREAM",
    a[a.GENERIC = 5] = "GENERIC"
}
)(PoseEnabledControllerType || (PoseEnabledControllerType = {}));
var PoseEnabledControllerHelper = function() {
    function a() {}
    return a.InitiateController = function(e) {
        for (var i = 0, o = this._ControllerFactories; i < o.length; i++) {
            var s = o[i];
            if (s.canCreate(e))
                return s.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."
    }
    ,
    a._ControllerFactories = [],
    a._DefaultControllerFactory = null,
    a
}()
  , PoseEnabledController = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i.id, i.index, i) || this;
        return o.isXR = !1,
        o._deviceRoomPosition = Vector3.Zero(),
        o._deviceRoomRotationQuaternion = new Quaternion,
        o.devicePosition = Vector3.Zero(),
        o.deviceRotationQuaternion = new Quaternion,
        o.deviceScaleFactor = 1,
        o._trackPosition = !0,
        o._maxRotationDistFromHeadset = Math.PI / 5,
        o._draggedRoomRotation = 0,
        o._leftHandSystemQuaternion = new Quaternion,
        o._deviceToWorld = Matrix.Identity(),
        o._pointingPoseNode = null,
        o._workingMatrix = Matrix.Identity(),
        o._meshAttachedObservable = new Observable,
        o.type = Gamepad.POSE_ENABLED,
        o.controllerType = PoseEnabledControllerType.GENERIC,
        o.position = Vector3.Zero(),
        o.rotationQuaternion = new Quaternion,
        o._calculatedPosition = Vector3.Zero(),
        o._calculatedRotation = new Quaternion,
        Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, o._leftHandSystemQuaternion),
        o
    }
    return e.prototype._disableTrackPosition = function(i) {
        this._trackPosition && (this._calculatedPosition.copyFrom(i),
        this._trackPosition = !1)
    }
    ,
    e.prototype.update = function() {
        a.prototype.update.call(this),
        this._updatePoseAndMesh()
    }
    ,
    e.prototype._updatePoseAndMesh = function() {
        if (!this.isXR) {
            var i = this.browserGamepad.pose;
            if (this.updateFromDevice(i),
            !this._trackPosition && EngineStore.LastCreatedScene && EngineStore.LastCreatedScene.activeCamera && EngineStore.LastCreatedScene.activeCamera.devicePosition) {
                var o = EngineStore.LastCreatedScene.activeCamera;
                if (o._computeDevicePosition(),
                this._deviceToWorld.setTranslation(o.devicePosition),
                o.deviceRotationQuaternion) {
                    var o = o;
                    o._deviceRoomRotationQuaternion.toEulerAnglesToRef(TmpVectors.Vector3[0]);
                    var s = Math.atan2(Math.sin(TmpVectors.Vector3[0].y - this._draggedRoomRotation), Math.cos(TmpVectors.Vector3[0].y - this._draggedRoomRotation));
                    if (Math.abs(s) > this._maxRotationDistFromHeadset) {
                        var c = s - (s < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
                        this._draggedRoomRotation += c;
                        var d = Math.sin(-c)
                          , _ = Math.cos(-c);
                        this._calculatedPosition.x = this._calculatedPosition.x * _ - this._calculatedPosition.z * d,
                        this._calculatedPosition.z = this._calculatedPosition.x * d + this._calculatedPosition.z * _
                    }
                }
            }
            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(i) {
        if (!this.isXR && i) {
            this.rawPose = i,
            i.position && (this._deviceRoomPosition.copyFromFloats(i.position[0], i.position[1], -i.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 o = this.rawPose;
            i.orientation && o.orientation && o.orientation.length === 4 && (this._deviceRoomRotationQuaternion.copyFromFloats(o.orientation[0], o.orientation[1], -o.orientation[2], -o.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(i) {
        if (this._mesh && (this._mesh.parent = null),
        this._mesh = i,
        this._poseControlledCamera && (this._mesh.parent = this._poseControlledCamera),
        this._mesh.rotationQuaternion || (this._mesh.rotationQuaternion = new Quaternion),
        !this.isXR && (this._updatePoseAndMesh(),
        this._pointingPoseNode)) {
            for (var o = [], s = this._pointingPoseNode; s.parent; )
                o.push(s.parent),
                s = s.parent;
            o.reverse().forEach(function(c) {
                c.computeWorldMatrix(!0)
            })
        }
        this._meshAttachedObservable.notifyObservers(i)
    }
    ,
    e.prototype.attachToPoseControlledCamera = function(i) {
        this._poseControlledCamera = i,
        this._mesh && (this._mesh.parent = this._poseControlledCamera)
    }
    ,
    e.prototype.dispose = function() {
        this._mesh && this._mesh.dispose(),
        this._mesh = null,
        a.prototype.dispose.call(this)
    }
    ,
    Object.defineProperty(e.prototype, "mesh", {
        get: function() {
            return this._mesh
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getForwardRay = function(i) {
        if (i === void 0 && (i = 100),
        !this.mesh)
            return new Ray(Vector3.Zero(),new Vector3(0,0,1),i);
        var o = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix()
          , s = o.getTranslation()
          , c = new Vector3(0,0,-1)
          , d = Vector3.TransformNormal(c, o)
          , _ = Vector3.Normalize(d);
        return new Ray(s,_,i)
    }
    ,
    e.POINTING_POSE = "POINTING_POSE",
    e
}(Gamepad);
function setWebVRRigMode(a, e) {
    if (e.vrDisplay) {
        var i = e.vrDisplay.getEyeParameters("left")
          , o = e.vrDisplay.getEyeParameters("right");
        a._rigCameras[0].viewport = new Viewport(0,0,.5,1),
        a._rigCameras[0].setCameraRigParameter("left", !0),
        a._rigCameras[0].setCameraRigParameter("specs", e.specs),
        a._rigCameras[0].setCameraRigParameter("eyeParameters", i),
        a._rigCameras[0].setCameraRigParameter("frameData", e.frameData),
        a._rigCameras[0].setCameraRigParameter("parentCamera", e.parentCamera),
        a._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix,
        a._rigCameras[0].getProjectionMatrix = a._getWebVRProjectionMatrix,
        a._rigCameras[0].parent = a,
        a._rigCameras[0]._getViewMatrix = a._getWebVRViewMatrix,
        a._rigCameras[1].viewport = new Viewport(.5,0,.5,1),
        a._rigCameras[1].setCameraRigParameter("eyeParameters", o),
        a._rigCameras[1].setCameraRigParameter("specs", e.specs),
        a._rigCameras[1].setCameraRigParameter("frameData", e.frameData),
        a._rigCameras[1].setCameraRigParameter("parentCamera", e.parentCamera),
        a._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix,
        a._rigCameras[1].getProjectionMatrix = a._getWebVRProjectionMatrix,
        a._rigCameras[1].parent = a,
        a._rigCameras[1]._getViewMatrix = a._getWebVRViewMatrix
    }
}
Node$2.AddNodeConstructor("WebVRFreeCamera", function(a, e) {
    return function() {
        return new WebVRFreeCamera(a,Vector3.Zero(),e)
    }
});
Node$2.AddNodeConstructor("WebVRGamepadCamera", function(a, e) {
    return function() {
        return new WebVRFreeCamera(a,Vector3.Zero(),e)
    }
});
var WebVRFreeCamera = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        c === void 0 && (c = {});
        var d = a.call(this, i, o, s) || this;
        d.webVROptions = c,
        d._vrDevice = null,
        d.rawPose = null,
        d._specsVersion = "1.1",
        d._attached = !1,
        d._descendants = [],
        d._deviceRoomPosition = Vector3.Zero(),
        d._deviceRoomRotationQuaternion = Quaternion.Identity(),
        d._standingMatrix = null,
        d.devicePosition = Vector3.Zero(),
        d.deviceRotationQuaternion = Quaternion.Identity(),
        d.deviceScaleFactor = 1,
        d._deviceToWorld = Matrix.Identity(),
        d._worldToDevice = Matrix.Identity(),
        d.controllers = [],
        d.onControllersAttachedObservable = new Observable,
        d.onControllerMeshLoadedObservable = new Observable,
        d.onPoseUpdatedFromDeviceObservable = new Observable,
        d._poseSet = !1,
        d.rigParenting = !0,
        d._defaultHeight = void 0,
        d._setRigMode = setWebVRRigMode.bind(null, d),
        d._detachIfAttached = function() {
            var b = d.getEngine().getVRDevice();
            b && !b.isPresenting && d.detachControl()
        }
        ,
        d._workingVector = Vector3.Zero(),
        d._oneVector = Vector3.One(),
        d._workingMatrix = Matrix.Identity(),
        d._tmpMatrix = new Matrix,
        d._cache.position = Vector3.Zero(),
        c.defaultHeight && (d._defaultHeight = c.defaultHeight,
        d.position.y = d._defaultHeight),
        d.minZ = .1,
        arguments.length === 5 && (d.webVROptions = arguments[4]),
        d.webVROptions.trackPosition == null && (d.webVROptions.trackPosition = !0),
        d.webVROptions.controllerMeshes == null && (d.webVROptions.controllerMeshes = !0),
        d.webVROptions.defaultLightingOnControllers == null && (d.webVROptions.defaultLightingOnControllers = !0),
        d.rotationQuaternion = new Quaternion,
        d.webVROptions && d.webVROptions.positionScale && (d.deviceScaleFactor = d.webVROptions.positionScale);
        var _ = d.getEngine();
        return d._onVREnabled = function(b) {
            b && d.initControllers()
        }
        ,
        _.onVRRequestPresentComplete.add(d._onVREnabled),
        _.initWebVR().add(function(b) {
            !b.vrDisplay || d._vrDevice === b.vrDisplay || (d._vrDevice = b.vrDisplay,
            d.setCameraRigMode(Camera$1.RIG_MODE_WEBVR, {
                parentCamera: d,
                vrDisplay: d._vrDevice,
                frameData: d._frameData,
                specs: d._specsVersion
            }),
            d._attached && d.getEngine().enableVR(d.webVROptions))
        }),
        typeof VRFrameData != "undefined" && (d._frameData = new VRFrameData),
        c.useMultiview && (d.getScene().getEngine().getCaps().multiview ? (d._useMultiviewToSingleView = !0,
        d._rigPostProcess = new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",d,1)) : (Logger$2.Warn("Multiview is not supported, falling back to standard rendering"),
        d._useMultiviewToSingleView = !1)),
        s.onBeforeCameraRenderObservable.add(function(b) {
            b.parent === d && d.rigParenting && (d._descendants = d.getDescendants(!0, function(k) {
                var j = d.controllers.some(function(_e) {
                    return _e._mesh === k
                })
                  , $ = d._rigCameras.indexOf(k) !== -1;
                return !j && !$
            }),
            d._descendants.forEach(function(k) {
                k.parent = b
            }))
        }),
        s.onAfterCameraRenderObservable.add(function(b) {
            b.parent === d && d.rigParenting && d._descendants.forEach(function(k) {
                k.parent = d
            })
        }),
        d
    }
    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(i) {
        var o = this;
        i === void 0 && (i = function(s) {}
        ),
        this.getEngine().initWebVRAsync().then(function(s) {
            !s.vrDisplay || !s.vrDisplay.stageParameters || !s.vrDisplay.stageParameters.sittingToStandingTransform || !o.webVROptions.trackPosition ? i(!1) : (o._standingMatrix = new Matrix,
            Matrix.FromFloat32ArrayToRefScaled(s.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, o._standingMatrix),
            o.getScene().useRightHandedSystem || o._standingMatrix && o._standingMatrix.toggleModelMatrixHandInPlace(),
            i(!0))
        })
    }
    ,
    e.prototype.useStandingMatrixAsync = function() {
        var i = this;
        return new Promise(function(o) {
            i.useStandingMatrix(function(s) {
                o(s)
            })
        }
        )
    }
    ,
    e.prototype.dispose = function() {
        this._detachIfAttached(),
        this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),
        this._updateCacheWhenTrackingDisabledObserver && this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),
        a.prototype.dispose.call(this)
    }
    ,
    e.prototype.getControllerByName = function(i) {
        for (var o = 0, s = this.controllers; o < s.length; o++) {
            var c = s[o];
            if (c.hand === i)
                return c
        }
        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(i) {
        return i === void 0 && (i = 100),
        this.leftCamera ? a.prototype.getForwardRay.call(this, i, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition) : a.prototype.getForwardRay.call(this, i)
    }
    ,
    e.prototype._checkInputs = function() {
        this._vrDevice && this._vrDevice.isPresenting && (this._vrDevice.getFrameData(this._frameData),
        this.updateFromDevice(this._frameData.pose)),
        a.prototype._checkInputs.call(this)
    }
    ,
    e.prototype.updateFromDevice = function(i) {
        i && i.orientation && i.orientation.length === 4 && (this.rawPose = i,
        this._deviceRoomRotationQuaternion.copyFromFloats(i.orientation[0], i.orientation[1], -i.orientation[2], -i.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(i) {
        i = Tools.BackCompatCameraNoPreventDefault(arguments),
        a.prototype.attachControl.call(this, i),
        this._attached = !0,
        i = Camera$1.ForceAttachControlToAlwaysPreventDefault ? !1 : i,
        this._vrDevice && this.getEngine().enableVR(this.webVROptions);
        var o = this._scene.getEngine().getHostWindow();
        o && o.addEventListener("vrdisplaypresentchange", this._detachIfAttached)
    }
    ,
    e.prototype.detachControl = function(i) {
        this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),
        this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),
        a.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 i = this._rigCameras[0]
          , o = this._rigCameras[1];
        i.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),
        o.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),
        i.position.copyFrom(this._deviceRoomPosition),
        o.position.copyFrom(this._deviceRoomPosition)
    }
    ,
    e.prototype._correctPositionIfNotTrackPosition = function(i, o) {
        o === void 0 && (o = !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),
        o || this._tmpMatrix.invert(),
        this._tmpMatrix.multiplyToRef(i, i))
    }
    ,
    e.prototype._updateCache = function(i) {
        var o = 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(s) {
            s._deviceToWorld.copyFrom(o._deviceToWorld),
            o._correctPositionIfNotTrackPosition(s._deviceToWorld),
            s.update()
        })),
        i || a.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),
        a.prototype.update.call(this)
    }
    ,
    e.prototype._getViewMatrix = function() {
        return Matrix.Identity()
    }
    ,
    e.prototype._getWebVRViewMatrix = function() {
        var i = this._cameraRigParams.parentCamera;
        i._updateCache();
        var o = this._cameraRigParams.left ? this._cameraRigParams.frameData.leftViewMatrix : this._cameraRigParams.frameData.rightViewMatrix;
        return Matrix.FromArrayToRef(o, 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),
        i.deviceScaleFactor !== 1 && (this._webvrViewMatrix.invert(),
        i.deviceScaleFactor && (this._webvrViewMatrix.multiplyAtIndex(12, i.deviceScaleFactor),
        this._webvrViewMatrix.multiplyAtIndex(13, i.deviceScaleFactor),
        this._webvrViewMatrix.multiplyAtIndex(14, i.deviceScaleFactor)),
        this._webvrViewMatrix.invert()),
        i._correctPositionIfNotTrackPosition(this._webvrViewMatrix, !0),
        i._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix),
        this._workingMatrix = this._workingMatrix || Matrix.Identity(),
        this._webvrViewMatrix.invertToRef(this._workingMatrix),
        this._workingMatrix.multiplyToRef(i.getWorldMatrix(), this._workingMatrix),
        this._workingMatrix.getTranslationToRef(this._globalPosition),
        this._markSyncedWithParent(),
        this._webvrViewMatrix
    }
    ,
    e.prototype._getWebVRProjectionMatrix = function() {
        var i = this.parent;
        i._vrDevice.depthNear = i.minZ,
        i._vrDevice.depthFar = i.maxZ;
        var o = this._cameraRigParams.left ? this._cameraRigParams.frameData.leftProjectionMatrix : this._cameraRigParams.frameData.rightProjectionMatrix;
        return Matrix.FromArrayToRef(o, 0, this._projectionMatrix),
        this.getScene().useRightHandedSystem || this._projectionMatrix.toggleProjectionMatrixHandInPlace(),
        this._projectionMatrix
    }
    ,
    e.prototype.initControllers = function() {
        var i = this;
        this.controllers = [];
        var o = this.getScene().gamepadManager;
        this._onGamepadDisconnectedObserver = o.onGamepadDisconnectedObservable.add(function(s) {
            if (s.type === Gamepad.POSE_ENABLED) {
                var c = s;
                c.defaultModel && c.defaultModel.setEnabled(!1),
                c.hand === "right" && (i._rightController = null),
                c.hand === "left" && (i._leftController = null);
                var d = i.controllers.indexOf(c);
                d !== -1 && i.controllers.splice(d, 1)
            }
        }),
        this._onGamepadConnectedObserver = o.onGamepadConnectedObservable.add(function(s) {
            if (s.type === Gamepad.POSE_ENABLED) {
                var c = s;
                if (i.webVROptions.trackPosition || (c._disableTrackPosition(new Vector3(c.hand == "left" ? -.15 : .15,-.5,.25)),
                i._updateCacheWhenTrackingDisabledObserver || (i._updateCacheWhenTrackingDisabledObserver = i._scene.onBeforeRenderObservable.add(function() {
                    i._updateCache()
                }))),
                c.deviceScaleFactor = i.deviceScaleFactor,
                c._deviceToWorld.copyFrom(i._deviceToWorld),
                i._correctPositionIfNotTrackPosition(c._deviceToWorld),
                i.webVROptions.controllerMeshes && (c.defaultModel ? c.defaultModel.setEnabled(!0) : c.initControllerMesh(i.getScene(), function(b) {
                    if (b.scaling.scaleInPlace(i.deviceScaleFactor),
                    i.onControllerMeshLoadedObservable.notifyObservers(c),
                    i.webVROptions.defaultLightingOnControllers) {
                        i._lightOnControllers || (i._lightOnControllers = new HemisphericLight("vrControllersLight",new Vector3(0,1,0),i.getScene()));
                        var k = function(j, $) {
                            var _e = j.getChildren();
                            _e && _e.length !== 0 && _e.forEach(function(et) {
                                $.includedOnlyMeshes.push(et),
                                k(et, $)
                            })
                        };
                        i._lightOnControllers.includedOnlyMeshes.push(b),
                        k(b, i._lightOnControllers)
                    }
                })),
                c.attachToPoseControlledCamera(i),
                i.controllers.indexOf(c) === -1) {
                    i.controllers.push(c);
                    for (var d = !1, _ = 0; _ < i.controllers.length; _++)
                        i.controllers[_].controllerType === PoseEnabledControllerType.VIVE && (d ? i.controllers[_].hand = "right" : (d = !0,
                        i.controllers[_].hand = "left"));
                    i.controllers.length >= 2 && i.onControllersAttachedObservable.notifyObservers(i.controllers)
                }
            }
        })
    }
    ,
    e
}(FreeCamera), WebVRController = function(a) {
    __extends(e, a);
    function e(i) {
        var o = a.call(this, i) || this;
        return o.onTriggerStateChangedObservable = new Observable,
        o.onMainButtonStateChangedObservable = new Observable,
        o.onSecondaryButtonStateChangedObservable = new Observable,
        o.onPadStateChangedObservable = new Observable,
        o.onPadValuesChangedObservable = new Observable,
        o.pad = {
            x: 0,
            y: 0
        },
        o._changes = {
            pressChanged: !1,
            touchChanged: !1,
            valueChanged: !1,
            changed: !1
        },
        o._buttons = new Array(i.buttons.length),
        o.hand = i.hand,
        o
    }
    return e.prototype.onButtonStateChange = function(i) {
        this._onButtonStateChange = i
    }
    ,
    Object.defineProperty(e.prototype, "defaultModel", {
        get: function() {
            return this._defaultModel
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.update = function() {
        a.prototype.update.call(this);
        for (var i = 0; i < this._buttons.length; i++)
            this._setButtonValue(this.browserGamepad.buttons[i], this._buttons[i], i);
        (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(i, o, s) {
        if (i || (i = {
            pressed: !1,
            touched: !1,
            value: 0
        }),
        !o) {
            this._buttons[s] = {
                pressed: i.pressed,
                touched: i.touched,
                value: i.value
            };
            return
        }
        this._checkChanges(i, o),
        this._changes.changed && (this._onButtonStateChange && this._onButtonStateChange(this.index, s, i),
        this._handleButtonChange(s, i, this._changes)),
        this._buttons[s].pressed = i.pressed,
        this._buttons[s].touched = i.touched,
        this._buttons[s].value = i.value < 1e-8 ? 0 : i.value
    }
    ,
    e.prototype._checkChanges = function(i, o) {
        return this._changes.pressChanged = i.pressed !== o.pressed,
        this._changes.touchChanged = i.touched !== o.touched,
        this._changes.valueChanged = i.value !== o.value,
        this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged,
        this._changes
    }
    ,
    e.prototype.dispose = function() {
        a.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(a) {
    a[a.A = 0] = "A",
    a[a.B = 1] = "B",
    a[a.X = 2] = "X",
    a[a.Y = 3] = "Y",
    a[a.LB = 4] = "LB",
    a[a.RB = 5] = "RB",
    a[a.Back = 8] = "Back",
    a[a.Start = 9] = "Start",
    a[a.LeftStick = 10] = "LeftStick",
    a[a.RightStick = 11] = "RightStick"
}
)(Xbox360Button || (Xbox360Button = {}));
var Xbox360Dpad;
(function(a) {
    a[a.Up = 12] = "Up",
    a[a.Down = 13] = "Down",
    a[a.Left = 14] = "Left",
    a[a.Right = 15] = "Right"
}
)(Xbox360Dpad || (Xbox360Dpad = {}));
var Xbox360Pad = function(a) {
    __extends(e, a);
    function e(i, o, s, c) {
        c === void 0 && (c = !1);
        var d = a.call(this, i, o, s, 0, 1, 2, 3) || this;
        return d._leftTrigger = 0,
        d._rightTrigger = 0,
        d.onButtonDownObservable = new Observable,
        d.onButtonUpObservable = new Observable,
        d.onPadDownObservable = new Observable,
        d.onPadUpObservable = new Observable,
        d._buttonA = 0,
        d._buttonB = 0,
        d._buttonX = 0,
        d._buttonY = 0,
        d._buttonBack = 0,
        d._buttonStart = 0,
        d._buttonLB = 0,
        d._buttonRB = 0,
        d._buttonLeftStick = 0,
        d._buttonRightStick = 0,
        d._dPadUp = 0,
        d._dPadDown = 0,
        d._dPadLeft = 0,
        d._dPadRight = 0,
        d._isXboxOnePad = !1,
        d.type = Gamepad.XBOX,
        d._isXboxOnePad = c,
        d
    }
    return e.prototype.onlefttriggerchanged = function(i) {
        this._onlefttriggerchanged = i
    }
    ,
    e.prototype.onrighttriggerchanged = function(i) {
        this._onrighttriggerchanged = i
    }
    ,
    Object.defineProperty(e.prototype, "leftTrigger", {
        get: function() {
            return this._leftTrigger
        },
        set: function(i) {
            this._onlefttriggerchanged && this._leftTrigger !== i && this._onlefttriggerchanged(i),
            this._leftTrigger = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rightTrigger", {
        get: function() {
            return this._rightTrigger
        },
        set: function(i) {
            this._onrighttriggerchanged && this._rightTrigger !== i && this._onrighttriggerchanged(i),
            this._rightTrigger = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.onbuttondown = function(i) {
        this._onbuttondown = i
    }
    ,
    e.prototype.onbuttonup = function(i) {
        this._onbuttonup = i
    }
    ,
    e.prototype.ondpaddown = function(i) {
        this._ondpaddown = i
    }
    ,
    e.prototype.ondpadup = function(i) {
        this._ondpadup = i
    }
    ,
    e.prototype._setButtonValue = function(i, o, s) {
        return i !== o && (i === 1 && (this._onbuttondown && this._onbuttondown(s),
        this.onButtonDownObservable.notifyObservers(s)),
        i === 0 && (this._onbuttonup && this._onbuttonup(s),
        this.onButtonUpObservable.notifyObservers(s))),
        i
    }
    ,
    e.prototype._setDPadValue = function(i, o, s) {
        return i !== o && (i === 1 && (this._ondpaddown && this._ondpaddown(s),
        this.onPadDownObservable.notifyObservers(s)),
        i === 0 && (this._ondpadup && this._ondpadup(s),
        this.onPadUpObservable.notifyObservers(s))),
        i
    }
    ,
    Object.defineProperty(e.prototype, "buttonA", {
        get: function() {
            return this._buttonA
        },
        set: function(i) {
            this._buttonA = this._setButtonValue(i, this._buttonA, Xbox360Button.A)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonB", {
        get: function() {
            return this._buttonB
        },
        set: function(i) {
            this._buttonB = this._setButtonValue(i, this._buttonB, Xbox360Button.B)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonX", {
        get: function() {
            return this._buttonX
        },
        set: function(i) {
            this._buttonX = this._setButtonValue(i, this._buttonX, Xbox360Button.X)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonY", {
        get: function() {
            return this._buttonY
        },
        set: function(i) {
            this._buttonY = this._setButtonValue(i, this._buttonY, Xbox360Button.Y)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonStart", {
        get: function() {
            return this._buttonStart
        },
        set: function(i) {
            this._buttonStart = this._setButtonValue(i, this._buttonStart, Xbox360Button.Start)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonBack", {
        get: function() {
            return this._buttonBack
        },
        set: function(i) {
            this._buttonBack = this._setButtonValue(i, this._buttonBack, Xbox360Button.Back)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonLB", {
        get: function() {
            return this._buttonLB
        },
        set: function(i) {
            this._buttonLB = this._setButtonValue(i, this._buttonLB, Xbox360Button.LB)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonRB", {
        get: function() {
            return this._buttonRB
        },
        set: function(i) {
            this._buttonRB = this._setButtonValue(i, this._buttonRB, Xbox360Button.RB)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonLeftStick", {
        get: function() {
            return this._buttonLeftStick
        },
        set: function(i) {
            this._buttonLeftStick = this._setButtonValue(i, this._buttonLeftStick, Xbox360Button.LeftStick)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonRightStick", {
        get: function() {
            return this._buttonRightStick
        },
        set: function(i) {
            this._buttonRightStick = this._setButtonValue(i, this._buttonRightStick, Xbox360Button.RightStick)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadUp", {
        get: function() {
            return this._dPadUp
        },
        set: function(i) {
            this._dPadUp = this._setDPadValue(i, this._dPadUp, Xbox360Dpad.Up)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadDown", {
        get: function() {
            return this._dPadDown
        },
        set: function(i) {
            this._dPadDown = this._setDPadValue(i, this._dPadDown, Xbox360Dpad.Down)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadLeft", {
        get: function() {
            return this._dPadLeft
        },
        set: function(i) {
            this._dPadLeft = this._setDPadValue(i, this._dPadLeft, Xbox360Dpad.Left)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadRight", {
        get: function() {
            return this._dPadRight
        },
        set: function(i) {
            this._dPadRight = this._setDPadValue(i, this._dPadRight, Xbox360Dpad.Right)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.update = function() {
        a.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() {
        a.prototype.dispose.call(this),
        this.onButtonDownObservable.clear(),
        this.onButtonUpObservable.clear(),
        this.onPadDownObservable.clear(),
        this.onPadUpObservable.clear()
    }
    ,
    e
}(Gamepad), DualShockButton;
(function(a) {
    a[a.Cross = 0] = "Cross",
    a[a.Circle = 1] = "Circle",
    a[a.Square = 2] = "Square",
    a[a.Triangle = 3] = "Triangle",
    a[a.L1 = 4] = "L1",
    a[a.R1 = 5] = "R1",
    a[a.Share = 8] = "Share",
    a[a.Options = 9] = "Options",
    a[a.LeftStick = 10] = "LeftStick",
    a[a.RightStick = 11] = "RightStick"
}
)(DualShockButton || (DualShockButton = {}));
var DualShockDpad;
(function(a) {
    a[a.Up = 12] = "Up",
    a[a.Down = 13] = "Down",
    a[a.Left = 14] = "Left",
    a[a.Right = 15] = "Right"
}
)(DualShockDpad || (DualShockDpad = {}));
var DualShockPad = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i.replace("STANDARD GAMEPAD", "SONY PLAYSTATION DUALSHOCK"), o, s, 0, 1, 2, 3) || this;
        return c._leftTrigger = 0,
        c._rightTrigger = 0,
        c.onButtonDownObservable = new Observable,
        c.onButtonUpObservable = new Observable,
        c.onPadDownObservable = new Observable,
        c.onPadUpObservable = new Observable,
        c._buttonCross = 0,
        c._buttonCircle = 0,
        c._buttonSquare = 0,
        c._buttonTriangle = 0,
        c._buttonShare = 0,
        c._buttonOptions = 0,
        c._buttonL1 = 0,
        c._buttonR1 = 0,
        c._buttonLeftStick = 0,
        c._buttonRightStick = 0,
        c._dPadUp = 0,
        c._dPadDown = 0,
        c._dPadLeft = 0,
        c._dPadRight = 0,
        c.type = Gamepad.DUALSHOCK,
        c
    }
    return e.prototype.onlefttriggerchanged = function(i) {
        this._onlefttriggerchanged = i
    }
    ,
    e.prototype.onrighttriggerchanged = function(i) {
        this._onrighttriggerchanged = i
    }
    ,
    Object.defineProperty(e.prototype, "leftTrigger", {
        get: function() {
            return this._leftTrigger
        },
        set: function(i) {
            this._onlefttriggerchanged && this._leftTrigger !== i && this._onlefttriggerchanged(i),
            this._leftTrigger = i
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rightTrigger", {
        get: function() {
            return this._rightTrigger
        },
        set: function(i) {
            this._onrighttriggerchanged && this._rightTrigger !== i && this._onrighttriggerchanged(i),
            this._rightTrigger = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.onbuttondown = function(i) {
        this._onbuttondown = i
    }
    ,
    e.prototype.onbuttonup = function(i) {
        this._onbuttonup = i
    }
    ,
    e.prototype.ondpaddown = function(i) {
        this._ondpaddown = i
    }
    ,
    e.prototype.ondpadup = function(i) {
        this._ondpadup = i
    }
    ,
    e.prototype._setButtonValue = function(i, o, s) {
        return i !== o && (i === 1 && (this._onbuttondown && this._onbuttondown(s),
        this.onButtonDownObservable.notifyObservers(s)),
        i === 0 && (this._onbuttonup && this._onbuttonup(s),
        this.onButtonUpObservable.notifyObservers(s))),
        i
    }
    ,
    e.prototype._setDPadValue = function(i, o, s) {
        return i !== o && (i === 1 && (this._ondpaddown && this._ondpaddown(s),
        this.onPadDownObservable.notifyObservers(s)),
        i === 0 && (this._ondpadup && this._ondpadup(s),
        this.onPadUpObservable.notifyObservers(s))),
        i
    }
    ,
    Object.defineProperty(e.prototype, "buttonCross", {
        get: function() {
            return this._buttonCross
        },
        set: function(i) {
            this._buttonCross = this._setButtonValue(i, this._buttonCross, DualShockButton.Cross)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonCircle", {
        get: function() {
            return this._buttonCircle
        },
        set: function(i) {
            this._buttonCircle = this._setButtonValue(i, this._buttonCircle, DualShockButton.Circle)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonSquare", {
        get: function() {
            return this._buttonSquare
        },
        set: function(i) {
            this._buttonSquare = this._setButtonValue(i, this._buttonSquare, DualShockButton.Square)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonTriangle", {
        get: function() {
            return this._buttonTriangle
        },
        set: function(i) {
            this._buttonTriangle = this._setButtonValue(i, this._buttonTriangle, DualShockButton.Triangle)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonOptions", {
        get: function() {
            return this._buttonOptions
        },
        set: function(i) {
            this._buttonOptions = this._setButtonValue(i, this._buttonOptions, DualShockButton.Options)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonShare", {
        get: function() {
            return this._buttonShare
        },
        set: function(i) {
            this._buttonShare = this._setButtonValue(i, this._buttonShare, DualShockButton.Share)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonL1", {
        get: function() {
            return this._buttonL1
        },
        set: function(i) {
            this._buttonL1 = this._setButtonValue(i, this._buttonL1, DualShockButton.L1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonR1", {
        get: function() {
            return this._buttonR1
        },
        set: function(i) {
            this._buttonR1 = this._setButtonValue(i, this._buttonR1, DualShockButton.R1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonLeftStick", {
        get: function() {
            return this._buttonLeftStick
        },
        set: function(i) {
            this._buttonLeftStick = this._setButtonValue(i, this._buttonLeftStick, DualShockButton.LeftStick)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonRightStick", {
        get: function() {
            return this._buttonRightStick
        },
        set: function(i) {
            this._buttonRightStick = this._setButtonValue(i, this._buttonRightStick, DualShockButton.RightStick)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadUp", {
        get: function() {
            return this._dPadUp
        },
        set: function(i) {
            this._dPadUp = this._setDPadValue(i, this._dPadUp, DualShockDpad.Up)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadDown", {
        get: function() {
            return this._dPadDown
        },
        set: function(i) {
            this._dPadDown = this._setDPadValue(i, this._dPadDown, DualShockDpad.Down)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadLeft", {
        get: function() {
            return this._dPadLeft
        },
        set: function(i) {
            this._dPadLeft = this._setDPadValue(i, this._dPadLeft, DualShockDpad.Left)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadRight", {
        get: function() {
            return this._dPadRight
        },
        set: function(i) {
            this._dPadRight = this._setDPadValue(i, this._dPadRight, DualShockDpad.Right)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.update = function() {
        a.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() {
        a.prototype.dispose.call(this),
        this.onButtonDownObservable.clear(),
        this.onButtonUpObservable.clear(),
        this.onPadDownObservable.clear(),
        this.onPadUpObservable.clear()
    }
    ,
    e
}(Gamepad)
  , GamepadManager = function() {
    function a(e) {
        var i = 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(s) {
            for (var c in i._babylonGamepads) {
                var d = i._babylonGamepads[c];
                d && d._isConnected && i.onGamepadConnectedObservable.notifyObserver(s, d)
            }
        }
        ),
        this._onGamepadConnectedEvent = function(s) {
            var c = s.gamepad;
            if (!(c.index in i._babylonGamepads && i._babylonGamepads[c.index].isConnected)) {
                var d;
                i._babylonGamepads[c.index] ? (d = i._babylonGamepads[c.index],
                d.browserGamepad = c,
                d._isConnected = !0) : d = i._addNewGamepad(c),
                i.onGamepadConnectedObservable.notifyObservers(d),
                i._startMonitoringGamepads()
            }
        }
        ,
        this._onGamepadDisconnectedEvent = function(s) {
            var c = s.gamepad;
            for (var d in i._babylonGamepads)
                if (i._babylonGamepads[d].index === c.index) {
                    var _ = i._babylonGamepads[d];
                    _._isConnected = !1,
                    i.onGamepadDisconnectedObservable.notifyObservers(_),
                    _.dispose && _.dispose();
                    break
                }
        }
        ,
        this._gamepadSupport)
            if (this._updateGamepadObjects(),
            this._babylonGamepads.length && this._startMonitoringGamepads(),
            this._gamepadEventSupported) {
                var o = this._scene ? this._scene.getEngine().getHostWindow() : window;
                o && (o.addEventListener("gamepadconnected", this._onGamepadConnectedEvent, !1),
                o.addEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent, !1))
            } else
                this._startMonitoringGamepads()
    }
    return Object.defineProperty(a.prototype, "gamepads", {
        get: function() {
            return this._babylonGamepads
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.getGamepadByType = function(e) {
        e === void 0 && (e = Gamepad.XBOX);
        for (var i = 0, o = this._babylonGamepads; i < o.length; i++) {
            var s = o[i];
            if (s && s.type === e)
                return s
        }
        return null
    }
    ,
    a.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 = []
    }
    ,
    a.prototype._addNewGamepad = function(e) {
        this._oneGamepadConnected || (this._oneGamepadConnected = !0);
        var i, o = e.id.search("054c") !== -1 && e.id.search("0ce6") === -1, s = e.id.search("Xbox One") !== -1;
        return s || e.id.search("Xbox 360") !== -1 || e.id.search("xinput") !== -1 || e.id.search("045e") !== -1 && e.id.search("Surface Dock") === -1 ? i = new Xbox360Pad(e.id,e.index,e,s) : o ? i = new DualShockPad(e.id,e.index,e) : e.pose ? i = PoseEnabledControllerHelper.InitiateController(e) : i = new GenericPad(e.id,e.index,e),
        this._babylonGamepads[i.index] = i,
        i
    }
    ,
    a.prototype._startMonitoringGamepads = function() {
        this._isMonitoring || (this._isMonitoring = !0,
        this._scene || this._checkGamepadsStatus())
    }
    ,
    a.prototype._stopMonitoringGamepads = function() {
        this._isMonitoring = !1
    }
    ,
    a.prototype._checkGamepadsStatus = function() {
        var e = this;
        this._updateGamepadObjects();
        for (var i in this._babylonGamepads) {
            var o = this._babylonGamepads[i];
            if (!(!o || !o.isConnected))
                try {
                    o.update()
                } catch {
                    this._loggedErrors.indexOf(o.index) === -1 && (Tools.Warn("Error updating gamepad " + o.id),
                    this._loggedErrors.push(o.index))
                }
        }
        this._isMonitoring && !this._scene && Engine.QueueNewFrame(function() {
            e._checkGamepadsStatus()
        })
    }
    ,
    a.prototype._updateGamepadObjects = function() {
        for (var e = navigator.getGamepads ? navigator.getGamepads() : navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : [], i = 0; i < e.length; i++) {
            var o = e[i];
            if (o)
                if (this._babylonGamepads[o.index])
                    this._babylonGamepads[i].browserGamepad = o,
                    this._babylonGamepads[i].isConnected || (this._babylonGamepads[i]._isConnected = !0,
                    this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]));
                else {
                    var s = this._addNewGamepad(o);
                    this.onGamepadConnectedObservable.notifyObservers(s)
                }
        }
    }
    ,
    a
}()
  , FreeCameraGamepadInput = function() {
    function a() {
        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(a.prototype, "invertYAxis", {
        get: function() {
            return this._yAxisScale !== 1
        },
        set: function(e) {
            this._yAxisScale = e ? -1 : 1
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.attachControl = function() {
        var e = this
          , i = this.camera.getScene().gamepadManager;
        this._onGamepadConnectedObserver = i.onGamepadConnectedObservable.add(function(o) {
            o.type !== Gamepad.POSE_ENABLED && (!e.gamepad || o.type === Gamepad.XBOX) && (e.gamepad = o)
        }),
        this._onGamepadDisconnectedObserver = i.onGamepadDisconnectedObservable.add(function(o) {
            e.gamepad === o && (e.gamepad = null)
        }),
        this.gamepad = i.getGamepadByType(Gamepad.XBOX),
        !this.gamepad && i.gamepads.length && (this.gamepad = i.gamepads[0])
    }
    ,
    a.prototype.detachControl = function(e) {
        this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),
        this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),
        this.gamepad = null
    }
    ,
    a.prototype.checkInputs = function() {
        if (this.gamepad && this.gamepad.leftStick) {
            var e = this.camera
              , i = this.gamepad.leftStick;
            this.gamepadMoveSensibility !== 0 && (i.x = Math.abs(i.x) > this.deadzoneDelta ? i.x / this.gamepadMoveSensibility : 0,
            i.y = Math.abs(i.y) > this.deadzoneDelta ? i.y / this.gamepadMoveSensibility : 0);
            var o = this.gamepad.rightStick;
            o && this.gamepadAngularSensibility !== 0 ? (o.x = Math.abs(o.x) > this.deadzoneDelta ? o.x / this.gamepadAngularSensibility : 0,
            o.y = (Math.abs(o.y) > this.deadzoneDelta ? o.y / this.gamepadAngularSensibility : 0) * this._yAxisScale) : o = {
                x: 0,
                y: 0
            },
            e.rotationQuaternion ? e.rotationQuaternion.toRotationMatrix(this._cameraTransform) : Matrix.RotationYawPitchRollToRef(e.rotation.y, e.rotation.x, 0, this._cameraTransform);
            var s = e._computeLocalCameraSpeed() * 50;
            this._vector3.copyFromFloats(i.x * s, 0, -i.y * s),
            Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform),
            e.cameraDirection.addInPlace(this._deltaTransform),
            this._vector2.copyFromFloats(o.y, o.x),
            e.cameraRotation.addInPlace(this._vector2)
        }
    }
    ,
    a.prototype.getClassName = function() {
        return "FreeCameraGamepadInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "gamepad"
    }
    ,
    __decorate([serialize()], a.prototype, "gamepadAngularSensibility", void 0),
    __decorate([serialize()], a.prototype, "gamepadMoveSensibility", void 0),
    a
}();
CameraInputTypes.FreeCameraGamepadInput = FreeCameraGamepadInput;
var ArcRotateCameraGamepadInput = function() {
    function a() {
        this.gamepadRotationSensibility = 80,
        this.gamepadMoveSensibility = 40,
        this._yAxisScale = 1
    }
    return Object.defineProperty(a.prototype, "invertYAxis", {
        get: function() {
            return this._yAxisScale !== 1
        },
        set: function(e) {
            this._yAxisScale = e ? -1 : 1
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.attachControl = function() {
        var e = this
          , i = this.camera.getScene().gamepadManager;
        this._onGamepadConnectedObserver = i.onGamepadConnectedObservable.add(function(o) {
            o.type !== Gamepad.POSE_ENABLED && (!e.gamepad || o.type === Gamepad.XBOX) && (e.gamepad = o)
        }),
        this._onGamepadDisconnectedObserver = i.onGamepadDisconnectedObservable.add(function(o) {
            e.gamepad === o && (e.gamepad = null)
        }),
        this.gamepad = i.getGamepadByType(Gamepad.XBOX)
    }
    ,
    a.prototype.detachControl = function(e) {
        this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),
        this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),
        this.gamepad = null
    }
    ,
    a.prototype.checkInputs = function() {
        if (this.gamepad) {
            var e = this.camera
              , i = this.gamepad.rightStick;
            if (i) {
                if (i.x != 0) {
                    var o = i.x / this.gamepadRotationSensibility;
                    o != 0 && Math.abs(o) > .005 && (e.inertialAlphaOffset += o)
                }
                if (i.y != 0) {
                    var s = i.y / this.gamepadRotationSensibility * this._yAxisScale;
                    s != 0 && Math.abs(s) > .005 && (e.inertialBetaOffset += s)
                }
            }
            var c = this.gamepad.leftStick;
            if (c && c.y != 0) {
                var d = c.y / this.gamepadMoveSensibility;
                d != 0 && Math.abs(d) > .005 && (this.camera.inertialRadiusOffset -= d)
            }
        }
    }
    ,
    a.prototype.getClassName = function() {
        return "ArcRotateCameraGamepadInput"
    }
    ,
    a.prototype.getSimpleName = function() {
        return "gamepad"
    }
    ,
    __decorate([serialize()], a.prototype, "gamepadRotationSensibility", void 0),
    __decorate([serialize()], a.prototype, "gamepadMoveSensibility", void 0),
    a
}();
CameraInputTypes.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
Object.defineProperty(Scene.prototype, "gamepadManager", {
    get: function() {
        if (!this._gamepadManager) {
            this._gamepadManager = new GamepadManager(this);
            var a = this._getComponent(SceneComponentConstants.NAME_GAMEPAD);
            a || (a = new GamepadSystemSceneComponent(this),
            this._addComponent(a))
        }
        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 a(e) {
        this.name = SceneComponentConstants.NAME_GAMEPAD,
        this.scene = e
    }
    return a.prototype.register = function() {
        this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate)
    }
    ,
    a.prototype.rebuild = function() {}
    ,
    a.prototype.dispose = function() {
        var e = this.scene._gamepadManager;
        e && (e.dispose(),
        this.scene._gamepadManager = null)
    }
    ,
    a.prototype._beforeCameraUpdate = function() {
        var e = this.scene._gamepadManager;
        e && e._isMonitoring && e._checkGamepadsStatus()
    }
    ,
    a
}(), WebXRManagedOutputCanvasOptions = function() {
    function a() {}
    return a.GetDefaults = function(e) {
        var i = new a;
        return i.canvasOptions = {
            antialias: !0,
            depth: !0,
            stencil: e ? e.isStencilEnable : !0,
            alpha: !0,
            multiview: !1,
            framebufferScaleFactor: 1
        },
        i.newCanvasCssStyle = "position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",
        i
    }
    ,
    a
}(), WebXRManagedOutputCanvas = function() {
    function a(e, i) {
        var o = this;
        if (i === void 0 && (i = WebXRManagedOutputCanvasOptions.GetDefaults()),
        this._options = i,
        this._canvas = null,
        this._engine = null,
        this.xrLayer = null,
        this.onXRLayerInitObservable = new Observable,
        this._engine = e.scene.getEngine(),
        this._engine.onDisposeObservable.addOnce(function() {
            o._engine = null
        }),
        i.canvasElement)
            this._setManagedOutputCanvas(i.canvasElement);
        else {
            var s = document.createElement("canvas");
            s.style.cssText = this._options.newCanvasCssStyle || "position:absolute; bottom:0px;right:0px;",
            this._setManagedOutputCanvas(s)
        }
        e.onXRSessionInit.add(function() {
            o._addCanvas()
        }),
        e.onXRSessionEnded.add(function() {
            o._removeCanvas()
        })
    }
    return a.prototype.dispose = function() {
        this._removeCanvas(),
        this._setManagedOutputCanvas(null)
    }
    ,
    a.prototype.initializeXRLayerAsync = function(e) {
        var i = this
          , o = function() {
            var s = new XRWebGLLayer(e,i.canvasContext,i._options.canvasOptions);
            return i.onXRLayerInitObservable.notifyObservers(s),
            s
        };
        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 i.xrLayer = o(),
            i.xrLayer
        }) : (this.xrLayer = o(),
        Promise.resolve(this.xrLayer))
    }
    ,
    a.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(i) {
            e._setCanvasSize(!0, i)
        })
    }
    ,
    a.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)
    }
    ,
    a.prototype._setCanvasSize = function(e, i) {
        e === void 0 && (e = !0),
        i === void 0 && (i = this.xrLayer),
        !(!this._canvas || !this._engine) && (e ? i && (this._canvas !== this._engine.getRenderingCanvas() ? (this._canvas.style.width = i.framebufferWidth + "px",
        this._canvas.style.height = i.framebufferHeight + "px") : this._engine.setSize(i.framebufferWidth, i.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)))
    }
    ,
    a.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)
    }
    ,
    a
}(), WebXRSessionManager = function() {
    function a(e) {
        var i = 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() {
            i._engine = null
        })
    }
    return Object.defineProperty(a.prototype, "referenceSpace", {
        get: function() {
            return this._referenceSpace
        },
        set: function(e) {
            this._referenceSpace = e,
            this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "sessionMode", {
        get: function() {
            return this._sessionMode
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.dispose = function() {
        this._sessionEnded || this.exitXRAsync(),
        this.onXRFrameObservable.clear(),
        this.onXRSessionEnded.clear(),
        this.onXRReferenceSpaceChanged.clear(),
        this.onXRSessionInit.clear()
    }
    ,
    a.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()
    }
    ,
    a.prototype.getRenderTargetTextureForEye = function(e) {
        return this._rttProvider.getRenderTargetForEye(e)
    }
    ,
    a.prototype.getWebXRRenderTarget = function(e) {
        var i = this.scene.getEngine();
        return this._xrNavigator.xr.native ? this._xrNavigator.xr.getWebXRRenderTarget(i) : (e = e || WebXRManagedOutputCanvasOptions.GetDefaults(i),
        e.canvasElement = e.canvasElement || i.getRenderingCanvas() || void 0,
        new WebXRManagedOutputCanvas(this,e))
    }
    ,
    a.prototype.initializeAsync = function() {
        return this._xrNavigator = navigator,
        this._xrNavigator.xr ? Promise.resolve() : Promise.reject("WebXR not available")
    }
    ,
    a.prototype.initializeSessionAsync = function(e, i) {
        var o = this;
        return e === void 0 && (e = "immersive-vr"),
        i === void 0 && (i = {}),
        this._xrNavigator.xr.requestSession(e, i).then(function(s) {
            return o.session = s,
            o._sessionMode = e,
            o.onXRSessionInit.notifyObservers(s),
            o._sessionEnded = !1,
            o.session.addEventListener("end", function() {
                o._sessionEnded = !0,
                o.onXRSessionEnded.notifyObservers(null),
                o._rttProvider = null,
                o._engine && (o._engine.framebufferDimensionsObject = null,
                o._engine.restoreDefaultFramebuffer(),
                o._engine.customAnimationFrameRequester = null,
                o._engine._renderLoop()),
                o.isNative && (o._renderTargetTextures.forEach(function(c) {
                    return c.dispose()
                }),
                o._renderTargetTextures.length = 0)
            }, {
                once: !0
            }),
            o.session
        })
    }
    ,
    a.prototype.isSessionSupportedAsync = function(e) {
        return a.IsSessionSupportedAsync(e)
    }
    ,
    a.prototype.resetReferenceSpace = function() {
        this.referenceSpace = this.baseReferenceSpace
    }
    ,
    a.prototype.runXRRenderLoop = function() {
        var e = this;
        if (!(this._sessionEnded || !this._engine)) {
            if (this._engine.customAnimationFrameRequester = {
                requestAnimationFrame: this.session.requestAnimationFrame.bind(this.session),
                renderFunction: function(d, _) {
                    e._sessionEnded || !e._engine || (e.currentFrame = _,
                    e.currentTimestamp = d,
                    _ && (e._engine.framebufferDimensionsObject = e._baseLayer,
                    e.onXRFrameObservable.notifyObservers(_),
                    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 i, o, s, c;
                this._rttProvider = {
                    getRenderTargetForEye: function() {
                        var d = e._baseLayer;
                        return (d.framebufferWidth !== o || d.framebufferHeight !== s || d.framebuffer !== c) && (i = e._createRenderTargetTexture(d.framebufferWidth, d.framebufferHeight, d.framebuffer),
                        o = d.framebufferWidth,
                        s = d.framebufferHeight,
                        c = d.framebuffer),
                        i
                    }
                },
                this._engine.framebufferDimensionsObject = this._baseLayer
            }
            typeof window != "undefined" && window.cancelAnimationFrame && window.cancelAnimationFrame(this._engine._frameHandler),
            this._engine._renderLoop()
        }
    }
    ,
    a.prototype.setReferenceSpaceTypeAsync = function(e) {
        var i = this;
        return e === void 0 && (e = "local-floor"),
        this.session.requestReferenceSpace(e).then(function(o) {
            return o
        }, function(o) {
            return Logger$2.Error("XR.requestReferenceSpace failed for the following reason: "),
            Logger$2.Error(o),
            Logger$2.Log('Defaulting to universally-supported "viewer" reference space type.'),
            i.session.requestReferenceSpace("viewer").then(function(s) {
                var c = new XRRigidTransform({
                    x: 0,
                    y: -i.defaultHeightCompensation,
                    z: 0
                });
                return s.getOffsetReferenceSpace(c)
            }, function(s) {
                throw Logger$2.Error(s),
                'XR initialization failed: required "viewer" reference space type not supported.'
            })
        }).then(function(o) {
            return i.session.requestReferenceSpace("viewer").then(function(s) {
                return i.viewerReferenceSpace = s,
                o
            })
        }).then(function(o) {
            return i.referenceSpace = i.baseReferenceSpace = o,
            i.referenceSpace
        })
    }
    ,
    a.prototype.updateRenderStateAsync = function(e) {
        return e.baseLayer && (this._baseLayer = e.baseLayer),
        this.session.updateRenderState(e)
    }
    ,
    a.IsSessionSupportedAsync = function(e) {
        if (!navigator.xr)
            return Promise.resolve(!1);
        var i = navigator.xr.isSessionSupported || navigator.xr.supportsSession;
        return i ? i.call(navigator.xr, e).then(function(o) {
            var s = typeof o == "undefined" ? !0 : o;
            return Promise.resolve(s)
        }).catch(function(o) {
            return Logger$2.Warn(o),
            Promise.resolve(!1)
        }) : Promise.resolve(!1)
    }
    ,
    Object.defineProperty(a.prototype, "isNative", {
        get: function() {
            var e;
            return (e = this._xrNavigator.xr.native) !== null && e !== void 0 ? e : !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "currentFrameRate", {
        get: function() {
            var e;
            return (e = this.session) === null || e === void 0 ? void 0 : e.frameRate
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "supportedFrameRates", {
        get: function() {
            var e;
            return (e = this.session) === null || e === void 0 ? void 0 : e.supportedFrameRates
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.updateTargetFrameRate = function(e) {
        return this.session.updateTargetFrameRate(e)
    }
    ,
    Object.defineProperty(a.prototype, "isFixedFoveationSupported", {
        get: function() {
            var e;
            return !!(!((e = this._baseLayer) === null || e === void 0) && e.fixedFoveation) !== null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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 i, o = Math.max(0, Math.min(1, e || 0));
            ((i = this._baseLayer) === null || i === void 0 ? void 0 : i.fixedFoveation) !== void 0 && (this._baseLayer.fixedFoveation = o)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._createRenderTargetTexture = function(e, i, o) {
        if (!this._engine)
            throw new Error("Engine is disposed");
        var s = new InternalTexture(this._engine,InternalTextureSource.Unknown,!0);
        s.width = e,
        s.height = i;
        var c = new RenderTargetTexture("XR renderTargetTexture",{
            width: e,
            height: i
        },this.scene)
          , d = c.renderTarget;
        return d.setTexture(s, 0),
        d._framebuffer = o,
        c._texture = s,
        c.disableRescaling(),
        c.skipInitialClear = !0,
        this._renderTargetTextures.push(c),
        c
    }
    ,
    a.prototype._destroyRenderTargetTexture = function(e) {
        this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e), 1),
        e.dispose()
    }
    ,
    a
}(), WebXRState;
(function(a) {
    a[a.ENTERING_XR = 0] = "ENTERING_XR",
    a[a.EXITING_XR = 1] = "EXITING_XR",
    a[a.IN_XR = 2] = "IN_XR",
    a[a.NOT_IN_XR = 3] = "NOT_IN_XR"
}
)(WebXRState || (WebXRState = {}));
var WebXRTrackingState;
(function(a) {
    a[a.NOT_TRACKING = 0] = "NOT_TRACKING",
    a[a.TRACKING_LOST = 1] = "TRACKING_LOST",
    a[a.TRACKING = 2] = "TRACKING"
}
)(WebXRTrackingState || (WebXRTrackingState = {}));
var VRExperienceHelperGazer = function() {
    function a(e, i) {
        if (i === void 0 && (i = 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 = a._idCounter++,
        i)
            this._gazeTracker = i.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 o = new StandardMaterial("targetMat",e);
            o.specularColor = Color3.Black(),
            o.emissiveColor = new Color3(.7,.7,.7),
            o.backFaceCulling = !1,
            this._gazeTracker.material = o
        }
    }
    return a.prototype._getForwardRay = function(e) {
        return new Ray(Vector3.Zero(),new Vector3(0,0,e))
    }
    ,
    a.prototype._selectionPointerDown = function() {
        this._pointerDownOnMeshAsked = !0,
        this._currentHit && this.scene.simulatePointerDown(this._currentHit, {
            pointerId: this._id
        })
    }
    ,
    a.prototype._selectionPointerUp = function() {
        this._currentHit && this.scene.simulatePointerUp(this._currentHit, {
            pointerId: this._id
        }),
        this._pointerDownOnMeshAsked = !1
    }
    ,
    a.prototype._activatePointer = function() {
        this._activePointer = !0
    }
    ,
    a.prototype._deactivatePointer = function() {
        this._activePointer = !1
    }
    ,
    a.prototype._updatePointerDistance = function(e) {}
    ,
    a.prototype.dispose = function() {
        this._interactionsEnabled = !1,
        this._teleportationEnabled = !1,
        this._gazeTracker && this._gazeTracker.dispose()
    }
    ,
    a._idCounter = 0,
    a
}()
  , VRExperienceHelperControllerGazer = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, o, s) || this;
        c.webVRController = i,
        c._laserPointer = CreateCylinder("laserPointer", {
            updatable: !1,
            height: 1,
            diameterTop: .004,
            diameterBottom: 2e-4,
            tessellation: 20,
            subdivisions: 1
        }, o);
        var d = new StandardMaterial("laserPointerMat",o);
        if (d.emissiveColor = new Color3(.7,.7,.7),
        d.alpha = .6,
        c._laserPointer.material = d,
        c._laserPointer.rotation.x = Math.PI / 2,
        c._laserPointer.position.z = -.5,
        c._laserPointer.isVisible = !1,
        c._laserPointer.isPickable = !1,
        !i.mesh) {
            var _ = new Mesh("preloadControllerMesh",o)
              , b = new Mesh(PoseEnabledController.POINTING_POSE,o);
            b.rotation.x = -.7,
            _.addChild(b),
            i.attachToMesh(_)
        }
        return c._setLaserPointerParent(i.mesh),
        c._meshAttachedObserver = i._meshAttachedObservable.add(function(k) {
            c._setLaserPointerParent(k)
        }),
        c
    }
    return e.prototype._getForwardRay = function(i) {
        return this.webVRController.getForwardRay(i)
    }
    ,
    e.prototype._activatePointer = function() {
        a.prototype._activatePointer.call(this),
        this._laserPointer.isVisible = !0
    }
    ,
    e.prototype._deactivatePointer = function() {
        a.prototype._deactivatePointer.call(this),
        this._laserPointer.isVisible = !1
    }
    ,
    e.prototype._setLaserPointerColor = function(i) {
        this._laserPointer.material.emissiveColor = i
    }
    ,
    e.prototype._setLaserPointerLightingDisabled = function(i) {
        this._laserPointer.material.disableLighting = i
    }
    ,
    e.prototype._setLaserPointerParent = function(i) {
        var o = function(_) {
            _.isPickable = !1,
            _.getChildMeshes().forEach(function(b) {
                o(b)
            })
        };
        o(i);
        var s = i.getChildren(void 0, !1)
          , c = i;
        this.webVRController._pointingPoseNode = null;
        for (var d = 0; d < s.length; d++)
            if (s[d].name && s[d].name.indexOf(PoseEnabledController.POINTING_POSE) >= 0) {
                c = s[d],
                this.webVRController._pointingPoseNode = c;
                break
            }
        this._laserPointer.parent = c
    }
    ,
    e.prototype._updatePointerDistance = function(i) {
        i === void 0 && (i = 100),
        this._laserPointer.scaling.y = i,
        this._laserPointer.position.z = -i / 2
    }
    ,
    e.prototype.dispose = function() {
        a.prototype.dispose.call(this),
        this._laserPointer.dispose(),
        this._meshAttachedObserver && this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)
    }
    ,
    e
}(VRExperienceHelperGazer)
  , VRExperienceHelperCameraGazer = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, o) || this;
        return s.getCamera = i,
        s
    }
    return e.prototype._getForwardRay = function(i) {
        var o = this.getCamera();
        return o ? o.getForwardRay(i) : new Ray(Vector3.Zero(),Vector3.Forward())
    }
    ,
    e
}(VRExperienceHelperGazer)
  , VRExperienceHelper = function() {
    function a(e, i) {
        var o = this;
        i === void 0 && (i = {}),
        this.webVROptions = i,
        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 = a.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() {
            o.moveButtonToBottomRight(),
            o._fullscreenVRpresenting && o._webVRready && o.exitVR()
        }
        ,
        this._onFullscreenChange = function() {
            var d = document;
            d.fullscreen !== void 0 ? o._fullscreenVRpresenting = document.fullscreen : d.mozFullScreen !== void 0 ? o._fullscreenVRpresenting = d.mozFullScreen : d.webkitIsFullScreen !== void 0 ? o._fullscreenVRpresenting = d.webkitIsFullScreen : d.msIsFullScreen !== void 0 ? o._fullscreenVRpresenting = d.msIsFullScreen : document.msFullscreenElement !== void 0 && (o._fullscreenVRpresenting = document.msFullscreenElement),
            !o._fullscreenVRpresenting && o._inputElement && (o.exitVR(),
            !o._useCustomVRButton && o._btnVR && (o._btnVR.style.top = o._inputElement.offsetTop + o._inputElement.offsetHeight - 70 + "px",
            o._btnVR.style.left = o._inputElement.offsetLeft + o._inputElement.offsetWidth - 100 + "px",
            o.updateButtonVisibility()))
        }
        ,
        this._cachedAngularSensibility = {
            angularSensibilityX: null,
            angularSensibilityY: null,
            angularSensibility: null
        },
        this.beforeRender = function() {
            o._leftController && o._leftController._activePointer && o._castRayAndSelectObject(o._leftController),
            o._rightController && o._rightController._activePointer && o._castRayAndSelectObject(o._rightController),
            o._noControllerIsActive && (o._scene.getEngine().isPointerLock || o.enableGazeEvenWhenNoPointerLock) ? o._castRayAndSelectObject(o._cameraGazer) : o._cameraGazer._gazeTracker.isVisible = !1
        }
        ,
        this._onNewGamepadConnected = function(d) {
            if (d.type !== Gamepad.POSE_ENABLED)
                d.leftStick && d.onleftstickchanged(function(k) {
                    o._teleportationInitialized && o.teleportationEnabled && (!o._leftController && !o._rightController || o._leftController && !o._leftController._activePointer && o._rightController && !o._rightController._activePointer) && (o._checkTeleportWithRay(k, o._cameraGazer),
                    o._checkTeleportBackwards(k, o._cameraGazer))
                }),
                d.rightStick && d.onrightstickchanged(function(k) {
                    o._teleportationInitialized && o._checkRotate(k, o._cameraGazer)
                }),
                d.type === Gamepad.XBOX && (d.onbuttondown(function(k) {
                    o._interactionsEnabled && k === Xbox360Button.A && o._cameraGazer._selectionPointerDown()
                }),
                d.onbuttonup(function(k) {
                    o._interactionsEnabled && k === Xbox360Button.A && o._cameraGazer._selectionPointerUp()
                }));
            else {
                var _ = d
                  , b = new VRExperienceHelperControllerGazer(_,o._scene,o._cameraGazer._gazeTracker);
                _.hand === "right" || o._leftController && o._leftController.webVRController != _ ? o._rightController = b : o._leftController = b,
                o._tryEnableInteractionOnController(b)
            }
        }
        ,
        this._tryEnableInteractionOnController = function(d) {
            o._interactionsRequested && !d._interactionsEnabled && o._enableInteractionOnController(d),
            o._teleportationRequested && !d._teleportationEnabled && o._enableTeleportationOnController(d)
        }
        ,
        this._onNewGamepadDisconnected = function(d) {
            d instanceof WebVRController && (d.hand === "left" && o._leftController != null && (o._leftController.dispose(),
            o._leftController = null),
            d.hand === "right" && o._rightController != null && (o._rightController.dispose(),
            o._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 s = "getVRDisplays"in navigator;
        if (!s && i.useXR === void 0 && (i.useXR = !0),
        i.createFallbackVRDeviceOrientationFreeCamera === void 0 && (i.createFallbackVRDeviceOrientationFreeCamera = !0),
        i.createDeviceOrientationCamera === void 0 && (i.createDeviceOrientationCamera = !0),
        i.laserToggle === void 0 && (i.laserToggle = !0),
        i.defaultHeight === void 0 && (i.defaultHeight = 1.7),
        i.useCustomVRButton && (this._useCustomVRButton = !0,
        i.customVRButton && (this._btnVR = i.customVRButton)),
        i.rayLength && (this._rayLength = i.rayLength),
        this._defaultHeight = i.defaultHeight,
        i.positionScale && (this._rayLength *= i.positionScale,
        this._defaultHeight *= i.positionScale),
        this._hasEnteredVR = !1,
        this._scene.activeCamera ? this._position = this._scene.activeCamera.position.clone() : this._position = new Vector3(0,this._defaultHeight,0),
        i.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 c = this._scene.activeCamera;
                c.rotationQuaternion ? this._deviceOrientationCamera.rotationQuaternion.copyFrom(c.rotationQuaternion) : this._deviceOrientationCamera.rotationQuaternion.copyFrom(Quaternion.RotationYawPitchRoll(c.rotation.y, c.rotation.x, c.rotation.z)),
                this._deviceOrientationCamera.rotation = c.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(d) {
            d ? (Logger$2.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),
            e.createDefaultXRExperienceAsync({
                floorMeshes: i.floorMeshes || []
            }).then(function(_) {
                o.xr = _,
                o.xrTestDone = !0,
                o._cameraGazer = new VRExperienceHelperCameraGazer(function() {
                    return o.xr.baseExperience.camera
                }
                ,e),
                o.xr.baseExperience.onStateChangedObservable.add(function(b) {
                    switch (b) {
                    case WebXRState.ENTERING_XR:
                        o.onEnteringVRObservable.notifyObservers(o),
                        o._interactionsEnabled || o.xr.pointerSelection.detach(),
                        o.xr.pointerSelection.displayLaserPointer = o._displayLaserPointer;
                        break;
                    case WebXRState.EXITING_XR:
                        o.onExitingVRObservable.notifyObservers(o),
                        o._scene.getEngine().resize();
                        break;
                    case WebXRState.IN_XR:
                        o._hasEnteredVR = !0;
                        break;
                    case WebXRState.NOT_IN_XR:
                        o._hasEnteredVR = !1;
                        break
                    }
                })
            })) : o.completeVRInit(e, i)
        }) : this.completeVRInit(e, i)
    }
    return Object.defineProperty(a.prototype, "onEnteringVR", {
        get: function() {
            return this.onEnteringVRObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onExitingVR", {
        get: function() {
            return this.onExitingVRObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "onControllerMeshLoaded", {
        get: function() {
            return this.onControllerMeshLoadedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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(a.prototype, "leftControllerGazeTrackerMesh", {
        get: function() {
            return this._leftController ? this._leftController._gazeTracker : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "rightControllerGazeTrackerMesh", {
        get: function() {
            return this._rightController ? this._rightController._gazeTracker : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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(a.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(a.prototype, "deviceOrientationCamera", {
        get: function() {
            return this._deviceOrientationCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "currentVRCamera", {
        get: function() {
            return this._webVRready ? this._webVRCamera : this._scene.activeCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "webVRCamera", {
        get: function() {
            return this._webVRCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "vrDeviceOrientationCamera", {
        get: function() {
            return this._vrDeviceOrientationCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "vrButton", {
        get: function() {
            return this._btnVR
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.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
    }),
    a.prototype.completeVRInit = function(e, i) {
        var o = this;
        if (this.xrTestDone = !0,
        i.createFallbackVRDeviceOrientationFreeCamera && (i.useMultiview && (i.vrDeviceOrientationCameraMetrics || (i.vrDeviceOrientationCameraMetrics = VRCameraMetrics.GetDefault()),
        i.vrDeviceOrientationCameraMetrics.multiviewEnabled = !0),
        this._vrDeviceOrientationCamera = new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene,!0,i.vrDeviceOrientationCameraMetrics),
        this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE),
        this._webVRCamera = new WebVRFreeCamera("WebVRHelper",this._position,this._scene,i),
        this._webVRCamera.useStandingMatrix(),
        this._cameraGazer = new VRExperienceHelperCameraGazer(function() {
            return o.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 s = 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"
              , c = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + s + "); 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) }";
            c += ".babylonVRicon.vrdisplaypresenting { display: none; }";
            var d = document.createElement("style");
            d.appendChild(document.createTextNode(c)),
            document.getElementsByTagName("head")[0].appendChild(d),
            this.moveButtonToBottomRight()
        }
        this._btnVR && this._btnVR.addEventListener("click", function() {
            o.isInVRMode ? o._scene.getEngine().disableVR() : o.enterVR()
        });
        var _ = this._scene.getEngine().getHostWindow();
        !_ || (_.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,
        i.createFallbackVRDeviceOrientationFreeCamera ? this.displayVRButton() : this._scene.getEngine().onVRDisplayChangedObservable.add(function(b) {
            b.vrDisplay && o.displayVRButton()
        }),
        this._onKeyDown = function(b) {
            b.keyCode === 27 && o.isInVRMode && o.exitVR()
        }
        ,
        document.addEventListener("keydown", this._onKeyDown),
        this._scene.onPrePointerObservable.add(function() {
            o._hasEnteredVR && o.exitVROnDoubleTap && (o.exitVR(),
            o._fullscreenVRpresenting && o._scene.getEngine().exitFullscreen())
        }, PointerEventTypes.POINTERDOUBLETAP, !1),
        this._onVRDisplayChanged = function(b) {
            return o.onVRDisplayChanged(b)
        }
        ,
        this._onVrDisplayPresentChange = function() {
            return o.onVrDisplayPresentChange()
        }
        ,
        this._onVRRequestPresentStart = function() {
            o._webVRrequesting = !0,
            o.updateButtonVisibility()
        }
        ,
        this._onVRRequestPresentComplete = function() {
            o._webVRrequesting = !1,
            o.updateButtonVisibility()
        }
        ,
        e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),
        e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),
        e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),
        _.addEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange),
        e.onDisposeObservable.add(function() {
            o.dispose()
        }),
        this._webVRCamera.onControllerMeshLoadedObservable.add(function(b) {
            return o._onDefaultMeshLoaded(b)
        }),
        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(b) {
            o._interactionsEnabled && e.activeCamera === o.vrDeviceOrientationCamera && b.event.pointerType === "mouse" && (b.type === PointerEventTypes.POINTERDOWN ? o._cameraGazer._selectionPointerDown() : b.type === PointerEventTypes.POINTERUP && o._cameraGazer._selectionPointerUp())
        }),
        this.webVROptions.floorMeshes && this.enableTeleportation({
            floorMeshes: this.webVROptions.floorMeshes
        }))
    }
    ,
    a.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 (i) {
            Logger$2.Warn("Error in your custom logic onControllerMeshLoaded: " + i)
        }
    }
    ,
    Object.defineProperty(a.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
    }),
    a.prototype.onVrDisplayPresentChange = function() {
        var e = this._scene.getEngine().getVRDevice();
        if (e) {
            var i = this._webVRpresenting;
            this._webVRpresenting = e.isPresenting,
            i && !this._webVRpresenting && this.exitVR()
        } else
            Logger$2.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");
        this.updateButtonVisibility()
    }
    ,
    a.prototype.onVRDisplayChanged = function(e) {
        this._webVRsupported = e.vrSupported,
        this._webVRready = !!e.vrDisplay,
        this._webVRpresenting = e.vrDisplay && e.vrDisplay.isPresenting,
        this.updateButtonVisibility()
    }
    ,
    a.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"
        }
    }
    ,
    a.prototype.displayVRButton = function() {
        !this._useCustomVRButton && !this._btnVRDisplayed && this._btnVR && (document.body.appendChild(this._btnVR),
        this._btnVRDisplayed = !0)
    }
    ,
    a.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")))
    }
    ,
    a.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 (d) {
                Logger$2.Warn("Error in your custom logic onEnteringVR: " + d)
            }
        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 i = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y
                  , o = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y
                  , s = o - i
                  , c = this.webVRCamera.rotationQuaternion.toEulerAngles().y;
                this.webVRCamera.rotationQuaternion = Quaternion.FromEulerAngles(0, c + s, 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(d) {
            e.onAfterEnteringVRObservable.notifyObservers({
                success: d
            })
        }),
        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(d) {
            d && d._activatePointer()
        }),
        this._hasEnteredVR = !0)
    }
    ,
    a.prototype.exitVR = function() {
        if (this.xr) {
            this.xr.baseExperience.exitXRAsync();
            return
        }
        if (this._hasEnteredVR) {
            if (this.onExitingVRObservable)
                try {
                    this.onExitingVRObservable.notifyObservers(this)
                } catch (i) {
                    Logger$2.Warn("Error in your custom logic onExitingVR: " + i)
                }
            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(i) {
                i && i._deactivatePointer()
            }),
            this._hasEnteredVR = !1;
            var e = this._scene.getEngine();
            e._onVrDisplayPresentChange && e._onVrDisplayPresentChange()
        }
    }
    ,
    Object.defineProperty(a.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
    }),
    a.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(i) {
                return i.isVisible && (i.isPickable || i.name === e._floorMeshName)
            }
            ,
            this.meshSelectionPredicate = function() {
                return !0
            }
            ,
            this._raySelectionPredicate = function(i) {
                return e._isTeleportationFloor(i) || i.name.indexOf("gazeTracker") === -1 && i.name.indexOf("teleportationTarget") === -1 && i.name.indexOf("torusTeleportation") === -1 ? e.raySelectionPredicate(i) : !1
            }
            ,
            this._interactionsEnabled = !0
        }
    }
    ,
    Object.defineProperty(a.prototype, "_noControllerIsActive", {
        get: function() {
            return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer)
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype._isTeleportationFloor = function(e) {
        for (var i = 0; i < this._floorMeshesCollection.length; i++)
            if (this._floorMeshesCollection[i].id === e.id)
                return !0;
        return !!(this._floorMeshName && e.name === this._floorMeshName)
    }
    ,
    a.prototype.addFloorMesh = function(e) {
        !this._floorMeshesCollection || this._floorMeshesCollection.indexOf(e) > -1 || this._floorMeshesCollection.push(e)
    }
    ,
    a.prototype.removeFloorMesh = function(e) {
        if (!!this._floorMeshesCollection) {
            var i = this._floorMeshesCollection.indexOf(e);
            i !== -1 && this._floorMeshesCollection.splice(i, 1)
        }
    }
    ,
    a.prototype.enableTeleportation = function(e) {
        var i = this;
        if (e === void 0 && (e = {}),
        !this._teleportationInitialized) {
            if (this._teleportationRequested = !0,
            this.enableInteractions(),
            this.webVROptions.useXR && (e.floorMeshes || e.floorMeshName)) {
                var o = e.floorMeshes || [];
                if (!o.length) {
                    var s = this._scene.getMeshByName(e.floorMeshName);
                    s && o.push(s)
                }
                if (this.xr) {
                    o.forEach(function(_) {
                        i.xr.teleportation.addFloorMesh(_)
                    }),
                    this.xr.teleportation.attached || this.xr.teleportation.attach();
                    return
                } else if (!this.xrTestDone) {
                    var c = function() {
                        i.xrTestDone && (i._scene.unregisterBeforeRender(c),
                        i.xr ? i.xr.teleportation.attached || i.xr.teleportation.attach() : i.enableTeleportation(e))
                    };
                    this._scene.registerBeforeRender(c);
                    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 d = new ImageProcessingConfiguration;
            d.vignetteColor = new Color4(0,0,0,0),
            d.vignetteEnabled = !0,
            this._postProcessMove = new ImageProcessingPostProcess("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,d),
            this._webVRCamera.detachPostProcess(this._postProcessMove),
            this._teleportationInitialized = !0,
            this._isDefaultTeleportationTarget && (this._createTeleportationCircles(),
            this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))
        }
    }
    ,
    a.prototype._enableInteractionOnController = function(e) {
        var i = this
          , o = e.webVRController.mesh;
        o && (e._interactionsEnabled = !0,
        this.isInVRMode && this._displayLaserPointer && e._activatePointer(),
        this.webVROptions.laserToggle && e.webVRController.onMainButtonStateChangedObservable.add(function(s) {
            i._displayLaserPointer && s.value === 1 && (e._activePointer ? e._deactivatePointer() : e._activatePointer(),
            i.displayGaze && (e._gazeTracker.isVisible = e._activePointer))
        }),
        e.webVRController.onTriggerStateChangedObservable.add(function(s) {
            var c = e;
            i._noControllerIsActive && (c = i._cameraGazer),
            c._pointerDownOnMeshAsked ? s.value < i._padSensibilityDown && c._selectionPointerUp() : s.value > i._padSensibilityUp && c._selectionPointerDown()
        }))
    }
    ,
    a.prototype._checkTeleportWithRay = function(e, i) {
        this._teleportationRequestInitiated && !i._teleportationRequestInitiated || (i._teleportationRequestInitiated ? Math.sqrt(e.y * e.y + e.x * e.x) < this._padSensibilityDown && (this._teleportActive && this.teleportCamera(this._haloCenter),
        i._teleportationRequestInitiated = !1) : e.y < -this._padSensibilityUp && i._dpadPressed && (i._activatePointer(),
        i._teleportationRequestInitiated = !0))
    }
    ,
    a.prototype._checkRotate = function(e, i) {
        i._teleportationRequestInitiated || (i._rotationLeftAsked ? e.x > -this._padSensibilityDown && (i._rotationLeftAsked = !1) : e.x < -this._padSensibilityUp && i._dpadPressed && (i._rotationLeftAsked = !0,
        this._rotationAllowed && this._rotateCamera(!1)),
        i._rotationRightAsked ? e.x < this._padSensibilityDown && (i._rotationRightAsked = !1) : e.x > this._padSensibilityUp && i._dpadPressed && (i._rotationRightAsked = !0,
        this._rotationAllowed && this._rotateCamera(!0)))
    }
    ,
    a.prototype._checkTeleportBackwards = function(e, i) {
        if (!i._teleportationRequestInitiated)
            if (e.y > this._padSensibilityUp && i._dpadPressed) {
                if (!i._teleportationBackRequestInitiated) {
                    if (!this.currentVRCamera)
                        return;
                    var o = Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix())
                      , s = this.currentVRCamera.position;
                    this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion && (o = this.currentVRCamera.deviceRotationQuaternion,
                    s = this.currentVRCamera.devicePosition),
                    o.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 c = new Ray(s,this._workingVector)
                      , d = this._scene.pickWithRay(c, this._raySelectionPredicate);
                    d && d.pickedPoint && d.pickedMesh && this._isTeleportationFloor(d.pickedMesh) && d.distance < 5 && this.teleportCamera(d.pickedPoint),
                    i._teleportationBackRequestInitiated = !0
                }
            } else
                i._teleportationBackRequestInitiated = !1
    }
    ,
    a.prototype._enableTeleportationOnController = function(e) {
        var i = this
          , o = e.webVRController.mesh;
        o && (e._interactionsEnabled || this._enableInteractionOnController(e),
        e._interactionsEnabled = !0,
        e._teleportationEnabled = !0,
        e.webVRController.controllerType === PoseEnabledControllerType.VIVE && (e._dpadPressed = !1,
        e.webVRController.onPadStateChangedObservable.add(function(s) {
            e._dpadPressed = s.pressed,
            e._dpadPressed || (e._rotationLeftAsked = !1,
            e._rotationRightAsked = !1,
            e._teleportationBackRequestInitiated = !1)
        })),
        e.webVRController.onPadValuesChangedObservable.add(function(s) {
            i.teleportationEnabled && (i._checkTeleportBackwards(s, e),
            i._checkTeleportWithRay(s, e)),
            i._checkRotate(s, e)
        }))
    }
    ,
    a.prototype._createTeleportationCircles = function() {
        this._teleportationTarget = CreateGround("teleportationTarget", {
            width: 2,
            height: 2,
            subdivisions: 2
        }, this._scene),
        this._teleportationTarget.isPickable = !1;
        var e = 512
          , i = new DynamicTexture("DynamicTexture",e,this._scene,!0);
        i.hasAlpha = !0;
        var o = i.getContext()
          , s = e / 2
          , c = e / 2
          , d = 200;
        o.beginPath(),
        o.arc(s, c, d, 0, 2 * Math.PI, !1),
        o.fillStyle = this._teleportationFillColor,
        o.fill(),
        o.lineWidth = 10,
        o.strokeStyle = this._teleportationBorderColor,
        o.stroke(),
        o.closePath(),
        i.update();
        var _ = new StandardMaterial("TextPlaneMaterial",this._scene);
        _.diffuseTexture = i,
        this._teleportationTarget.material = _;
        var b = CreateTorus("torusTeleportation", {
            diameter: .75,
            thickness: .1,
            tessellation: 25,
            updatable: !1
        }, this._scene);
        b.isPickable = !1,
        b.parent = this._teleportationTarget;
        var k = new Animation("animationInnerCircle","position.y",30,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE)
          , j = [];
        j.push({
            frame: 0,
            value: 0
        }),
        j.push({
            frame: 30,
            value: .4
        }),
        j.push({
            frame: 60,
            value: 0
        }),
        k.setKeys(j);
        var $ = new SineEase;
        $.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),
        k.setEasingFunction($),
        b.animations = [],
        b.animations.push(k),
        this._scene.beginAnimation(b, 0, 60, !0),
        this._hideTeleportationTarget()
    }
    ,
    a.prototype._displayTeleportationTarget = function() {
        this._teleportActive = !0,
        this._teleportationInitialized && (this._teleportationTarget.isVisible = !0,
        this._isDefaultTeleportationTarget && (this._teleportationTarget.getChildren()[0].isVisible = !0))
    }
    ,
    a.prototype._hideTeleportationTarget = function() {
        this._teleportActive = !1,
        this._teleportationInitialized && (this._teleportationTarget.isVisible = !1,
        this._isDefaultTeleportationTarget && (this._teleportationTarget.getChildren()[0].isVisible = !1))
    }
    ,
    a.prototype._rotateCamera = function(e) {
        var i = this;
        if (this.currentVRCamera instanceof FreeCamera) {
            e ? this._rotationAngle++ : this._rotationAngle--,
            this.currentVRCamera.animations = [];
            var o = Quaternion.FromRotationMatrix(Matrix.RotationY(Math.PI / 4 * this._rotationAngle))
              , s = new Animation("animationRotation","rotationQuaternion",90,Animation.ANIMATIONTYPE_QUATERNION,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , c = [];
            c.push({
                frame: 0,
                value: this.currentVRCamera.rotationQuaternion
            }),
            c.push({
                frame: 6,
                value: o
            }),
            s.setKeys(c),
            s.setEasingFunction(this._circleEase),
            this.currentVRCamera.animations.push(s),
            this._postProcessMove.animations = [];
            var d = new Animation("animationPP","vignetteWeight",90,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , _ = [];
            _.push({
                frame: 0,
                value: 0
            }),
            _.push({
                frame: 3,
                value: 4
            }),
            _.push({
                frame: 6,
                value: 0
            }),
            d.setKeys(_),
            d.setEasingFunction(this._circleEase),
            this._postProcessMove.animations.push(d);
            var b = new Animation("animationPP2","vignetteStretch",90,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , k = [];
            k.push({
                frame: 0,
                value: 0
            }),
            k.push({
                frame: 3,
                value: 10
            }),
            k.push({
                frame: 6,
                value: 0
            }),
            b.setKeys(k),
            b.setEasingFunction(this._circleEase),
            this._postProcessMove.animations.push(b),
            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() {
                i._webVRCamera.detachPostProcess(i._postProcessMove)
            }),
            this._scene.beginAnimation(this.currentVRCamera, 0, 6, !1, 1)
        }
    }
    ,
    a.prototype._moveTeleportationSelectorTo = function(e, i, o) {
        if (e.pickedPoint) {
            i._teleportationRequestInitiated && (this._displayTeleportationTarget(),
            this._haloCenter.copyFrom(e.pickedPoint),
            this._teleportationTarget.position.copyFrom(e.pickedPoint));
            var s = this._convertNormalToDirectionOfRay(e.getNormal(!0, !1), o);
            if (s) {
                var c = Vector3.Cross(Axis.Y, s)
                  , d = Vector3.Cross(s, c);
                Vector3.RotationFromAxisToRef(d, s, c, this._teleportationTarget.rotation)
            }
            this._teleportationTarget.position.y += .1
        }
    }
    ,
    a.prototype.teleportCamera = function(e) {
        var i = 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 o = 90, s, c;
            if (this._teleportationMode == a.TELEPORTATIONMODE_CONSTANTSPEED) {
                c = o;
                var d = Vector3.Distance(this.currentVRCamera.position, this._workingVector);
                s = this._teleportationSpeed / d
            } else
                c = Math.round(this._teleportationTime * o / 1e3),
                s = 1;
            this.currentVRCamera.animations = [];
            var _ = new Animation("animationCameraTeleportation","position",o,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , b = [{
                frame: 0,
                value: this.currentVRCamera.position
            }, {
                frame: c,
                value: this._workingVector
            }];
            _.setKeys(b),
            _.setEasingFunction(this._teleportationEasing),
            this.currentVRCamera.animations.push(_),
            this._postProcessMove.animations = [];
            var k = Math.round(c / 2)
              , j = new Animation("animationPP","vignetteWeight",o,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , $ = [];
            $.push({
                frame: 0,
                value: 0
            }),
            $.push({
                frame: k,
                value: 8
            }),
            $.push({
                frame: c,
                value: 0
            }),
            j.setKeys($),
            this._postProcessMove.animations.push(j);
            var _e = new Animation("animationPP2","vignetteStretch",o,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , et = [];
            et.push({
                frame: 0,
                value: 0
            }),
            et.push({
                frame: k,
                value: 10
            }),
            et.push({
                frame: c,
                value: 0
            }),
            _e.setKeys(et),
            this._postProcessMove.animations.push(_e),
            this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0,
            this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0,
            this._webVRCamera.attachPostProcess(this._postProcessMove),
            this._scene.beginAnimation(this._postProcessMove, 0, c, !1, s, function() {
                i._webVRCamera.detachPostProcess(i._postProcessMove)
            }),
            this._scene.beginAnimation(this.currentVRCamera, 0, c, !1, s, function() {
                i.onAfterCameraTeleport.notifyObservers(i._workingVector)
            }),
            this._hideTeleportationTarget()
        }
    }
    ,
    a.prototype._convertNormalToDirectionOfRay = function(e, i) {
        if (e) {
            var o = Math.acos(Vector3.Dot(e, i.direction));
            o < Math.PI / 2 && e.scaleInPlace(-1)
        }
        return e
    }
    ,
    a.prototype._castRayAndSelectObject = function(e) {
        if (this.currentVRCamera instanceof FreeCamera) {
            var i = e._getForwardRay(this._rayLength)
              , o = this._scene.pickWithRay(i, this._raySelectionPredicate);
            if (o && this._scene.simulatePointerMove(o, {
                pointerId: e._id
            }),
            e._currentHit = o,
            o && o.pickedPoint) {
                if (this._displayGaze) {
                    var s = 1;
                    e._gazeTracker.isVisible = !0,
                    e._isActionableMesh && (s = 3),
                    this.updateGazeTrackerScale && (e._gazeTracker.scaling.x = o.distance * s,
                    e._gazeTracker.scaling.y = o.distance * s,
                    e._gazeTracker.scaling.z = o.distance * s);
                    var c = this._convertNormalToDirectionOfRay(o.getNormal(), i)
                      , d = .002;
                    if (c) {
                        var _ = Vector3.Cross(Axis.Y, c)
                          , b = Vector3.Cross(c, _);
                        Vector3.RotationFromAxisToRef(b, c, _, e._gazeTracker.rotation)
                    }
                    e._gazeTracker.position.copyFrom(o.pickedPoint),
                    e._gazeTracker.position.x < 0 ? e._gazeTracker.position.x += d : e._gazeTracker.position.x -= d,
                    e._gazeTracker.position.y < 0 ? e._gazeTracker.position.y += d : e._gazeTracker.position.y -= d,
                    e._gazeTracker.position.z < 0 ? e._gazeTracker.position.z += d : e._gazeTracker.position.z -= d
                }
                e._updatePointerDistance(o.distance)
            } else
                e._updatePointerDistance(),
                e._gazeTracker.isVisible = !1;
            if (o && o.pickedMesh) {
                if (this._teleportationInitialized && this._isTeleportationFloor(o.pickedMesh) && o.pickedPoint) {
                    e._currentMeshSelected && !this._isTeleportationFloor(e._currentMeshSelected) && this._notifySelectedMeshUnselected(e._currentMeshSelected),
                    e._currentMeshSelected = null,
                    e._teleportationRequestInitiated && this._moveTeleportationSelectorTo(o, e, i);
                    return
                }
                if (o.pickedMesh !== e._currentMeshSelected)
                    if (this.meshSelectionPredicate(o.pickedMesh)) {
                        this.onNewMeshPicked.notifyObservers(o),
                        e._currentMeshSelected = o.pickedMesh,
                        o.pickedMesh.isPickable && o.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(o.pickedMesh);
                            var k = e;
                            k.webVRController && this.onMeshSelectedWithController.notifyObservers({
                                mesh: o.pickedMesh,
                                controller: k.webVRController
                            })
                        } catch (j) {
                            Logger$2.Warn("Error while raising onNewMeshSelected or onMeshSelectedWithController: " + j)
                        }
                    } 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)
        }
    }
    ,
    a.prototype._notifySelectedMeshUnselected = function(e) {
        e && this.onSelectedMeshUnselected.notifyObservers(e)
    }
    ,
    a.prototype.setLaserColor = function(e, i) {
        i === void 0 && (i = this._pickedLaserColor),
        this._laserColor = e,
        this._pickedLaserColor = i
    }
    ,
    a.prototype.setLaserLightingState = function(e) {
        e === void 0 && (e = !0),
        this._leftController && this._leftController._setLaserPointerLightingDisabled(!e),
        this._rightController && this._rightController._setLaserPointerLightingDisabled(!e)
    }
    ,
    a.prototype.setGazeColor = function(e, i) {
        i === void 0 && (i = this._pickedGazeColor),
        this._gazeColor = e,
        this._pickedGazeColor = i
    }
    ,
    a.prototype.changeLaserColor = function(e) {
        !this.updateControllerLaserColor || (this._leftController && this._leftController._setLaserPointerColor(e),
        this._rightController && this._rightController._setLaserPointerColor(e))
    }
    ,
    a.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))
    }
    ,
    a.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)
    }
    ,
    a.prototype.getClassName = function() {
        return "VRExperienceHelper"
    }
    ,
    a.TELEPORTATIONMODE_CONSTANTTIME = 0,
    a.TELEPORTATIONMODE_CONSTANTSPEED = 1,
    a
}()
  , _ENVTextureLoader = function() {
    function a() {
        this.supportCascades = !1
    }
    return a.prototype.canLoad = function(e) {
        return EndsWith(e, ".env")
    }
    ,
    a.prototype.loadCubeData = function(e, i, o, s, c) {
        if (!Array.isArray(e)) {
            var d = GetEnvInfo(e);
            if (d) {
                i.width = d.width,
                i.height = d.width;
                try {
                    UploadEnvSpherical(i, d),
                    UploadEnvLevelsAsync(i, e, d).then(function() {
                        i.isReady = !0,
                        i.onLoadedObservable.notifyObservers(i),
                        i.onLoadedObservable.clear(),
                        s && s()
                    }, function(_) {
                        c == null || c("Can not upload environment levels", _)
                    })
                } catch (_) {
                    c == null || c("Can not upload environment file", _)
                }
            } else
                c && c("Can not parse the environment file", null)
        }
    }
    ,
    a.prototype.loadData = function(e, i, o) {
        throw ".env not supported in 2d."
    }
    ,
    a
}();
Engine._TextureLoaders.push(new _ENVTextureLoader);
var KhronosTextureContainer = function() {
    function a(e, i, o, s) {
        if (this.data = e,
        this.isInvalid = !1,
        !a.IsValid(e)) {
            this.isInvalid = !0,
            Logger$2.Error("texture missing KTX identifier");
            return
        }
        var c = Uint32Array.BYTES_PER_ELEMENT
          , d = new DataView(this.data.buffer,this.data.byteOffset + 12,13 * c)
          , _ = d.getUint32(0, !0)
          , b = _ === 67305985;
        if (this.glType = d.getUint32(1 * c, b),
        this.glTypeSize = d.getUint32(2 * c, b),
        this.glFormat = d.getUint32(3 * c, b),
        this.glInternalFormat = d.getUint32(4 * c, b),
        this.glBaseInternalFormat = d.getUint32(5 * c, b),
        this.pixelWidth = d.getUint32(6 * c, b),
        this.pixelHeight = d.getUint32(7 * c, b),
        this.pixelDepth = d.getUint32(8 * c, b),
        this.numberOfArrayElements = d.getUint32(9 * c, b),
        this.numberOfFaces = d.getUint32(10 * c, b),
        this.numberOfMipmapLevels = d.getUint32(11 * c, b),
        this.bytesOfKeyValueData = d.getUint32(12 * c, b),
        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 !== i) {
            Logger$2.Error("number of faces expected" + i + ", but found " + this.numberOfFaces);
            return
        }
        this.loadType = a.COMPRESSED_2D
    }
    return a.prototype.uploadLevels = function(e, i) {
        switch (this.loadType) {
        case a.COMPRESSED_2D:
            this._upload2DCompressedLevels(e, i);
            break
        }
    }
    ,
    a.prototype._upload2DCompressedLevels = function(e, i) {
        for (var o = a.HEADER_LEN + this.bytesOfKeyValueData, s = this.pixelWidth, c = this.pixelHeight, d = i ? this.numberOfMipmapLevels : 1, _ = 0; _ < d; _++) {
            var b = new Int32Array(this.data.buffer,this.data.byteOffset + o,1)[0];
            o += 4;
            for (var k = 0; k < this.numberOfFaces; k++) {
                var j = new Uint8Array(this.data.buffer,this.data.byteOffset + o,b)
                  , $ = e.getEngine();
                $._uploadCompressedDataToTextureDirectly(e, this.glInternalFormat, s, c, j, k, _),
                o += b,
                o += 3 - (b + 3) % 4
            }
            s = Math.max(1, s * .5),
            c = Math.max(1, c * .5)
        }
    }
    ,
    a.IsValid = function(e) {
        if (e.byteLength >= 12) {
            var i = new Uint8Array(e.buffer,e.byteOffset,12);
            if (i[0] === 171 && i[1] === 75 && i[2] === 84 && i[3] === 88 && i[4] === 32 && i[5] === 49 && i[6] === 49 && i[7] === 187 && i[8] === 13 && i[9] === 10 && i[10] === 26 && i[11] === 10)
                return !0
        }
        return !1
    }
    ,
    a.HEADER_LEN = 12 + 13 * 4,
    a.COMPRESSED_2D = 0,
    a.COMPRESSED_3D = 1,
    a.TEX_2D = 2,
    a.TEX_3D = 3,
    a
}()
  , KhronosTextureContainer2 = function() {
    function a(e, i) {
        i === void 0 && (i = a.DefaultNumWorkers),
        this._engine = e,
        a._Initialized || a._CreateWorkerPool(i)
    }
    return a.GetDefaultNumWorkers = function() {
        return typeof navigator != "object" || !navigator.hardwareConcurrency ? 1 : Math.min(Math.floor(navigator.hardwareConcurrency * .5), 4)
    }
    ,
    a._CreateWorkerPool = function(e) {
        this._Initialized = !0,
        e && typeof Worker == "function" ? a._WorkerPoolPromise = new Promise(function(i) {
            for (var o = "(" + workerFunc + ")()", s = URL.createObjectURL(new Blob([o],{
                type: "application/javascript"
            })), c = new Array(e), d = 0; d < c.length; d++)
                c[d] = new Promise(function(_, b) {
                    var k = new Worker(s)
                      , j = function(_e) {
                        k.removeEventListener("error", j),
                        k.removeEventListener("message", $),
                        b(_e)
                    }
                      , $ = function(_e) {
                        _e.data.action === "init" && (k.removeEventListener("error", j),
                        k.removeEventListener("message", $),
                        _(k))
                    };
                    k.addEventListener("error", j),
                    k.addEventListener("message", $),
                    k.postMessage({
                        action: "init",
                        urls: a.URLConfig
                    })
                }
                );
            Promise.all(c).then(function(_) {
                i(new WorkerPool(_))
            })
        }
        ) : typeof KTX2DECODER == "undefined" ? a._NoWorkerPromise = Tools.LoadScriptAsync(a.URLConfig.jsDecoderModule).then(function() {
            KTX2DECODER.MSCTranscoder.UseFromWorkerThread = !1,
            KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = !0;
            var i = a.URLConfig;
            i.wasmUASTCToASTC !== null && (KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL = i.wasmUASTCToASTC),
            i.wasmUASTCToBC7 !== null && (KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL = i.wasmUASTCToBC7),
            i.wasmUASTCToRGBA_UNORM !== null && (KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = i.wasmUASTCToRGBA_UNORM),
            i.wasmUASTCToRGBA_SRGB !== null && (KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = i.wasmUASTCToRGBA_SRGB),
            i.jsMSCTranscoder !== null && (KTX2DECODER.MSCTranscoder.JSModuleURL = i.jsMSCTranscoder),
            i.wasmMSCTranscoder !== null && (KTX2DECODER.MSCTranscoder.WasmModuleURL = i.wasmMSCTranscoder),
            i.wasmZSTDDecoder !== null && (KTX2DECODER.ZSTDDecoder.WasmModuleURL = i.wasmZSTDDecoder)
        }) : (KTX2DECODER.MSCTranscoder.UseFromWorkerThread = !1,
        KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = !0)
    }
    ,
    a.prototype.uploadAsync = function(e, i, o) {
        var s = this
          , c = this._engine.getCaps()
          , d = {
            astc: !!c.astc,
            bptc: !!c.bptc,
            s3tc: !!c.s3tc,
            pvrtc: !!c.pvrtc,
            etc2: !!c.etc2,
            etc1: !!c.etc1
        };
        return a._WorkerPoolPromise ? a._WorkerPoolPromise.then(function(_) {
            return new Promise(function(b, k) {
                _.push(function(j, $) {
                    var _e = function(tt) {
                        j.removeEventListener("error", _e),
                        j.removeEventListener("message", et),
                        k(tt),
                        $()
                    }
                      , et = function(tt) {
                        if (tt.data.action === "decoded") {
                            if (j.removeEventListener("error", _e),
                            j.removeEventListener("message", et),
                            !tt.data.success)
                                k({
                                    message: tt.data.msg
                                });
                            else
                                try {
                                    s._createTexture(tt.data.decodedData, i, o),
                                    b()
                                } catch (rt) {
                                    k({
                                        message: rt
                                    })
                                }
                            $()
                        }
                    };
                    j.addEventListener("error", _e),
                    j.addEventListener("message", et),
                    j.postMessage({
                        action: "decode",
                        data: e,
                        caps: d,
                        options: o
                    })
                })
            }
            )
        }) : a._NoWorkerPromise ? a._NoWorkerPromise.then(function() {
            return new Promise(function(_, b) {
                a._Ktx2Decoder || (a._Ktx2Decoder = new KTX2DECODER.KTX2Decoder),
                a._Ktx2Decoder.decode(e, c).then(function(k) {
                    s._createTexture(k, i),
                    _()
                }).catch(function(k) {
                    b({
                        message: k
                    })
                })
            }
            )
        }) : new Promise(function(_, b) {
            a._Ktx2Decoder || (a._Ktx2Decoder = new KTX2DECODER.KTX2Decoder),
            a._Ktx2Decoder.decode(e, c).then(function(k) {
                s._createTexture(k, i),
                _()
            }).catch(function(k) {
                b({
                    message: k
                })
            })
        }
        )
    }
    ,
    a.prototype.dispose = function() {
        a._WorkerPoolPromise && a._WorkerPoolPromise.then(function(e) {
            e.dispose()
        }),
        delete a._WorkerPoolPromise,
        delete a._NoWorkerPromise
    }
    ,
    a.prototype._createTexture = function(e, i, o) {
        var s = 3553;
        if (this._engine._bindTextureDirectly(s, i),
        o && (o.transcodedFormat = e.transcodedFormat,
        o.isInGammaSpace = e.isInGammaSpace,
        o.hasAlpha = e.hasAlpha,
        o.transcoderName = e.transcoderName),
        e.transcodedFormat === 32856 ? (i.type = 0,
        i.format = 5) : i.format = e.transcodedFormat,
        i._gammaSpace = e.isInGammaSpace,
        i.generateMipMaps = e.mipmaps.length > 1,
        e.errors)
            throw new Error("KTX2 container - could not transcode the data. " + e.errors);
        for (var c = 0; c < e.mipmaps.length; ++c) {
            var d = e.mipmaps[c];
            if (!d || !d.data)
                throw new Error("KTX2 container - could not transcode one of the image");
            e.transcodedFormat === 32856 ? (i.width = d.width,
            i.height = d.height,
            this._engine._uploadDataToTextureDirectly(i, d.data, 0, c, void 0, !0)) : this._engine._uploadCompressedDataToTextureDirectly(i, e.transcodedFormat, d.width, d.height, d.data, 0, c)
        }
        i._extension = ".ktx2",
        i.width = e.mipmaps[0].width,
        i.height = e.mipmaps[0].height,
        i.isReady = !0,
        this._engine._bindTextureDirectly(s, null)
    }
    ,
    a.IsValid = function(e) {
        if (e.byteLength >= 12) {
            var i = new Uint8Array(e.buffer,e.byteOffset,12);
            if (i[0] === 171 && i[1] === 75 && i[2] === 84 && i[3] === 88 && i[4] === 32 && i[5] === 50 && i[6] === 48 && i[7] === 187 && i[8] === 13 && i[9] === 10 && i[10] === 26 && i[11] === 10)
                return !0
        }
        return !1
    }
    ,
    a.URLConfig = {
        jsDecoderModule: "https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/babylon.ktx2Decoder.js",
        wasmUASTCToASTC: "https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/uastc_astc.wasm",
        wasmUASTCToBC7: "https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/uastc_bc7.wasm",
        wasmUASTCToRGBA_UNORM: "https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/uastc_rgba32_unorm.wasm",
        wasmUASTCToRGBA_SRGB: "https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/uastc_rgba32_srgb.wasm",
        jsMSCTranscoder: "https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/msc_basis_transcoder.js",
        wasmMSCTranscoder: "https://app-asset-1258211750.file.myqcloud.com/4/ktx2/ktx2decoder/ktx2Transcoders/msc_basis_transcoder.wasm",
        wasmZSTDDecoder: null
    },
    a.DefaultNumWorkers = a.GetDefaultNumWorkers(),
    a
}();
function workerFunc() {
    var a;
    onmessage = function(e) {
        if (!!e.data)
            switch (e.data.action) {
            case "init":
                var i = e.data.urls;
                importScripts(i.jsDecoderModule),
                i.wasmUASTCToASTC !== null && (KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL = i.wasmUASTCToASTC),
                i.wasmUASTCToBC7 !== null && (KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL = i.wasmUASTCToBC7),
                i.wasmUASTCToRGBA_UNORM !== null && (KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = i.wasmUASTCToRGBA_UNORM),
                i.wasmUASTCToRGBA_SRGB !== null && (KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = i.wasmUASTCToRGBA_SRGB),
                i.jsMSCTranscoder !== null && (KTX2DECODER.MSCTranscoder.JSModuleURL = i.jsMSCTranscoder),
                i.wasmMSCTranscoder !== null && (KTX2DECODER.MSCTranscoder.WasmModuleURL = i.wasmMSCTranscoder),
                i.wasmZSTDDecoder !== null && (KTX2DECODER.ZSTDDecoder.WasmModuleURL = i.wasmZSTDDecoder),
                a = new KTX2DECODER.KTX2Decoder,
                postMessage({
                    action: "init"
                });
                break;
            case "decode":
                a.decode(e.data.data, e.data.caps, e.data.options).then(function(o) {
                    for (var s = [], c = 0; c < o.mipmaps.length; ++c) {
                        var d = o.mipmaps[c];
                        d && d.data && s.push(d.data.buffer)
                    }
                    postMessage({
                        action: "decoded",
                        success: !0,
                        decodedData: o
                    }, s)
                }).catch(function(o) {
                    postMessage({
                        action: "decoded",
                        success: !1,
                        msg: o
                    })
                });
                break
            }
    }
}
var _KTXTextureLoader = function() {
    function a() {
        this.supportCascades = !1
    }
    return a.prototype.canLoad = function(e, i) {
        return EndsWith(e, ".ktx") || EndsWith(e, ".ktx2") || i === "image/ktx" || i === "image/ktx2"
    }
    ,
    a.prototype.loadCubeData = function(e, i, o, s, c) {
        if (!Array.isArray(e)) {
            i._invertVScale = !i.invertY;
            var d = i.getEngine()
              , _ = new KhronosTextureContainer(e,6)
              , b = _.numberOfMipmapLevels > 1 && i.generateMipMaps;
            d._unpackFlipY(!0),
            _.uploadLevels(i, i.generateMipMaps),
            i.width = _.pixelWidth,
            i.height = _.pixelHeight,
            d._setCubeMapTextureParams(i, b),
            i.isReady = !0,
            i.onLoadedObservable.notifyObservers(i),
            i.onLoadedObservable.clear(),
            s && s()
        }
    }
    ,
    a.prototype.loadData = function(e, i, o, s) {
        if (KhronosTextureContainer.IsValid(e)) {
            i._invertVScale = !i.invertY;
            var c = new KhronosTextureContainer(e,1);
            o(c.pixelWidth, c.pixelHeight, i.generateMipMaps, !0, function() {
                c.uploadLevels(i, i.generateMipMaps)
            }, c.isInvalid)
        } else if (KhronosTextureContainer2.IsValid(e)) {
            var d = new KhronosTextureContainer2(i.getEngine());
            d.uploadAsync(e, i, s).then(function() {
                o(i.width, i.height, i.generateMipMaps, !0, function() {}, !1)
            }, function(_) {
                Logger$2.Warn("Failed to load KTX2 texture data: " + _.message),
                o(0, 0, !1, !1, function() {}, !0)
            })
        } else
            Logger$2.Error("texture missing KTX identifier"),
            o(0, 0, !1, !1, function() {}, !0)
    }
    ,
    a
}();
Engine._TextureLoaders.unshift(new _KTXTextureLoader);
var WebXRCamera = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, Vector3.Zero(), o) || this;
        return c._xrSessionManager = s,
        c._firstFrame = !1,
        c._referenceQuaternion = Quaternion.Identity(),
        c._referencedPosition = new Vector3,
        c._trackingState = WebXRTrackingState.NOT_TRACKING,
        c.onBeforeCameraTeleport = new Observable,
        c.onAfterCameraTeleport = new Observable,
        c.onTrackingStateChanged = new Observable,
        c.compensateOnFirstFrame = !0,
        c._rotate180 = new Quaternion(0,1,0,0),
        c.minZ = .1,
        c.rotationQuaternion = new Quaternion,
        c.cameraRigMode = Camera$1.RIG_MODE_CUSTOM,
        c.updateUpVectorFromRotation = !0,
        c._updateNumberOfRigCameras(1),
        c.freezeProjectionMatrix(),
        c._xrSessionManager.onXRSessionInit.add(function() {
            c._referencedPosition.copyFromFloats(0, 0, 0),
            c._referenceQuaternion.copyFromFloats(0, 0, 0, 1),
            c._firstFrame = c.compensateOnFirstFrame
        }),
        c._xrSessionManager.onXRFrameObservable.add(function(d) {
            c._firstFrame && c._updateFromXRSession(),
            c._updateReferenceSpace(),
            c._updateFromXRSession()
        }, void 0, !0),
        c
    }
    return Object.defineProperty(e.prototype, "trackingState", {
        get: function() {
            return this._trackingState
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._setTrackingState = function(i) {
        this._trackingState !== i && (this._trackingState = i,
        this.onTrackingStateChanged.notifyObservers(i))
    }
    ,
    Object.defineProperty(e.prototype, "realWorldHeight", {
        get: function() {
            var i = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);
            return i && i.transform ? i.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(i, o) {
        if (i === void 0 && (i = this.getScene().activeCamera),
        o === void 0 && (o = !0),
        !(!i || i === this)) {
            var s = i.computeWorldMatrix();
            s.decompose(void 0, this.rotationQuaternion, this.position),
            this.position.y = 0,
            Quaternion.FromEulerAnglesToRef(0, this.rotationQuaternion.toEulerAngles().y, 0, this.rotationQuaternion),
            this._firstFrame = !0,
            o && this._xrSessionManager.resetReferenceSpace()
        }
    }
    ,
    e.prototype.getClassName = function() {
        return "WebXRCamera"
    }
    ,
    e.prototype.dispose = function() {
        a.prototype.dispose.call(this),
        this._lastXRViewerPose = void 0
    }
    ,
    e.prototype._updateFromXRSession = function() {
        var i = this
          , o = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);
        if (this._lastXRViewerPose = o || void 0,
        !o) {
            this._setTrackingState(WebXRTrackingState.NOT_TRACKING);
            return
        }
        var s = o.emulatedPosition ? WebXRTrackingState.TRACKING_LOST : WebXRTrackingState.TRACKING;
        if (this._setTrackingState(s),
        o.transform) {
            var c = o.transform.orientation;
            if (o.transform.orientation.x === void 0)
                return;
            var d = o.transform.position;
            this._referencedPosition.set(d.x, d.y, d.z),
            this._referenceQuaternion.set(c.x, c.y, c.z, c.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 !== o.views.length && this._updateNumberOfRigCameras(o.views.length),
        o.views.forEach(function(_, b) {
            var k = i.rigCameras[b];
            !k.isLeftCamera && !k.isRightCamera && (_.eye === "right" ? k._isRightCamera = !0 : _.eye === "left" && (k._isLeftCamera = !0));
            var j = _.transform.position
              , $ = _.transform.orientation;
            if (k.parent = i.parent,
            k.position.set(j.x, j.y, j.z),
            k.rotationQuaternion.set($.x, $.y, $.z, $.w),
            i._scene.useRightHandedSystem ? k.rotationQuaternion.multiplyInPlace(i._rotate180) : (k.position.z *= -1,
            k.rotationQuaternion.z *= -1,
            k.rotationQuaternion.w *= -1),
            Matrix.FromFloat32ArrayToRefScaled(_.projectionMatrix, 0, 1, k._projectionMatrix),
            i._scene.useRightHandedSystem || k._projectionMatrix.toggleProjectionMatrixHandInPlace(),
            b === 0 && i._projectionMatrix.copyFrom(k._projectionMatrix),
            i._xrSessionManager.session.renderState.baseLayer) {
                var _e = i._xrSessionManager.session.renderState.baseLayer.getViewport(_)
                  , et = i._xrSessionManager.session.renderState.baseLayer.framebufferWidth
                  , tt = i._xrSessionManager.session.renderState.baseLayer.framebufferHeight;
                k.viewport.width = _e.width / et,
                k.viewport.height = _e.height / tt,
                k.viewport.x = _e.x / et,
                k.viewport.y = _e.y / tt
            }
            k.outputRenderTarget = i._xrSessionManager.getRenderTargetTextureForEye(_.eye)
        })
    }
    ,
    e.prototype._updateNumberOfRigCameras = function(i) {
        for (i === void 0 && (i = 1); this.rigCameras.length < i; ) {
            var o = new TargetCamera("XR-RigCamera: " + this.rigCameras.length,Vector3.Zero(),this.getScene());
            o.minZ = .1,
            o.rotationQuaternion = new Quaternion,
            o.updateUpVectorFromRotation = !0,
            o.isRigCamera = !0,
            o.rigParent = this,
            o.freezeProjectionMatrix(),
            this.rigCameras.push(o)
        }
        for (; this.rigCameras.length > i; ) {
            var s = this.rigCameras.pop();
            s && s.dispose()
        }
    }
    ,
    e.prototype._updateReferenceSpace = function() {
        if (!this.position.equals(this._referencedPosition) || !this.rotationQuaternion.equals(this._referenceQuaternion)) {
            var i = TmpVectors.Matrix[0]
              , o = TmpVectors.Matrix[1]
              , s = TmpVectors.Matrix[2];
            Matrix.ComposeToRef(e._ScaleReadOnly, this._referenceQuaternion, this._referencedPosition, i),
            Matrix.ComposeToRef(e._ScaleReadOnly, this.rotationQuaternion, this.position, o),
            i.invert().multiplyToRef(o, s),
            s.invert(),
            this._scene.useRightHandedSystem || s.toggleModelMatrixHandInPlace(),
            s.decompose(void 0, this._referenceQuaternion, this._referencedPosition);
            var c = 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(c)
        }
    }
    ,
    e._ScaleReadOnly = Vector3.One(),
    e
}(FreeCamera), _a, WebXRFeatureName = function() {
    function a() {}
    return a.ANCHOR_SYSTEM = "xr-anchor-system",
    a.BACKGROUND_REMOVER = "xr-background-remover",
    a.HIT_TEST = "xr-hit-test",
    a.MESH_DETECTION = "xr-mesh-detection",
    a.PHYSICS_CONTROLLERS = "xr-physics-controller",
    a.PLANE_DETECTION = "xr-plane-detection",
    a.POINTER_SELECTION = "xr-controller-pointer-selection",
    a.TELEPORTATION = "xr-controller-teleportation",
    a.FEATURE_POINTS = "xr-feature-points",
    a.HAND_TRACKING = "xr-hand-tracking",
    a.IMAGE_TRACKING = "xr-image-tracking",
    a.NEAR_INTERACTION = "xr-near-interaction",
    a.DOM_OVERLAY = "xr-dom-overlay",
    a.MOVEMENT = "xr-controller-movement",
    a.LIGHT_ESTIMATION = "xr-light-estimation",
    a.EYE_TRACKING = "xr-eye-tracking",
    a.WALKING_LOCOMOTION = "xr-walking-locomotion",
    a
}(), WebXRFeaturesManager = function() {
    function a(e) {
        var i = this;
        this._xrSessionManager = e,
        this._features = {},
        this._xrSessionManager.onXRSessionInit.add(function() {
            i.getEnabledFeatures().forEach(function(o) {
                var s = i._features[o];
                s.enabled && !s.featureImplementation.attached && !s.featureImplementation.disableAutoAttach && i.attachFeature(o)
            })
        }),
        this._xrSessionManager.onXRSessionEnded.add(function() {
            i.getEnabledFeatures().forEach(function(o) {
                var s = i._features[o];
                s.enabled && s.featureImplementation.attached && i.detachFeature(o)
            })
        })
    }
    return a.AddWebXRFeature = function(e, i, o, s) {
        o === void 0 && (o = 1),
        s === void 0 && (s = !1),
        this._AvailableFeatures[e] = this._AvailableFeatures[e] || {
            latest: o
        },
        o > this._AvailableFeatures[e].latest && (this._AvailableFeatures[e].latest = o),
        s && (this._AvailableFeatures[e].stable = o),
        this._AvailableFeatures[e][o] = i
    }
    ,
    a.ConstructFeature = function(e, i, o, s) {
        i === void 0 && (i = 1);
        var c = this._AvailableFeatures[e][i];
        if (!c)
            throw new Error("feature not found");
        return c(o, s)
    }
    ,
    a.GetAvailableFeatures = function() {
        return Object.keys(this._AvailableFeatures)
    }
    ,
    a.GetAvailableVersions = function(e) {
        return Object.keys(this._AvailableFeatures[e])
    }
    ,
    a.GetLatestVersionOfFeature = function(e) {
        return this._AvailableFeatures[e] && this._AvailableFeatures[e].latest || -1
    }
    ,
    a.GetStableVersionOfFeature = function(e) {
        return this._AvailableFeatures[e] && this._AvailableFeatures[e].stable || -1
    }
    ,
    a.prototype.attachFeature = function(e) {
        var i = this._features[e];
        i && i.enabled && !i.featureImplementation.attached && i.featureImplementation.attach()
    }
    ,
    a.prototype.detachFeature = function(e) {
        var i = this._features[e];
        i && i.featureImplementation.attached && i.featureImplementation.detach()
    }
    ,
    a.prototype.disableFeature = function(e) {
        var i = typeof e == "string" ? e : e.Name
          , o = this._features[i];
        return o && o.enabled ? (o.enabled = !1,
        this.detachFeature(i),
        o.featureImplementation.dispose(),
        delete this._features[i],
        !0) : !1
    }
    ,
    a.prototype.dispose = function() {
        var e = this;
        this.getEnabledFeatures().forEach(function(i) {
            e.disableFeature(i)
        })
    }
    ,
    a.prototype.enableFeature = function(e, i, o, s, c) {
        var d = this;
        i === void 0 && (i = "latest"),
        o === void 0 && (o = {}),
        s === void 0 && (s = !0),
        c === void 0 && (c = !0);
        var _ = typeof e == "string" ? e : e.Name
          , b = 0;
        if (typeof i == "string") {
            if (!i)
                throw new Error("Error in provided version - " + _ + " (" + i + ")");
            if (i === "stable" ? b = a.GetStableVersionOfFeature(_) : i === "latest" ? b = a.GetLatestVersionOfFeature(_) : b = +i,
            b === -1 || isNaN(b))
                throw new Error("feature not found - " + _ + " (" + i + ")")
        } else
            b = i;
        var k = a._ConflictingFeatures[_];
        if (k !== void 0 && this.getEnabledFeatures().indexOf(k) !== -1)
            throw new Error("Feature " + _ + " cannot be enabled while " + k + " is enabled.");
        var j = this._features[_]
          , $ = a.ConstructFeature(_, b, this._xrSessionManager, o);
        if (!$)
            throw new Error("feature not found - " + _);
        j && this.disableFeature(_);
        var _e = $();
        if (_e.dependsOn) {
            var et = _e.dependsOn.every(function(tt) {
                return !!d._features[tt]
            });
            if (!et)
                throw new Error("Dependant features missing. Make sure the following features are enabled - " + _e.dependsOn.join(", "))
        }
        if (_e.isCompatible())
            return this._features[_] = {
                featureImplementation: _e,
                enabled: !0,
                version: b,
                required: c
            },
            s ? this._xrSessionManager.session && !this._features[_].featureImplementation.attached && this.attachFeature(_) : this._features[_].featureImplementation.disableAutoAttach = !0,
            this._features[_].featureImplementation;
        if (c)
            throw new Error("required feature not compatible");
        return Tools.Warn("Feature " + _ + " not compatible with the current environment/browser and was not enabled."),
        _e
    }
    ,
    a.prototype.getEnabledFeature = function(e) {
        return this._features[e] && this._features[e].featureImplementation
    }
    ,
    a.prototype.getEnabledFeatures = function() {
        return Object.keys(this._features)
    }
    ,
    a.prototype._extendXRSessionInitObject = function(e) {
        return __awaiter(this, void 0, void 0, function() {
            var i, o, s, c, d, _, b;
            return __generator(this, function(k) {
                switch (k.label) {
                case 0:
                    i = this.getEnabledFeatures(),
                    o = 0,
                    s = i,
                    k.label = 1;
                case 1:
                    return o < s.length ? (c = s[o],
                    d = this._features[c],
                    _ = d.featureImplementation.xrNativeFeatureName,
                    _ && (d.required ? (e.requiredFeatures = e.requiredFeatures || [],
                    e.requiredFeatures.indexOf(_) === -1 && e.requiredFeatures.push(_)) : (e.optionalFeatures = e.optionalFeatures || [],
                    e.optionalFeatures.indexOf(_) === -1 && e.optionalFeatures.push(_))),
                    d.featureImplementation.getXRSessionInitExtension ? [4, d.featureImplementation.getXRSessionInitExtension()] : [3, 3]) : [3, 4];
                case 2:
                    b = k.sent(),
                    e = __assign(__assign({}, e), b),
                    k.label = 3;
                case 3:
                    return o++,
                    [3, 1];
                case 4:
                    return [2, e]
                }
            })
        })
    }
    ,
    a._AvailableFeatures = {},
    a._ConflictingFeatures = (_a = {},
    _a[WebXRFeatureName.TELEPORTATION] = WebXRFeatureName.MOVEMENT,
    _a[WebXRFeatureName.MOVEMENT] = WebXRFeatureName.TELEPORTATION,
    _a),
    a
}();
Node$2.AddNodeConstructor("TouchCamera", function(a, e) {
    return function() {
        return new TouchCamera(a,Vector3.Zero(),e)
    }
});
var TouchCamera = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, o, s) || this;
        return c.inputs.addTouch(),
        c._setupInputs(),
        c
    }
    return Object.defineProperty(e.prototype, "touchAngularSensibility", {
        get: function() {
            var i = this.inputs.attached.touch;
            return i ? i.touchAngularSensibility : 0
        },
        set: function(i) {
            var o = this.inputs.attached.touch;
            o && (o.touchAngularSensibility = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "touchMoveSensibility", {
        get: function() {
            var i = this.inputs.attached.touch;
            return i ? i.touchMoveSensibility : 0
        },
        set: function(i) {
            var o = this.inputs.attached.touch;
            o && (o.touchMoveSensibility = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "TouchCamera"
    }
    ,
    e.prototype._setupInputs = function() {
        var i = this.inputs.attached.touch
          , o = this.inputs.attached.mouse;
        o ? o.touchEnabled = !1 : i.allowMouse = !0
    }
    ,
    e
}(FreeCamera);
Node$2.AddNodeConstructor("FreeCamera", function(a, e) {
    return function() {
        return new UniversalCamera(a,Vector3.Zero(),e)
    }
});
var UniversalCamera = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, o, s) || this;
        return c.inputs.addGamepad(),
        c
    }
    return Object.defineProperty(e.prototype, "gamepadAngularSensibility", {
        get: function() {
            var i = this.inputs.attached.gamepad;
            return i ? i.gamepadAngularSensibility : 0
        },
        set: function(i) {
            var o = this.inputs.attached.gamepad;
            o && (o.gamepadAngularSensibility = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "gamepadMoveSensibility", {
        get: function() {
            var i = this.inputs.attached.gamepad;
            return i ? i.gamepadMoveSensibility : 0
        },
        set: function(i) {
            var o = this.inputs.attached.gamepad;
            o && (o.gamepadMoveSensibility = i)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "UniversalCamera"
    }
    ,
    e
}(TouchCamera);
Camera$1._createDefaultParsedCamera = function(a, e) {
    return new UniversalCamera(a,Vector3.Zero(),e)
}
;
var WebXRExperienceHelper = function() {
    function a(e) {
        var i = 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() {
            i.exitXRAsync()
        })
    }
    return a.CreateAsync = function(e) {
        var i = new a(e);
        return i.sessionManager.initializeAsync().then(function() {
            return i._supported = !0,
            i
        }).catch(function(o) {
            throw i._setState(WebXRState.NOT_IN_XR),
            i.dispose(),
            o
        })
    }
    ,
    a.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)
    }
    ,
    a.prototype.enterXRAsync = function(e, i, o, s) {
        var c, d;
        return o === void 0 && (o = this.sessionManager.getWebXRRenderTarget()),
        s === void 0 && (s = {}),
        __awaiter(this, void 0, void 0, function() {
            var _, b = this;
            return __generator(this, function(k) {
                switch (k.label) {
                case 0:
                    if (!this._supported)
                        throw "WebXR not supported in this browser or environment";
                    return this._setState(WebXRState.ENTERING_XR),
                    i !== "viewer" && i !== "local" && (s.optionalFeatures = s.optionalFeatures || [],
                    s.optionalFeatures.push(i)),
                    [4, this.featuresManager._extendXRSessionInitObject(s)];
                case 1:
                    s = k.sent(),
                    e === "immersive-ar" && i !== "unbounded" && Logger$2.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode"),
                    k.label = 2;
                case 2:
                    return k.trys.push([2, 7, , 8]),
                    [4, this.sessionManager.initializeSessionAsync(e, s)];
                case 3:
                    return k.sent(),
                    [4, this.sessionManager.setReferenceSpaceTypeAsync(i)];
                case 4:
                    return k.sent(),
                    [4, o.initializeXRLayerAsync(this.sessionManager.session)];
                case 5:
                    return k.sent(),
                    [4, this.sessionManager.updateRenderStateAsync({
                        depthFar: this.camera.maxZ,
                        depthNear: this.camera.minZ,
                        baseLayer: o.xrLayer
                    })];
                case 6:
                    return k.sent(),
                    this.sessionManager.runXRRenderLoop(),
                    this._originalSceneAutoClear = this.scene.autoClear,
                    this._nonVRCamera = this.scene.activeCamera,
                    this._attachedToElement = !!(!((c = this._nonVRCamera) === null || c === void 0) && c.inputs.attachedToElement),
                    (d = this._nonVRCamera) === null || d === void 0 || d.detachControl(),
                    this.scene.activeCamera = this.camera,
                    e !== "immersive-ar" ? this._nonXRToXRCamera() : (this.scene.autoClear = !1,
                    this.camera.compensateOnFirstFrame = !1),
                    this.sessionManager.onXRSessionEnded.addOnce(function() {
                        b.camera.rigCameras.forEach(function(j) {
                            j.outputRenderTarget = null
                        }),
                        b.scene.autoClear = b._originalSceneAutoClear,
                        b.scene.activeCamera = b._nonVRCamera,
                        b._attachedToElement && b._nonVRCamera && b._nonVRCamera.attachControl(!!b._nonVRCamera.inputs.noPreventDefault),
                        e !== "immersive-ar" && b.camera.compensateOnFirstFrame && (b._nonVRCamera.setPosition ? b._nonVRCamera.setPosition(b.camera.position) : b._nonVRCamera.position.copyFrom(b.camera.position)),
                        b._setState(WebXRState.NOT_IN_XR)
                    }),
                    this.sessionManager.onXRFrameObservable.addOnce(function() {
                        b._setState(WebXRState.IN_XR)
                    }),
                    [2, this.sessionManager];
                case 7:
                    throw _ = k.sent(),
                    console.log(_),
                    console.log(_.message),
                    this._setState(WebXRState.NOT_IN_XR),
                    _;
                case 8:
                    return [2]
                }
            })
        })
    }
    ,
    a.prototype.exitXRAsync = function() {
        return this.state !== WebXRState.IN_XR ? Promise.resolve() : (this._setState(WebXRState.EXITING_XR),
        this.sessionManager.exitXRAsync())
    }
    ,
    a.prototype.enableSpectatorMode = function() {
        var e = this;
        if (!this._spectatorMode) {
            var i = function() {
                e._spectatorCamera && (e._spectatorCamera.position.copyFrom(e.camera.rigCameras[0].globalPosition),
                e._spectatorCamera.rotationQuaternion.copyFrom(e.camera.rigCameras[0].absoluteRotation))
            }
              , o = 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(i),
                e.scene.onAfterRenderCameraObservable.add(function(s) {
                    s === e.camera && (e.scene.getEngine().framebufferDimensionsObject = null)
                })) : e.state === WebXRState.EXITING_XR && (e.sessionManager.onXRFrameObservable.removeCallback(i),
                e.scene.activeCameras = null)
            };
            this._spectatorMode = !0,
            this.onStateChangedObservable.add(o),
            o()
        }
    }
    ,
    a.prototype._nonXRToXRCamera = function() {
        this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),
        this.onInitialXRPoseSetObservable.notifyObservers(this.camera)
    }
    ,
    a.prototype._setState = function(e) {
        this.state !== e && (this.state = e,
        this.onStateChangedObservable.notifyObservers(this.state))
    }
    ,
    a
}()
  , WebXRControllerComponent = function() {
    function a(e, i, o, s) {
        o === void 0 && (o = -1),
        s === void 0 && (s = []),
        this.id = e,
        this.type = i,
        this._buttonIndex = o,
        this._axesIndices = s,
        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(a.prototype, "axes", {
        get: function() {
            return this._axes
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "changes", {
        get: function() {
            return this._changes
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "hasChanges", {
        get: function() {
            return this._hasChanges
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "pressed", {
        get: function() {
            return this._pressed
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "touched", {
        get: function() {
            return this._touched
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(a.prototype, "value", {
        get: function() {
            return this._currentValue
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.dispose = function() {
        this.onAxisValueChangedObservable.clear(),
        this.onButtonStateChangedObservable.clear()
    }
    ,
    a.prototype.isAxes = function() {
        return this._axesIndices.length !== 0
    }
    ,
    a.prototype.isButton = function() {
        return this._buttonIndex !== -1
    }
    ,
    a.prototype.update = function(e) {
        var i = !1
          , o = !1;
        if (this._hasChanges = !1,
        this._changes = {},
        this.isButton()) {
            var s = e.buttons[this._buttonIndex];
            if (!s)
                return;
            this._currentValue !== s.value && (this.changes.value = {
                current: s.value,
                previous: this._currentValue
            },
            i = !0,
            this._currentValue = s.value),
            this._touched !== s.touched && (this.changes.touched = {
                current: s.touched,
                previous: this._touched
            },
            i = !0,
            this._touched = s.touched),
            this._pressed !== s.pressed && (this.changes.pressed = {
                current: s.pressed,
                previous: this._pressed
            },
            i = !0,
            this._pressed = s.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]],
        o = !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]],
        o = !0)),
        i && (this._hasChanges = !0,
        this.onButtonStateChangedObservable.notifyObservers(this)),
        o && (this._hasChanges = !0,
        this.onAxisValueChangedObservable.notifyObservers(this._axes))
    }
    ,
    a.BUTTON_TYPE = "button",
    a.SQUEEZE_TYPE = "squeeze",
    a.THUMBSTICK_TYPE = "thumbstick",
    a.TOUCHPAD_TYPE = "touchpad",
    a.TRIGGER_TYPE = "trigger",
    a
}()
  , WebXRAbstractMotionController = function() {
    function a(e, i, o, s, c, d) {
        var _ = this;
        c === void 0 && (c = !1),
        this.scene = e,
        this.layout = i,
        this.gamepadObject = o,
        this.handedness = s,
        this._doNotLoadControllerMesh = c,
        this._controllerCache = d,
        this._initComponent = function(b) {
            if (!!b) {
                var k = _.layout.components[b]
                  , j = k.type
                  , $ = k.gamepadIndices.button
                  , _e = [];
                k.gamepadIndices.xAxis !== void 0 && k.gamepadIndices.yAxis !== void 0 && _e.push(k.gamepadIndices.xAxis, k.gamepadIndices.yAxis),
                _.components[b] = new WebXRControllerComponent(b,j,$,_e)
            }
        }
        ,
        this._modelReady = !1,
        this.components = {},
        this.disableAnimation = !1,
        this.onModelLoadedObservable = new Observable,
        i.components && Object.keys(i.components).forEach(this._initComponent)
    }
    return a.prototype.dispose = function() {
        var e = this;
        this.getComponentIds().forEach(function(i) {
            return e.getComponent(i).dispose()
        }),
        this.rootMesh && (this.rootMesh.getChildren(void 0, !0).forEach(function(i) {
            i.setEnabled(!1)
        }),
        this.rootMesh.dispose(!!this._controllerCache, !this._controllerCache))
    }
    ,
    a.prototype.getAllComponentsOfType = function(e) {
        var i = this;
        return this.getComponentIds().map(function(o) {
            return i.components[o]
        }).filter(function(o) {
            return o.type === e
        })
    }
    ,
    a.prototype.getComponent = function(e) {
        return this.components[e]
    }
    ,
    a.prototype.getComponentIds = function() {
        return Object.keys(this.components)
    }
    ,
    a.prototype.getComponentOfType = function(e) {
        return this.getAllComponentsOfType(e)[0] || null
    }
    ,
    a.prototype.getMainComponent = function() {
        return this.getComponent(this.layout.selectComponentId)
    }
    ,
    a.prototype.loadModel = function() {
        return __awaiter(this, void 0, void 0, function() {
            var e, i, o = this;
            return __generator(this, function(s) {
                return e = !this._getModelLoadingConstraints(),
                i = this._getGenericFilenameAndPath(),
                e ? Logger$2.Warn("Falling back to generic models") : i = this._getFilenameAndPath(),
                [2, new Promise(function(c, d) {
                    var _ = function(k) {
                        e ? o._getGenericParentMesh(k) : o._setRootMesh(k),
                        o._processLoadedModel(k),
                        o._modelReady = !0,
                        o.onModelLoadedObservable.notifyObservers(o),
                        c(!0)
                    };
                    if (o._controllerCache) {
                        var b = o._controllerCache.filter(function(k) {
                            return k.filename === i.filename && k.path === i.path
                        });
                        if (b[0]) {
                            b[0].meshes.forEach(function(k) {
                                return k.setEnabled(!0)
                            }),
                            _(b[0].meshes);
                            return
                        }
                    }
                    SceneLoader.ImportMesh("", i.path, i.filename, o.scene, function(k) {
                        o._controllerCache && o._controllerCache.push(__assign(__assign({}, i), {
                            meshes: k
                        })),
                        _(k)
                    }, null, function(k, j) {
                        Logger$2.Log(j),
                        Logger$2.Warn("Failed to retrieve controller model of type " + o.profileId + " from the remote server: " + i.path + i.filename),
                        d(j)
                    })
                }
                )]
            })
        })
    }
    ,
    a.prototype.updateFromXRFrame = function(e) {
        var i = this;
        this.getComponentIds().forEach(function(o) {
            return i.getComponent(o).update(i.gamepadObject)
        }),
        this.updateModel(e)
    }
    ,
    Object.defineProperty(a.prototype, "handness", {
        get: function() {
            return this.handedness
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.pulse = function(e, i, o) {
        return o === void 0 && (o = 0),
        this.gamepadObject.hapticActuators && this.gamepadObject.hapticActuators[o] ? this.gamepadObject.hapticActuators[o].pulse(e, i) : Promise.resolve(!1)
    }
    ,
    a.prototype._getChildByName = function(e, i) {
        return e.getChildren(function(o) {
            return o.name === i
        }, !1)[0]
    }
    ,
    a.prototype._getImmediateChildByName = function(e, i) {
        return e.getChildren(function(o) {
            return o.name == i
        }, !0)[0]
    }
    ,
    a.prototype._lerpTransform = function(e, i, o) {
        if (!(!e.minMesh || !e.maxMesh || !e.valueMesh) && !(!e.minMesh.rotationQuaternion || !e.maxMesh.rotationQuaternion || !e.valueMesh.rotationQuaternion)) {
            var s = o ? i * .5 + .5 : i;
            Quaternion.SlerpToRef(e.minMesh.rotationQuaternion, e.maxMesh.rotationQuaternion, s, e.valueMesh.rotationQuaternion),
            Vector3.LerpToRef(e.minMesh.position, e.maxMesh.position, s, e.valueMesh.position)
        }
    }
    ,
    a.prototype.updateModel = function(e) {
        !this._modelReady || this._updateModel(e)
    }
    ,
    a.prototype._getGenericFilenameAndPath = function() {
        return {
            filename: "generic.babylon",
            path: "https://controllers.babylonjs.com/generic/"
        }
    }
    ,
    a.prototype._getGenericParentMesh = function(e) {
        var i = this;
        this.rootMesh = new Mesh(this.profileId + " " + this.handedness,this.scene),
        e.forEach(function(o) {
            o.parent || (o.isPickable = !1,
            o.setParent(i.rootMesh))
        }),
        this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0)
    }
    ,
    a
}()
  , WebXRGenericTriggerMotionController = function(a) {
    __extends(e, a);
    function e(i, o, s) {
        var c = a.call(this, i, GenericTriggerLayout[s], o, s) || this;
        return c.profileId = e.ProfileId,
        c
    }
    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(i) {}
    ,
    e.prototype._setRootMesh = function(i) {
        var o = this;
        this.rootMesh = new Mesh(this.profileId + " " + this.handedness,this.scene),
        i.forEach(function(s) {
            s.isPickable = !1,
            s.parent || s.setParent(o.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(a) {
    __extends(e, a);
    function e(i, o, s, c, d) {
        var _ = a.call(this, i, s.layouts[o.handedness || "none"], o.gamepad, o.handedness, void 0, d) || this;
        return _._repositoryUrl = c,
        _.controllerCache = d,
        _._buttonMeshMapping = {},
        _._touchDots = {},
        _.profileId = s.profileId,
        _
    }
    return e.prototype.dispose = function() {
        var i = this;
        a.prototype.dispose.call(this),
        this.controllerCache || Object.keys(this._touchDots).forEach(function(o) {
            i._touchDots[o].dispose()
        })
    }
    ,
    e.prototype._getFilenameAndPath = function() {
        return {
            filename: this.layout.assetPath,
            path: this._repositoryUrl + "/profiles/" + this.profileId + "/"
        }
    }
    ,
    e.prototype._getModelLoadingConstraints = function() {
        var i = SceneLoader.IsPluginForExtensionAvailable(".glb");
        return i || Logger$2.Warn("glTF / glb loader was not registered, using generic controller instead"),
        i
    }
    ,
    e.prototype._processLoadedModel = function(i) {
        var o = this;
        this.getComponentIds().forEach(function(s) {
            var c = o.layout.components[s];
            o._buttonMeshMapping[s] = {
                mainMesh: o._getChildByName(o.rootMesh, c.rootNodeName),
                states: {}
            },
            Object.keys(c.visualResponses).forEach(function(d) {
                var _ = c.visualResponses[d];
                if (_.valueNodeProperty === "transform")
                    o._buttonMeshMapping[s].states[d] = {
                        valueMesh: o._getChildByName(o.rootMesh, _.valueNodeName),
                        minMesh: o._getChildByName(o.rootMesh, _.minNodeName),
                        maxMesh: o._getChildByName(o.rootMesh, _.maxNodeName)
                    };
                else {
                    var b = c.type === WebXRControllerComponent.TOUCHPAD_TYPE && c.touchPointNodeName ? c.touchPointNodeName : _.valueNodeName;
                    if (o._buttonMeshMapping[s].states[d] = {
                        valueMesh: o._getChildByName(o.rootMesh, b)
                    },
                    c.type === WebXRControllerComponent.TOUCHPAD_TYPE && !o._touchDots[d]) {
                        var k = CreateSphere(d + "dot", {
                            diameter: .0015,
                            segments: 8
                        }, o.scene);
                        k.material = new StandardMaterial(d + "mat",o.scene),
                        k.material.diffuseColor = Color3.Red(),
                        k.parent = o._buttonMeshMapping[s].states[d].valueMesh || null,
                        k.isVisible = !1,
                        o._touchDots[d] = k
                    }
                }
            })
        })
    }
    ,
    e.prototype._setRootMesh = function(i) {
        this.rootMesh = new Mesh(this.profileId + "-" + this.handedness,this.scene),
        this.rootMesh.isPickable = !1;
        for (var o, s = 0; s < i.length; s++) {
            var c = i[s];
            c.isPickable = !1,
            c.parent || (o = c)
        }
        o && o.setParent(this.rootMesh),
        this.scene.useRightHandedSystem || this.rootMesh.rotate(Axis.Y, Math.PI, Space.WORLD)
    }
    ,
    e.prototype._updateModel = function(i) {
        var o = this;
        this.disableAnimation || this.getComponentIds().forEach(function(s) {
            var c = o.getComponent(s);
            if (!!c.hasChanges) {
                var d = o._buttonMeshMapping[s]
                  , _ = o.layout.components[s];
                Object.keys(_.visualResponses).forEach(function(b) {
                    var k = _.visualResponses[b]
                      , j = c.value;
                    if (k.componentProperty === "xAxis" ? j = c.axes.x : k.componentProperty === "yAxis" && (j = c.axes.y),
                    k.valueNodeProperty === "transform")
                        o._lerpTransform(d.states[b], j, k.componentProperty !== "button");
                    else {
                        var $ = d.states[b].valueMesh;
                        $ && ($.isVisible = c.touched || c.pressed),
                        o._touchDots[b] && (o._touchDots[b].isVisible = c.touched || c.pressed)
                    }
                })
            }
        })
    }
    ,
    e
}(WebXRAbstractMotionController)
  , controllerCache = []
  , WebXRMotionControllerManager = function() {
    function a() {}
    return a.ClearProfilesCache = function() {
        this._ProfilesList = null,
        this._ProfileLoadingPromises = {}
    }
    ,
    a.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"])
    }
    ,
    a.FindFallbackWithProfileId = function(e) {
        var i = this._Fallbacks[e] || [];
        return i.unshift(e),
        i
    }
    ,
    a.GetMotionControllerWithXRInput = function(e, i, o) {
        var s = this
          , c = [];
        if (o && c.push(o),
        c.push.apply(c, e.profiles || []),
        c.length && !c[0] && c.pop(),
        e.gamepad && e.gamepad.id)
            switch (e.gamepad.id) {
            case (e.gamepad.id.match(/oculus touch/gi) ? e.gamepad.id : void 0):
                c.push("oculus-touch-v2");
                break
            }
        var d = c.indexOf("windows-mixed-reality");
        if (d !== -1 && c.splice(d, 0, "microsoft-mixed-reality"),
        c.length || c.push("generic-trigger"),
        this.UseOnlineRepository) {
            var _ = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers
              , b = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository;
            return _.call(this, c, e, i).catch(function() {
                return b.call(s, c, e, i)
            })
        } else
            return this._LoadProfilesFromAvailableControllers(c, e, i)
    }
    ,
    a.RegisterController = function(e, i) {
        this._AvailableControllers[e] = i
    }
    ,
    a.RegisterFallbacksForProfileId = function(e, i) {
        var o;
        this._Fallbacks[e] ? (o = this._Fallbacks[e]).push.apply(o, i) : this._Fallbacks[e] = i
    }
    ,
    a.UpdateProfilesList = function() {
        return this._ProfilesList = Tools.LoadFileAsync(this.BaseRepositoryUrl + "/profiles/profilesList.json", !1).then(function(e) {
            return JSON.parse(e.toString())
        }),
        this._ProfilesList
    }
    ,
    a.ClearControllerCache = function() {
        controllerCache.forEach(function(e) {
            e.meshes.forEach(function(i) {
                i.dispose(!1, !0)
            })
        }),
        controllerCache.length = 0
    }
    ,
    a._LoadProfileFromRepository = function(e, i, o) {
        var s = this;
        return Promise.resolve().then(function() {
            return s._ProfilesList ? s._ProfilesList : s.UpdateProfilesList()
        }).then(function(c) {
            for (var d = 0; d < e.length; ++d)
                if (!!e[d] && c[e[d]])
                    return e[d];
            throw new Error("neither controller " + e[0] + " nor all fallbacks were found in the repository,")
        }).then(function(c) {
            return s._ProfileLoadingPromises[c] || (s._ProfileLoadingPromises[c] = Tools.LoadFileAsync(s.BaseRepositoryUrl + "/profiles/" + c + "/profile.json", !1).then(function(d) {
                return JSON.parse(d)
            })),
            s._ProfileLoadingPromises[c]
        }).then(function(c) {
            return new WebXRProfiledMotionController(o,i,c,s.BaseRepositoryUrl,s.DisableControllerCache ? void 0 : controllerCache)
        })
    }
    ,
    a._LoadProfilesFromAvailableControllers = function(e, i, o) {
        for (var s = 0; s < e.length; ++s)
            if (!!e[s])
                for (var c = this.FindFallbackWithProfileId(e[s]), d = 0; d < c.length; ++d) {
                    var _ = this._AvailableControllers[c[d]];
                    if (_)
                        return Promise.resolve(_(i, o))
                }
        throw new Error("no controller requested was found in the available controllers list")
    }
    ,
    a._AvailableControllers = {},
    a._Fallbacks = {},
    a._ProfileLoadingPromises = {},
    a.BaseRepositoryUrl = "https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",
    a.PrioritizeOnlineRepository = !0,
    a.UseOnlineRepository = !0,
    a.DisableControllerCache = !0,
    a
}();
WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, function(a, e) {
    return new WebXRGenericTriggerMotionController(e,a.gamepad,a.handedness)
});
WebXRMotionControllerManager.DefaultFallbacks();
var idCount = 0
  , WebXRInputSource = function() {
    function a(e, i, o) {
        var s = this;
        o === void 0 && (o = {}),
        this._scene = e,
        this.inputSource = i,
        this._options = o,
        this._tmpVector = new Vector3,
        this._disposed = !1,
        this.onDisposeObservable = new Observable,
        this.onMeshLoadedObservable = new Observable,
        this.onMotionControllerInitObservable = new Observable,
        this._uniqueId = "controller-" + idCount++ + "-" + i.targetRayMode + "-" + i.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(i, e, this._options.forceControllerProfile).then(function(c) {
            s.motionController = c,
            s.onMotionControllerInitObservable.notifyObservers(c),
            !s._options.doNotLoadControllerMesh && !s.motionController._doNotLoadControllerMesh && s.motionController.loadModel().then(function(d) {
                var _;
                d && s.motionController && s.motionController.rootMesh && (s._options.renderingGroupId && (s.motionController.rootMesh.renderingGroupId = s._options.renderingGroupId,
                s.motionController.rootMesh.getChildMeshes(!1).forEach(function(b) {
                    return b.renderingGroupId = s._options.renderingGroupId
                })),
                s.onMeshLoadedObservable.notifyObservers(s.motionController.rootMesh),
                s.motionController.rootMesh.parent = s.grip || s.pointer,
                s.motionController.disableAnimation = !!s._options.disableMotionControllerAnimation),
                s._disposed && ((_ = s.motionController) === null || _ === void 0 || _.dispose())
            })
        }, function() {
            Tools.Warn("Could not find a matching motion controller for the registered input source")
        })
    }
    return Object.defineProperty(a.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    a.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
    }
    ,
    a.prototype.getWorldPointerRayToRef = function(e, i) {
        i === void 0 && (i = !1);
        var o = i && this.grip ? this.grip : this.pointer;
        Vector3.TransformNormalToRef(this._tmpVector, o.getWorldMatrix(), e.direction),
        e.direction.normalize(),
        e.origin.copyFrom(o.absolutePosition),
        e.length = 1e3
    }
    ,
    a.prototype.updateFromXRFrame = function(e, i, o) {
        var s = e.getPose(this.inputSource.targetRaySpace, i);
        if (this._lastXRPose = s,
        s) {
            var c = s.transform.position;
            this.pointer.position.set(c.x, c.y, c.z);
            var d = s.transform.orientation;
            this.pointer.rotationQuaternion.set(d.x, d.y, d.z, d.w),
            this._scene.useRightHandedSystem || (this.pointer.position.z *= -1,
            this.pointer.rotationQuaternion.z *= -1,
            this.pointer.rotationQuaternion.w *= -1),
            this.pointer.parent = o.parent
        }
        if (this.inputSource.gripSpace && this.grip) {
            var _ = e.getPose(this.inputSource.gripSpace, i);
            if (_) {
                var c = _.transform.position
                  , b = _.transform.orientation;
                this.grip.position.set(c.x, c.y, c.z),
                this.grip.rotationQuaternion.set(b.x, b.y, b.z, b.w),
                this._scene.useRightHandedSystem || (this.grip.position.z *= -1,
                this.grip.rotationQuaternion.z *= -1,
                this.grip.rotationQuaternion.w *= -1)
            }
            this.grip.parent = o.parent
        }
        this.motionController && this.motionController.updateFromXRFrame(e)
    }
    ,
    a
}()
  , WebXRInput = function() {
    function a(e, i, o) {
        var s = this;
        if (o === void 0 && (o = {}),
        this.xrSessionManager = e,
        this.xrCamera = i,
        this.options = o,
        this.controllers = [],
        this.onControllerAddedObservable = new Observable,
        this.onControllerRemovedObservable = new Observable,
        this._onInputSourcesChange = function(c) {
            s._addAndRemoveControllers(c.added, c.removed)
        }
        ,
        this._sessionEndedObserver = this.xrSessionManager.onXRSessionEnded.add(function() {
            s._addAndRemoveControllers([], s.controllers.map(function(c) {
                return c.inputSource
            }))
        }),
        this._sessionInitObserver = this.xrSessionManager.onXRSessionInit.add(function(c) {
            c.addEventListener("inputsourceschange", s._onInputSourcesChange)
        }),
        this._frameObserver = this.xrSessionManager.onXRFrameObservable.add(function(c) {
            s.controllers.forEach(function(d) {
                d.updateFromXRFrame(c, s.xrSessionManager.referenceSpace, s.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 a.prototype._addAndRemoveControllers = function(e, i) {
        for (var o = this, s = this.controllers.map(function($) {
            return $.inputSource
        }), c = 0, d = e; c < d.length; c++) {
            var _ = d[c];
            if (s.indexOf(_) === -1) {
                var b = new WebXRInputSource(this.xrSessionManager.scene,_,__assign(__assign({}, this.options.controllerOptions || {}), {
                    forceControllerProfile: this.options.forceInputProfile,
                    doNotLoadControllerMesh: this.options.doNotLoadControllerMeshes,
                    disableMotionControllerAnimation: this.options.disableControllerAnimation
                }));
                this.controllers.push(b),
                this.onControllerAddedObservable.notifyObservers(b)
            }
        }
        var k = []
          , j = [];
        this.controllers.forEach(function($) {
            i.indexOf($.inputSource) === -1 ? k.push($) : j.push($)
        }),
        this.controllers = k,
        j.forEach(function($) {
            o.onControllerRemovedObservable.notifyObservers($),
            $.dispose()
        })
    }
    ,
    a.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()
    }
    ,
    a
}()
  , WebXRAbstractFeature = function() {
    function a(e) {
        this._xrSessionManager = e,
        this._attached = !1,
        this._removeOnDetach = [],
        this.isDisposed = !1,
        this.disableAutoAttach = !1,
        this.xrNativeFeatureName = ""
    }
    return Object.defineProperty(a.prototype, "attached", {
        get: function() {
            return this._attached
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.attach = function(e) {
        var i = 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(o) {
            return i._onXRFrame(o)
        }),
        !0
    }
    ,
    a.prototype.detach = function() {
        return this._attached ? (this._attached = !1,
        this._removeOnDetach.forEach(function(e) {
            e.observable.remove(e.observer)
        }),
        !0) : (this.disableAutoAttach = !0,
        !1)
    }
    ,
    a.prototype.dispose = function() {
        this.detach(),
        this.isDisposed = !0
    }
    ,
    a.prototype.isCompatible = function() {
        return !0
    }
    ,
    a.prototype._addNewAttachObserver = function(e, i) {
        this._removeOnDetach.push({
            observable: e,
            observer: e.add(i)
        })
    }
    ,
    a
}()
  , WebXRControllerPointerSelection = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i) || this;
        return s._options = o,
        s._attachController = function(c) {
            if (!s._controllers[c.uniqueId]) {
                var d = s._generateNewMeshPair(c.pointer)
                  , _ = d.laserPointer
                  , b = d.selectionMesh;
                switch (s._controllers[c.uniqueId] = {
                    xrController: c,
                    laserPointer: _,
                    selectionMesh: b,
                    meshUnderPointer: null,
                    pick: null,
                    tmpRay: new Ray(new Vector3,new Vector3),
                    disabledByNearInteraction: !1,
                    id: e._idCounter++
                },
                s._attachedController ? !s._options.enablePointerSelectionOnAllControllers && s._options.preferredHandedness && c.inputSource.handedness === s._options.preferredHandedness && (s._attachedController = c.uniqueId) : s._options.enablePointerSelectionOnAllControllers || (s._attachedController = c.uniqueId),
                c.inputSource.targetRayMode) {
                case "tracked-pointer":
                    return s._attachTrackedPointerRayMode(c);
                case "gaze":
                    return s._attachGazeMode(c);
                case "screen":
                    return s._attachScreenRayMode(c)
                }
            }
        }
        ,
        s._controllers = {},
        s._tmpVectorForPickCompare = new Vector3,
        s.disablePointerLighting = !0,
        s.disableSelectionMeshLighting = !0,
        s.displayLaserPointer = !0,
        s.displaySelectionMesh = !0,
        s.laserPointerPickedColor = new Color3(.9,.9,.9),
        s.laserPointerDefaultColor = new Color3(.7,.7,.7),
        s.selectionMeshDefaultColor = new Color3(.8,.8,.8),
        s.selectionMeshPickedColor = new Color3(.3,.3,1),
        s._identityMatrix = Matrix.Identity(),
        s._screenCoordinatesRef = Vector3.Zero(),
        s._viewportRef = new Viewport(0,0,0,0),
        s._scene = s._xrSessionManager.scene,
        s
    }
    return e.prototype.attach = function() {
        var i = this;
        if (!a.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(_) {
            i._detachController(_.uniqueId)
        }),
        this._scene.constantlyUpdateMeshUnderPointer = !0,
        this._options.gazeCamera) {
            var o = this._options.gazeCamera
              , s = this._generateNewMeshPair(o)
              , c = s.laserPointer
              , d = s.selectionMesh;
            this._controllers.camera = {
                webXRCamera: o,
                laserPointer: c,
                selectionMesh: d,
                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 i = this;
        return a.prototype.detach.call(this) ? (Object.keys(this._controllers).forEach(function(o) {
            i._detachController(o)
        }),
        !0) : !1
    }
    ,
    e.prototype.getMeshUnderPointer = function(i) {
        return this._controllers[i] ? this._controllers[i].meshUnderPointer : null
    }
    ,
    e.prototype.getXRControllerByPointerId = function(i) {
        for (var o = Object.keys(this._controllers), s = 0; s < o.length; ++s)
            if (this._controllers[o[s]].id === i)
                return this._controllers[o[s]].xrController || null;
        return null
    }
    ,
    e.prototype._getPointerSelectionDisabledByPointerId = function(i) {
        for (var o = Object.keys(this._controllers), s = 0; s < o.length; ++s)
            if (this._controllers[o[s]].id === i)
                return this._controllers[o[s]].disabledByNearInteraction;
        return !0
    }
    ,
    e.prototype._setPointerSelectionDisabledByPointerId = function(i, o) {
        for (var s = Object.keys(this._controllers), c = 0; c < s.length; ++c)
            if (this._controllers[s[c]].id === i) {
                this._controllers[s[c]].disabledByNearInteraction = o;
                return
            }
    }
    ,
    e.prototype._onXRFrame = function(i) {
        var o = this;
        Object.keys(this._controllers).forEach(function(s) {
            var c = o._controllers[s];
            if (!o._options.enablePointerSelectionOnAllControllers && s !== o._attachedController || c.disabledByNearInteraction) {
                c.selectionMesh.isVisible = !1,
                c.laserPointer.isVisible = !1,
                c.pick = null;
                return
            }
            c.laserPointer.isVisible = o.displayLaserPointer;
            var d;
            if (c.xrController)
                d = c.xrController.pointer.position,
                c.xrController.getWorldPointerRayToRef(c.tmpRay);
            else if (c.webXRCamera)
                d = c.webXRCamera.position,
                c.webXRCamera.getForwardRayToRef(c.tmpRay);
            else
                return;
            if (o._options.maxPointerDistance && (c.tmpRay.length = o._options.maxPointerDistance),
            !o._options.disableScenePointerVectorUpdate && d) {
                var _ = o._xrSessionManager.scene
                  , b = o._options.xrInput.xrCamera;
                b && (b.viewport.toGlobalToRef(_.getEngine().getRenderWidth(), _.getEngine().getRenderHeight(), o._viewportRef),
                Vector3.ProjectToRef(d, o._identityMatrix, _.getTransformMatrix(), o._viewportRef, o._screenCoordinatesRef),
                typeof o._screenCoordinatesRef.x == "number" && typeof o._screenCoordinatesRef.y == "number" && !isNaN(o._screenCoordinatesRef.x) && !isNaN(o._screenCoordinatesRef.y) && (_.pointerX = o._screenCoordinatesRef.x,
                _.pointerY = o._screenCoordinatesRef.y,
                c.screenCoordinates = {
                    x: o._screenCoordinatesRef.x,
                    y: o._screenCoordinatesRef.y
                }))
            }
            var k = null;
            o._utilityLayerScene && (k = o._utilityLayerScene.pickWithRay(c.tmpRay, o._utilityLayerScene.pointerMovePredicate || o.raySelectionPredicate));
            var j = o._scene.pickWithRay(c.tmpRay, o._scene.pointerMovePredicate || o.raySelectionPredicate);
            !k || !k.hit ? c.pick = j : !j || !j.hit || k.distance < j.distance ? c.pick = k : c.pick = j,
            c.pick && c.xrController && (c.pick.aimTransform = c.xrController.pointer,
            c.pick.gripTransform = c.xrController.grip || null);
            var $ = c.pick;
            if ($ && $.pickedPoint && $.hit) {
                o._updatePointerDistance(c.laserPointer, $.distance),
                c.selectionMesh.position.copyFrom($.pickedPoint),
                c.selectionMesh.scaling.x = Math.sqrt($.distance),
                c.selectionMesh.scaling.y = Math.sqrt($.distance),
                c.selectionMesh.scaling.z = Math.sqrt($.distance);
                var _e = o._convertNormalToDirectionOfRay($.getNormal(!0), c.tmpRay)
                  , et = .001;
                if (c.selectionMesh.position.copyFrom($.pickedPoint),
                _e) {
                    var tt = Vector3.Cross(Axis.Y, _e)
                      , rt = Vector3.Cross(_e, tt);
                    Vector3.RotationFromAxisToRef(rt, _e, tt, c.selectionMesh.rotation),
                    c.selectionMesh.position.addInPlace(_e.scale(et))
                }
                c.selectionMesh.isVisible = o.displaySelectionMesh,
                c.meshUnderPointer = $.pickedMesh
            } else
                c.selectionMesh.isVisible = !1,
                o._updatePointerDistance(c.laserPointer, 1),
                c.meshUnderPointer = null
        })
    }
    ,
    Object.defineProperty(e.prototype, "_utilityLayerScene", {
        get: function() {
            return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachGazeMode = function(i) {
        var o = this
          , s = this._controllers[i && i.uniqueId || "camera"]
          , c = this._options.timeToSelect || 3e3
          , d = this._options.useUtilityLayer ? this._utilityLayerScene : this._scene
          , _ = new PickingInfo
          , b = CreateTorus("selection", {
            diameter: .0035 * 15,
            thickness: .0025 * 6,
            tessellation: 20
        }, d);
        b.isVisible = !1,
        b.isPickable = !1,
        b.parent = s.selectionMesh;
        var k = 0
          , j = !1
          , $ = {
            pointerId: s.id,
            pointerType: "xr"
        };
        s.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(function() {
            if (!!s.pick) {
                if (o._augmentPointerInit($, s.id, s.screenCoordinates),
                s.laserPointer.material.alpha = 0,
                b.isVisible = !1,
                s.pick.hit)
                    if (o._pickingMoved(_, s.pick))
                        j && (o._options.disablePointerUpOnTouchOut || o._scene.simulatePointerUp(s.pick, $)),
                        j = !1,
                        k = 0;
                    else if (k > c / 10 && (b.isVisible = !0),
                    k += o._scene.getEngine().getDeltaTime(),
                    k >= c)
                        o._scene.simulatePointerDown(s.pick, $),
                        j = !0,
                        o._options.disablePointerUpOnTouchOut && o._scene.simulatePointerUp(s.pick, $),
                        b.isVisible = !1;
                    else {
                        var _e = 1 - k / c;
                        b.scaling.set(_e, _e, _e)
                    }
                else
                    j = !1,
                    k = 0;
                o._scene.simulatePointerMove(s.pick, $),
                _ = s.pick
            }
        }),
        this._options.renderingGroupId !== void 0 && (b.renderingGroupId = this._options.renderingGroupId),
        i && i.onDisposeObservable.addOnce(function() {
            s.pick && !o._options.disablePointerUpOnTouchOut && j && (o._scene.simulatePointerUp(s.pick, $),
            s.finalPointerUpTriggered = !0),
            b.dispose()
        })
    }
    ,
    e.prototype._attachScreenRayMode = function(i) {
        var o = this
          , s = this._controllers[i.uniqueId]
          , c = !1
          , d = {
            pointerId: s.id,
            pointerType: "xr"
        };
        s.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(function() {
            o._augmentPointerInit(d, s.id, s.screenCoordinates),
            !(!s.pick || o._options.disablePointerUpOnTouchOut && c) && (c ? o._scene.simulatePointerMove(s.pick, d) : (o._scene.simulatePointerDown(s.pick, d),
            c = !0,
            o._options.disablePointerUpOnTouchOut && o._scene.simulatePointerUp(s.pick, d)))
        }),
        i.onDisposeObservable.addOnce(function() {
            o._augmentPointerInit(d, s.id, s.screenCoordinates),
            s.pick && c && !o._options.disablePointerUpOnTouchOut && (o._scene.simulatePointerUp(s.pick, d),
            s.finalPointerUpTriggered = !0)
        })
    }
    ,
    e.prototype._attachTrackedPointerRayMode = function(i) {
        var o = this
          , s = this._controllers[i.uniqueId];
        if (this._options.forceGazeMode)
            return this._attachGazeMode(i);
        var c = {
            pointerId: s.id,
            pointerType: "xr"
        };
        if (s.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(function() {
            s.laserPointer.material.disableLighting = o.disablePointerLighting,
            s.selectionMesh.material.disableLighting = o.disableSelectionMeshLighting,
            s.pick && (o._augmentPointerInit(c, s.id, s.screenCoordinates),
            o._scene.simulatePointerMove(s.pick, c))
        }),
        i.inputSource.gamepad) {
            var d = function(k) {
                o._options.overrideButtonId && (s.selectionComponent = k.getComponent(o._options.overrideButtonId)),
                s.selectionComponent || (s.selectionComponent = k.getMainComponent()),
                s.onButtonChangedObserver = s.selectionComponent.onButtonStateChangedObservable.add(function(j) {
                    if (j.changes.pressed) {
                        var $ = j.changes.pressed.current;
                        s.pick ? (o._options.enablePointerSelectionOnAllControllers || i.uniqueId === o._attachedController) && (o._augmentPointerInit(c, s.id, s.screenCoordinates),
                        $ ? (o._scene.simulatePointerDown(s.pick, c),
                        s.selectionMesh.material.emissiveColor = o.selectionMeshPickedColor,
                        s.laserPointer.material.emissiveColor = o.laserPointerPickedColor) : (o._scene.simulatePointerUp(s.pick, c),
                        s.selectionMesh.material.emissiveColor = o.selectionMeshDefaultColor,
                        s.laserPointer.material.emissiveColor = o.laserPointerDefaultColor)) : $ && !o._options.enablePointerSelectionOnAllControllers && !o._options.disableSwitchOnClick && (o._attachedController = i.uniqueId)
                    }
                })
            };
            i.motionController ? d(i.motionController) : i.onMotionControllerInitObservable.add(d)
        } else {
            var _ = function(k) {
                o._augmentPointerInit(c, s.id, s.screenCoordinates),
                s.xrController && k.inputSource === s.xrController.inputSource && s.pick && (o._scene.simulatePointerDown(s.pick, c),
                s.selectionMesh.material.emissiveColor = o.selectionMeshPickedColor,
                s.laserPointer.material.emissiveColor = o.laserPointerPickedColor)
            }
              , b = function(k) {
                o._augmentPointerInit(c, s.id, s.screenCoordinates),
                s.xrController && k.inputSource === s.xrController.inputSource && s.pick && (o._scene.simulatePointerUp(s.pick, c),
                s.selectionMesh.material.emissiveColor = o.selectionMeshDefaultColor,
                s.laserPointer.material.emissiveColor = o.laserPointerDefaultColor)
            };
            s.eventListeners = {
                selectend: b,
                selectstart: _
            },
            this._xrSessionManager.session.addEventListener("selectstart", _),
            this._xrSessionManager.session.addEventListener("selectend", b)
        }
    }
    ,
    e.prototype._convertNormalToDirectionOfRay = function(i, o) {
        if (i) {
            var s = Math.acos(Vector3.Dot(i, o.direction));
            s < Math.PI / 2 && i.scaleInPlace(-1)
        }
        return i
    }
    ,
    e.prototype._detachController = function(i) {
        var o = this
          , s = this._controllers[i];
        !s || (s.selectionComponent && s.onButtonChangedObserver && s.selectionComponent.onButtonStateChangedObservable.remove(s.onButtonChangedObserver),
        s.onFrameObserver && this._xrSessionManager.onXRFrameObservable.remove(s.onFrameObserver),
        s.eventListeners && Object.keys(s.eventListeners).forEach(function(c) {
            var d = s.eventListeners && s.eventListeners[c];
            d && o._xrSessionManager.session.removeEventListener(c, d)
        }),
        this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(function() {
            try {
                if (!s.finalPointerUpTriggered) {
                    var c = {
                        pointerId: s.id,
                        pointerType: "xr"
                    };
                    o._augmentPointerInit(c, s.id, s.screenCoordinates),
                    o._scene.simulatePointerUp(new PickingInfo, c)
                }
                if (s.selectionMesh.dispose(),
                s.laserPointer.dispose(),
                delete o._controllers[i],
                o._attachedController === i) {
                    var d = Object.keys(o._controllers);
                    d.length ? o._attachedController = d[0] : o._attachedController = ""
                }
            } catch {
                Tools.Warn("controller already detached.")
            }
        }))
    }
    ,
    e.prototype._generateNewMeshPair = function(i) {
        var o = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene
          , s = this._options.customLasterPointerMeshGenerator ? this._options.customLasterPointerMeshGenerator() : CreateCylinder("laserPointer", {
            height: 1,
            diameterTop: 2e-4,
            diameterBottom: .004,
            tessellation: 20,
            subdivisions: 1
        }, o);
        s.parent = i;
        var c = new StandardMaterial("laserPointerMat",o);
        c.emissiveColor = this.laserPointerDefaultColor,
        c.alpha = .7,
        s.material = c,
        s.rotation.x = Math.PI / 2,
        this._updatePointerDistance(s, 1),
        s.isPickable = !1,
        s.isVisible = !1;
        var d = this._options.customSelectionMeshGenerator ? this._options.customSelectionMeshGenerator() : CreateTorus("gazeTracker", {
            diameter: .0035 * 3,
            thickness: .0025 * 3,
            tessellation: 20
        }, o);
        d.bakeCurrentTransformIntoVertices(),
        d.isPickable = !1,
        d.isVisible = !1;
        var _ = new StandardMaterial("targetMat",o);
        return _.specularColor = Color3.Black(),
        _.emissiveColor = this.selectionMeshDefaultColor,
        _.backFaceCulling = !1,
        d.material = _,
        this._options.renderingGroupId !== void 0 && (s.renderingGroupId = this._options.renderingGroupId,
        d.renderingGroupId = this._options.renderingGroupId),
        {
            laserPointer: s,
            selectionMesh: d
        }
    }
    ,
    e.prototype._pickingMoved = function(i, o) {
        var s;
        if (!i.hit || !o.hit || !i.pickedMesh || !i.pickedPoint || !o.pickedMesh || !o.pickedPoint || i.pickedMesh !== o.pickedMesh)
            return !0;
        (s = i.pickedPoint) === null || s === void 0 || s.subtractToRef(o.pickedPoint, this._tmpVectorForPickCompare),
        this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
        var c = (this._options.gazeModePointerMovedFactor || 1) * .01 * o.distance
          , d = this._tmpVectorForPickCompare.length();
        return d > c
    }
    ,
    e.prototype._updatePointerDistance = function(i, o) {
        o === void 0 && (o = 100),
        i.scaling.y = o,
        this._scene.useRightHandedSystem && (o *= -1),
        i.position.z = o / 2 + .05
    }
    ,
    e.prototype._augmentPointerInit = function(i, o, s) {
        i.pointerId = o,
        i.pointerType = "xr",
        s && (i.screenX = s.x,
        i.screenY = s.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(a, e) {
    return function() {
        return new WebXRControllerPointerSelection(a,e)
    }
}, WebXRControllerPointerSelection.Version, !0);
SubMesh.prototype._projectOnTrianglesToRef = function(a, e, i, o, s, c) {
    for (var d = TmpVectors.Vector3[0], _ = TmpVectors.Vector3[1], b = 1 / 0, k = this.indexStart; k < this.indexStart + this.indexCount - (3 - o); k += o) {
        var j = i[k]
          , $ = i[k + 1]
          , _e = i[k + 2];
        if (s && _e === 4294967295) {
            k += 2;
            continue
        }
        var et = e[j]
          , tt = e[$]
          , rt = e[_e];
        if (!(!et || !tt || !rt)) {
            var it = Vector3.ProjectOnTriangleToRef(a, et, tt, rt, _);
            it < b && (d.copyFrom(_),
            b = it)
        }
    }
    return c.copyFrom(d),
    b
}
;
SubMesh.prototype._projectOnUnIndexedTrianglesToRef = function(a, e, i, o) {
    for (var s = TmpVectors.Vector3[0], c = TmpVectors.Vector3[1], d = 1 / 0, _ = this.verticesStart; _ < this.verticesStart + this.verticesCount; _ += 3) {
        var b = e[_]
          , k = e[_ + 1]
          , j = e[_ + 2]
          , $ = Vector3.ProjectOnTriangleToRef(a, b, k, j, c);
        $ < d && (s.copyFrom(c),
        d = $)
    }
    return o.copyFrom(s),
    d
}
;
SubMesh.prototype.projectToRef = function(a, e, i, o) {
    var s = this.getMaterial();
    if (!s)
        return -1;
    var c = 3
      , d = !1;
    switch (s.fillMode) {
    case 3:
    case 4:
    case 5:
    case 6:
    case 8:
        return -1;
    case 7:
        c = 1,
        d = !0;
        break
    }
    return this._mesh.getClassName() === "InstancedLinesMesh" || this._mesh.getClassName() === "LinesMesh" ? -1 : !i.length && this._mesh._unIndexed ? this._projectOnUnIndexedTrianglesToRef(a, e, i, o) : this._projectOnTrianglesToRef(a, e, i, c, d, o)
}
;
var WebXRNearInteraction = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i) || this;
        return s._options = o,
        s._attachController = function(c) {
            if (!s._controllers[c.uniqueId]) {
                var d = s._generateNewHandTipMesh()
                  , _ = s._generateVisualCue();
                switch (s._controllers[c.uniqueId] = {
                    xrController: c,
                    meshUnderPointer: null,
                    nearInteractionMesh: null,
                    pick: null,
                    pickIndexMeshTip: d,
                    grabRay: new Ray(new Vector3,new Vector3),
                    hoverInteraction: !1,
                    nearInteraction: !1,
                    grabInteraction: !1,
                    id: e._idCounter++,
                    pickedPointVisualCue: _
                },
                s._attachedController ? !s._options.enableNearInteractionOnAllControllers && s._options.preferredHandedness && c.inputSource.handedness === s._options.preferredHandedness && (s._attachedController = c.uniqueId) : s._options.enableNearInteractionOnAllControllers || (s._attachedController = c.uniqueId),
                c.inputSource.targetRayMode) {
                case "tracked-pointer":
                    return s._attachNearInteractionMode(c);
                case "gaze":
                    return null;
                case "screen":
                    return null
                }
            }
        }
        ,
        s._controllers = {},
        s._farInteractionFeature = null,
        s.selectionMeshDefaultColor = new Color3(.8,.8,.8),
        s.selectionMeshPickedColor = new Color3(.3,.3,1),
        s._hoverRadius = .1,
        s._pickRadius = .02,
        s._nearGrabLengthScale = 5,
        s._indexTipQuaternion = new Quaternion,
        s._indexTipOrientationVector = Vector3.Zero(),
        s._scene = s._xrSessionManager.scene,
        s._options.farInteractionFeature && (s._farInteractionFeature = s._options.farInteractionFeature),
        s
    }
    return e.prototype.attach = function() {
        var i = this;
        return a.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(o) {
            i._detachController(o.uniqueId)
        }),
        this._scene.constantlyUpdateMeshUnderPointer = !0,
        !0) : !1
    }
    ,
    e.prototype.detach = function() {
        var i = this;
        return a.prototype.detach.call(this) ? (Object.keys(this._controllers).forEach(function(o) {
            i._detachController(o)
        }),
        !0) : !1
    }
    ,
    e.prototype.getMeshUnderPointer = function(i) {
        return this._controllers[i] ? this._controllers[i].meshUnderPointer : null
    }
    ,
    e.prototype.getXRControllerByPointerId = function(i) {
        for (var o = Object.keys(this._controllers), s = 0; s < o.length; ++s)
            if (this._controllers[o[s]].id === i)
                return this._controllers[o[s]].xrController || null;
        return null
    }
    ,
    e.prototype.setFarInteractionFeature = function(i) {
        this._farInteractionFeature = i
    }
    ,
    e.prototype._nearPickPredicate = function(i) {
        return i.isEnabled() && i.isVisible && i.isPickable && i.isNearPickable
    }
    ,
    e.prototype._nearGrabPredicate = function(i) {
        return i.isEnabled() && i.isVisible && i.isPickable && i.isNearGrabbable
    }
    ,
    e.prototype._nearInteractionPredicate = function(i) {
        return i.isEnabled() && i.isVisible && i.isPickable && (i.isNearPickable || i.isNearGrabbable)
    }
    ,
    e.prototype._controllerAvailablePredicate = function(i, o) {
        for (var s = i; s; ) {
            if (s.reservedDataStore && s.reservedDataStore.nearInteraction && s.reservedDataStore.nearInteraction.excludedControllerId === o)
                return !1;
            s = s.parent
        }
        return !0
    }
    ,
    e.prototype._onXRFrame = function(i) {
        var o = this;
        Object.keys(this._controllers).forEach(function(s) {
            var c = o._controllers[s];
            if (!o._options.enableNearInteractionOnAllControllers && s !== o._attachedController || !c.xrController || !c.xrController.inputSource.hand) {
                c.pick = null;
                return
            }
            if (c.hoverInteraction = !1,
            c.nearInteraction = !1,
            c.xrController) {
                var d = c.xrController.inputSource.hand;
                if (d) {
                    var _ = d.get("index-finger-tip");
                    if (_) {
                        var b = i.getJointPose(_, o._xrSessionManager.referenceSpace);
                        if (b && b.transform) {
                            var k = o._scene.useRightHandedSystem ? 1 : -1
                              , j = b.transform.position
                              , $ = b.transform.orientation;
                            o._indexTipQuaternion.set($.x, $.y, $.z * k, $.w * k),
                            c.pickIndexMeshTip && c.pickIndexMeshTip.position.set(j.x, j.y, j.z * k);
                            var _e = o._nearGrabLengthScale * o._hoverRadius;
                            c.grabRay.origin.set(j.x, j.y, j.z * k),
                            o._indexTipQuaternion.toEulerAnglesToRef(o._indexTipOrientationVector),
                            c.grabRay.direction.set(o._indexTipOrientationVector.x, o._indexTipOrientationVector.y, o._indexTipOrientationVector.z),
                            c.grabRay.length = _e
                        }
                    }
                }
            } else
                return;
            var et = function(lt, ft) {
                var ht = null;
                return !ft || !ft.hit ? ht = lt : !lt || !lt.hit || ft.distance < lt.distance ? ht = ft : ht = lt,
                ht
            }
              , tt = function(lt) {
                var ft = new PickingInfo
                  , ht = !1
                  , pt = lt && lt.pickedPoint && lt.hit;
                return lt != null && lt.pickedPoint && (ht = lt.pickedPoint.x === 0 && lt.pickedPoint.y === 0 && lt.pickedPoint.z === 0),
                pt && !ht && (ft = lt),
                ft
            };
            if (!c.grabInteraction) {
                var rt = null
                  , it = null;
                o._options.useUtilityLayer && o._utilityLayerScene && (it = o._pickWithSphere(c, o._hoverRadius, o._utilityLayerScene, function(lt) {
                    return o._nearInteractionPredicate(lt)
                }));
                var nt = o._pickWithSphere(c, o._hoverRadius, o._scene, function(lt) {
                    return o._nearInteractionPredicate(lt)
                })
                  , ot = et(nt, it);
                if (ot && ot.hit && (rt = tt(ot),
                rt.hit && (c.hoverInteraction = !0)),
                c.pickIndexMeshTip && c.hoverInteraction) {
                    var at = null;
                    o._options.useUtilityLayer && o._utilityLayerScene && (at = o._pickWithSphere(c, o._pickRadius, o._utilityLayerScene, function(lt) {
                        return o._nearPickPredicate(lt)
                    }));
                    var st = o._pickWithSphere(c, o._pickRadius, o._scene, function(lt) {
                        return o._nearPickPredicate(lt)
                    })
                      , ut = et(st, at)
                      , ct = tt(ut);
                    ct.hit && (rt = ct,
                    c.nearInteraction = !0)
                }
                c.pick = rt,
                c.pick && c.pick.pickedPoint && c.pick.hit ? (c.meshUnderPointer = c.pick.pickedMesh,
                c.pickedPointVisualCue.position.copyFrom(c.pick.pickedPoint),
                c.pickedPointVisualCue.isVisible = !0,
                o._farInteractionFeature && o._farInteractionFeature.attached && o._farInteractionFeature._setPointerSelectionDisabledByPointerId(c.id, !0)) : (c.meshUnderPointer = null,
                c.pickedPointVisualCue.isVisible = !1,
                o._farInteractionFeature && o._farInteractionFeature.attached && o._farInteractionFeature._setPointerSelectionDisabledByPointerId(c.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 i = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene
          , o = CreateSphere("nearInteraction", {
            diameter: .0035 * 3
        }, i);
        o.bakeCurrentTransformIntoVertices(),
        o.isPickable = !1,
        o.isVisible = !1,
        o.rotationQuaternion = Quaternion.Identity();
        var s = new StandardMaterial("targetMat",i);
        return s.specularColor = Color3.Black(),
        s.emissiveColor = this.selectionMeshDefaultColor,
        s.backFaceCulling = !1,
        o.material = s,
        o
    }
    ,
    e.prototype._isControllerReadyForNearInteraction = function(i) {
        return this._farInteractionFeature ? this._farInteractionFeature._getPointerSelectionDisabledByPointerId(i) : !0
    }
    ,
    e.prototype._attachNearInteractionMode = function(i) {
        var o = this
          , s = this._controllers[i.uniqueId]
          , c = {
            pointerId: s.id,
            pointerType: "xr"
        };
        s.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(function() {
            !o._options.enableNearInteractionOnAllControllers && i.uniqueId !== o._attachedController || !s.xrController || !s.xrController.inputSource.hand || (s.pick && (s.pick.ray = s.grabRay),
            s.pick && o._isControllerReadyForNearInteraction(s.id) && o._scene.simulatePointerMove(s.pick, c),
            s.nearInteraction && s.pick && s.pick.hit ? s.nearInteractionMesh || (o._scene.simulatePointerDown(s.pick, c),
            s.nearInteractionMesh = s.meshUnderPointer) : s.nearInteractionMesh && s.pick && (o._scene.simulatePointerUp(s.pick, c),
            s.nearInteractionMesh = null))
        });
        var d = function(j) {
            o._options.enableNearInteractionOnAllControllers || i.uniqueId === o._attachedController && o._isControllerReadyForNearInteraction(s.id) ? (s.pick && (s.pick.ray = s.grabRay),
            j && s.pick && s.meshUnderPointer && o._nearGrabPredicate(s.meshUnderPointer) ? (s.grabInteraction = !0,
            s.pickedPointVisualCue.isVisible = !1,
            o._scene.simulatePointerDown(s.pick, c)) : !j && s.pick && s.grabInteraction && (o._scene.simulatePointerUp(s.pick, c),
            s.grabInteraction = !1,
            s.pickedPointVisualCue.isVisible = !0)) : j && !o._options.enableNearInteractionOnAllControllers && !o._options.disableSwitchOnClick && (o._attachedController = i.uniqueId)
        };
        if (i.inputSource.gamepad) {
            var _ = function(j) {
                s.squeezeComponent = j.getComponent("grasp"),
                s.squeezeComponent ? s.onSqueezeButtonChangedObserver = s.squeezeComponent.onButtonStateChangedObservable.add(function($) {
                    if ($.changes.pressed) {
                        var _e = $.changes.pressed.current;
                        d(_e)
                    }
                }) : (s.selectionComponent = j.getMainComponent(),
                s.onButtonChangedObserver = s.selectionComponent.onButtonStateChangedObservable.add(function($) {
                    if ($.changes.pressed) {
                        var _e = $.changes.pressed.current;
                        d(_e)
                    }
                }))
            };
            i.motionController ? _(i.motionController) : i.onMotionControllerInitObservable.add(_)
        } else {
            var b = function(j) {
                s.xrController && j.inputSource === s.xrController.inputSource && s.pick && o._isControllerReadyForNearInteraction(s.id) && s.meshUnderPointer && o._nearGrabPredicate(s.meshUnderPointer) && (s.grabInteraction = !0,
                s.pickedPointVisualCue.isVisible = !1,
                o._scene.simulatePointerDown(s.pick, c))
            }
              , k = function(j) {
                s.xrController && j.inputSource === s.xrController.inputSource && s.pick && o._isControllerReadyForNearInteraction(s.id) && (o._scene.simulatePointerUp(s.pick, c),
                s.grabInteraction = !1,
                s.pickedPointVisualCue.isVisible = !0)
            };
            s.eventListeners = {
                selectend: k,
                selectstart: b
            },
            this._xrSessionManager.session.addEventListener("selectstart", b),
            this._xrSessionManager.session.addEventListener("selectend", k)
        }
    }
    ,
    e.prototype._detachController = function(i) {
        var o = this, s, c = this._controllers[i];
        if (!!c) {
            c.squeezeComponent && c.onSqueezeButtonChangedObserver && c.squeezeComponent.onButtonStateChangedObservable.remove(c.onSqueezeButtonChangedObserver),
            c.selectionComponent && c.onButtonChangedObserver && c.selectionComponent.onButtonStateChangedObservable.remove(c.onButtonChangedObserver),
            c.onFrameObserver && this._xrSessionManager.onXRFrameObservable.remove(c.onFrameObserver),
            c.eventListeners && Object.keys(c.eventListeners).forEach(function(b) {
                var k = c.eventListeners && c.eventListeners[b];
                k && o._xrSessionManager.session.removeEventListener(b, k)
            }),
            (s = c.pickIndexMeshTip) === null || s === void 0 || s.dispose(),
            c.pickedPointVisualCue.dispose();
            var d = {
                pointerId: c.id,
                pointerType: "xr"
            };
            if (this._scene.simulatePointerUp(new PickingInfo, d),
            delete this._controllers[i],
            this._attachedController === i) {
                var _ = Object.keys(this._controllers);
                _.length ? this._attachedController = _[0] : this._attachedController = ""
            }
        }
    }
    ,
    e.prototype._generateNewHandTipMesh = function() {
        var i = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene
          , o = null
          , s = function(c, d, _) {
            var b = null;
            return b = CreateSphere(c, {
                diameter: 1
            }, _),
            b.scaling.set(d, d, d),
            b.isVisible = !1,
            b
        };
        return o = s("IndexPickSphere", this._pickRadius, i),
        o
    }
    ,
    e.prototype._pickWithSphere = function(i, o, s, c) {
        var d = new PickingInfo;
        if (d.distance = 1 / 0,
        i.pickIndexMeshTip && i.xrController)
            for (var _ = i.pickIndexMeshTip.position, b = BoundingSphere.CreateFromCenterAndRadius(_, o), k = 0; k < s.meshes.length; k++) {
                var j = s.meshes[k];
                if (!(!c(j) || !this._controllerAvailablePredicate(j, i.xrController.uniqueId))) {
                    var $ = e.PickMeshWithSphere(j, b);
                    $ && $.hit && $.distance < d.distance && (d.hit = $.hit,
                    d.pickedMesh = j,
                    d.pickedPoint = $.pickedPoint,
                    d.aimTransform = i.xrController.pointer,
                    d.gripTransform = i.xrController.grip || null,
                    d.originMesh = i.pickIndexMeshTip,
                    d.distance = $.distance)
                }
            }
        return d
    }
    ,
    e.PickMeshWithSphere = function(i, o, s) {
        s === void 0 && (s = !1);
        var c = i.subMeshes
          , d = new PickingInfo
          , _ = i.getBoundingInfo();
        if (!i._generatePointsArray() || !i.subMeshes || !_ || !s && !BoundingSphere.Intersects(_.boundingSphere, o))
            return d;
        var b = TmpVectors.Vector3[0], k = TmpVectors.Vector3[1], j = 1 / 0, $, _e, et, tt = TmpVectors.Vector3[2], rt = TmpVectors.Matrix[0];
        rt.copyFrom(i.getWorldMatrix()),
        rt.invert(),
        Vector3.TransformCoordinatesToRef(o.center, rt, tt);
        for (var it = 0; it < c.length; it++) {
            var nt = c[it];
            nt.projectToRef(tt, i._positions, i.getIndices(), k),
            Vector3.TransformCoordinatesToRef(k, i.getWorldMatrix(), k),
            $ = Vector3.Distance(k, o.center),
            et = Vector3.Distance(k, i.getAbsolutePosition()),
            _e = Vector3.Distance(o.center, i.getAbsolutePosition()),
            _e !== -1 && et !== -1 && et > _e && ($ = 0,
            k.copyFrom(o.center)),
            $ !== -1 && $ < j && (j = $,
            b.copyFrom(k))
        }
        return j < o.radius && (d.hit = !0,
        d.distance = j,
        d.pickedMesh = i,
        d.pickedPoint = b.clone()),
        d
    }
    ,
    e._idCounter = 200,
    e.Name = WebXRFeatureName.NEAR_INTERACTION,
    e.Version = 1,
    e
}(WebXRAbstractFeature);
WebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name, function(a, e) {
    return function() {
        return new WebXRNearInteraction(a,e)
    }
}, WebXRNearInteraction.Version, !0);
var WebXREnterExitUIButton = function() {
    function a(e, i, o) {
        this.element = e,
        this.sessionMode = i,
        this.referenceSpaceType = o
    }
    return a.prototype.update = function(e) {}
    ,
    a
}(), WebXREnterExitUI = function() {
    function a(e, i) {
        var o = this;
        if (this.scene = e,
        this.options = i,
        this._activeButton = null,
        this._buttons = [],
        this.activeButtonChangedObservable = new Observable,
        this._onSessionGranted = function($) {
            o._helper && o._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;",
        !i.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 (i.customButtons)
            this._buttons = i.customButtons;
        else {
            var s = i.sessionMode || "immersive-vr"
              , c = i.referenceSpaceType || "local-floor"
              , d = 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"
              , _ = ".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(" + d + "); 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) }";
            _ += '.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';
            var b = document.createElement("style");
            b.appendChild(document.createTextNode(_)),
            document.getElementsByTagName("head")[0].appendChild(b);
            var k = document.createElement("button");
            k.className = "babylonVRicon",
            k.title = s + " - " + c,
            this._buttons.push(new WebXREnterExitUIButton(k,s,c)),
            this._buttons[this._buttons.length - 1].update = function($) {
                this.element.style.display = $ === null || $ === this ? "" : "none",
                k.className = "babylonVRicon" + ($ === this ? " vrdisplaypresenting" : "")
            }
            ,
            this._updateButtons(null)
        }
        var j = e.getEngine().getInputElement();
        j && j.parentNode && (j.parentNode.appendChild(this.overlay),
        e.onDisposeObservable.addOnce(function() {
            o.dispose()
        }))
    }
    return a.prototype.setHelperAsync = function(e, i) {
        return __awaiter(this, void 0, void 0, function() {
            var o, s, c = this;
            return __generator(this, function(d) {
                switch (d.label) {
                case 0:
                    return this._helper = e,
                    this._renderTarget = i,
                    o = this._buttons.map(function(_) {
                        return e.sessionManager.isSessionSupportedAsync(_.sessionMode)
                    }),
                    e.onStateChangedObservable.add(function(_) {
                        _ == WebXRState.NOT_IN_XR && c._updateButtons(null)
                    }),
                    [4, Promise.all(o)];
                case 1:
                    return s = d.sent(),
                    s.forEach(function(_, b) {
                        _ ? (c.overlay.appendChild(c._buttons[b].element),
                        c._buttons[b].element.onclick = c._enterXRWithButtonIndex.bind(c, b)) : Tools.Warn('Session mode "' + c._buttons[b].sessionMode + '" not supported in browser')
                    }),
                    [2]
                }
            })
        })
    }
    ,
    a.CreateAsync = function(e, i, o) {
        return __awaiter(this, void 0, void 0, function() {
            var s;
            return __generator(this, function(c) {
                switch (c.label) {
                case 0:
                    return s = new a(e,o),
                    [4, s.setHelperAsync(i, o.renderTarget || void 0)];
                case 1:
                    return c.sent(),
                    [2, s]
                }
            })
        })
    }
    ,
    a.prototype._enterXRWithButtonIndex = function(e) {
        return e === void 0 && (e = 0),
        __awaiter(this, void 0, void 0, function() {
            var i, o, s;
            return __generator(this, function(c) {
                switch (c.label) {
                case 0:
                    return this._helper.state != WebXRState.IN_XR ? [3, 2] : [4, this._helper.exitXRAsync()];
                case 1:
                    return c.sent(),
                    this._updateButtons(null),
                    [3, 6];
                case 2:
                    if (this._helper.state != WebXRState.NOT_IN_XR)
                        return [3, 6];
                    c.label = 3;
                case 3:
                    return c.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 c.sent(),
                    this._updateButtons(this._buttons[e]),
                    [3, 6];
                case 5:
                    return i = c.sent(),
                    this._updateButtons(null),
                    o = this._buttons[e].element,
                    s = o.title,
                    o.title = "Error entering XR session : " + s,
                    o.classList.add("xr-error"),
                    this.options.onError && this.options.onError(i),
                    [3, 6];
                case 6:
                    return [2]
                }
            })
        })
    }
    ,
    a.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)
    }
    ,
    a.prototype._updateButtons = function(e) {
        var i = this;
        this._activeButton = e,
        this._buttons.forEach(function(o) {
            o.update(i._activeButton)
        }),
        this.activeButtonChangedObservable.notifyObservers(this._activeButton)
    }
    ,
    a
}(), TimerState;
(function(a) {
    a[a.INIT = 0] = "INIT",
    a[a.STARTED = 1] = "STARTED",
    a[a.ENDED = 2] = "ENDED"
}
)(TimerState || (TimerState = {}));
function setAndStartTimer(a) {
    var e, i = 0, o = Date.now();
    a.observableParameters = (e = a.observableParameters) !== null && e !== void 0 ? e : {};
    var s = a.contextObservable.add(function(c) {
        var d = Date.now();
        i = d - o;
        var _ = {
            startTime: o,
            currentTime: d,
            deltaTime: i,
            completeRate: i / a.timeout,
            payload: c
        };
        a.onTick && a.onTick(_),
        a.breakCondition && a.breakCondition() && (a.contextObservable.remove(s),
        a.onAborted && a.onAborted(_)),
        i >= a.timeout && (a.contextObservable.remove(s),
        a.onEnded && a.onEnded(_))
    }, a.observableParameters.mask, a.observableParameters.insertFirst, a.observableParameters.scope);
    return s
}
(function() {
    function a(e) {
        var i = this, o, s;
        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(c) {
            var d = Date.now();
            i._timer = d - i._startTime;
            var _ = {
                startTime: i._startTime,
                currentTime: d,
                deltaTime: i._timer,
                completeRate: i._timer / i._timeToEnd,
                payload: c
            }
              , b = i._breakOnNextTick || i._breakCondition(_);
            b || i._timer >= i._timeToEnd ? i._stop(_, b) : i.onEachCountObservable.notifyObservers(_)
        }
        ,
        this._setState(TimerState.INIT),
        this._contextObservable = e.contextObservable,
        this._observableParameters = (o = e.observableParameters) !== null && o !== void 0 ? o : {},
        this._breakCondition = (s = e.breakCondition) !== null && s !== void 0 ? s : 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(a.prototype, "breakCondition", {
        set: function(e) {
            this._breakCondition = e
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.clearObservables = function() {
        this.onEachCountObservable.clear(),
        this.onTimerAbortedObservable.clear(),
        this.onTimerEndedObservable.clear(),
        this.onStateChangedObservable.clear()
    }
    ,
    a.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)
    }
    ,
    a.prototype.stop = function() {
        this._state === TimerState.STARTED && (this._breakOnNextTick = !0)
    }
    ,
    a.prototype.dispose = function() {
        this._observer && this._contextObservable.remove(this._observer),
        this.clearObservables()
    }
    ,
    a.prototype._setState = function(e) {
        this._state = e,
        this.onStateChangedObservable.notifyObservers(this._state)
    }
    ,
    a.prototype._stop = function(e, i) {
        i === void 0 && (i = !1),
        this._contextObservable.remove(this._observer),
        this._setState(TimerState.ENDED),
        i ? this.onTimerAbortedObservable.notifyObservers(e) : this.onTimerEndedObservable.notifyObservers(e)
    }
    ,
    a
}
)();
var WebXRMotionControllerTeleportation = function(a) {
    __extends(e, a);
    function e(i, o) {
        var s = a.call(this, i) || this;
        return s._options = o,
        s._controllers = {},
        s._snappedToPoint = !1,
        s._tmpRay = new Ray(new Vector3,new Vector3),
        s._tmpVector = new Vector3,
        s._tmpQuaternion = new Quaternion,
        s.skipNextTeleportation = !1,
        s.backwardsMovementEnabled = !0,
        s.backwardsTeleportationDistance = .7,
        s.parabolicCheckRadius = 5,
        s.parabolicRayEnabled = !0,
        s.straightRayEnabled = !0,
        s.rotationAngle = Math.PI / 8,
        s.onTargetMeshPositionUpdatedObservable = new Observable,
        s.teleportationEnabled = !0,
        s._rotationEnabled = !0,
        s._attachController = function(c) {
            if (!(s._controllers[c.uniqueId] || s._options.forceHandedness && c.inputSource.handedness !== s._options.forceHandedness)) {
                s._controllers[c.uniqueId] = {
                    xrController: c,
                    teleportationState: {
                        forward: !1,
                        backwards: !1,
                        rotating: !1,
                        currentRotation: 0,
                        baseRotation: 0
                    }
                };
                var d = s._controllers[c.uniqueId];
                if (d.xrController.inputSource.targetRayMode === "tracked-pointer" && d.xrController.inputSource.gamepad) {
                    var _ = function() {
                        if (c.motionController) {
                            var b = c.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE) || c.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);
                            if (!b || s._options.useMainComponentOnly) {
                                var k = c.motionController.getMainComponent();
                                if (!k)
                                    return;
                                d.teleportationComponent = k,
                                d.onButtonChangedObserver = k.onButtonStateChangedObservable.add(function() {
                                    if (!!s.teleportationEnabled && k.changes.pressed)
                                        if (k.changes.pressed.current) {
                                            d.teleportationState.forward = !0,
                                            s._currentTeleportationControllerId = d.xrController.uniqueId,
                                            d.teleportationState.baseRotation = s._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,
                                            d.teleportationState.currentRotation = 0;
                                            var j = s._options.timeToTeleport || 3e3;
                                            setAndStartTimer({
                                                timeout: j,
                                                contextObservable: s._xrSessionManager.onXRFrameObservable,
                                                breakCondition: function() {
                                                    return !k.pressed
                                                },
                                                onEnded: function() {
                                                    s._currentTeleportationControllerId === d.xrController.uniqueId && d.teleportationState.forward && s._teleportForward(c.uniqueId)
                                                }
                                            })
                                        } else
                                            d.teleportationState.forward = !1,
                                            s._currentTeleportationControllerId = ""
                                })
                            } else
                                d.teleportationComponent = b,
                                d.onAxisChangedObserver = b.onAxisValueChangedObservable.add(function(j) {
                                    if (j.y <= .7 && d.teleportationState.backwards && (d.teleportationState.backwards = !1),
                                    j.y > .7 && !d.teleportationState.forward && s.backwardsMovementEnabled && !s.snapPointsOnly && !d.teleportationState.backwards) {
                                        d.teleportationState.backwards = !0,
                                        s._tmpQuaternion.copyFrom(s._options.xrInput.xrCamera.rotationQuaternion),
                                        s._tmpQuaternion.toEulerAnglesToRef(s._tmpVector),
                                        s._tmpVector.x = 0,
                                        s._tmpVector.z = 0,
                                        Quaternion.FromEulerVectorToRef(s._tmpVector, s._tmpQuaternion),
                                        s._tmpVector.set(0, 0, s.backwardsTeleportationDistance * (s._xrSessionManager.scene.useRightHandedSystem ? 1 : -1)),
                                        s._tmpVector.rotateByQuaternionToRef(s._tmpQuaternion, s._tmpVector),
                                        s._tmpVector.addInPlace(s._options.xrInput.xrCamera.position),
                                        s._tmpRay.origin.copyFrom(s._tmpVector),
                                        s._tmpRay.length = s._options.xrInput.xrCamera.realWorldHeight + .1,
                                        s._tmpRay.direction.set(0, -1, 0);
                                        var $ = s._xrSessionManager.scene.pickWithRay(s._tmpRay, function(et) {
                                            return s._floorMeshes.indexOf(et) !== -1
                                        });
                                        $ && $.pickedPoint && (s._options.xrInput.xrCamera.position.x = $.pickedPoint.x,
                                        s._options.xrInput.xrCamera.position.z = $.pickedPoint.z)
                                    }
                                    if (j.y < -.7 && !s._currentTeleportationControllerId && !d.teleportationState.rotating && s.teleportationEnabled && (d.teleportationState.forward = !0,
                                    s._currentTeleportationControllerId = d.xrController.uniqueId,
                                    d.teleportationState.baseRotation = s._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),
                                    j.x) {
                                        if (d.teleportationState.forward)
                                            s._currentTeleportationControllerId === d.xrController.uniqueId && (s.rotationEnabled ? setTimeout(function() {
                                                d.teleportationState.currentRotation = Math.atan2(j.x, j.y * (s._xrSessionManager.scene.useRightHandedSystem ? 1 : -1))
                                            }) : d.teleportationState.currentRotation = 0);
                                        else if (!d.teleportationState.rotating && Math.abs(j.x) > .7) {
                                            d.teleportationState.rotating = !0;
                                            var _e = s.rotationAngle * (j.x > 0 ? 1 : -1) * (s._xrSessionManager.scene.useRightHandedSystem ? -1 : 1);
                                            Quaternion.FromEulerAngles(0, _e, 0).multiplyToRef(s._options.xrInput.xrCamera.rotationQuaternion, s._options.xrInput.xrCamera.rotationQuaternion)
                                        }
                                    } else
                                        d.teleportationState.rotating = !1;
                                    j.x === 0 && j.y === 0 && d.teleportationState.forward && s._teleportForward(c.uniqueId)
                                })
                        }
                    };
                    c.motionController ? _() : c.onMotionControllerInitObservable.addOnce(function() {
                        _()
                    })
                } else
                    s._xrSessionManager.scene.onPointerObservable.add(function(b) {
                        if (b.type === PointerEventTypes.POINTERDOWN) {
                            d.teleportationState.forward = !0,
                            s._currentTeleportationControllerId = d.xrController.uniqueId,
                            d.teleportationState.baseRotation = s._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,
                            d.teleportationState.currentRotation = 0;
                            var k = s._options.timeToTeleport || 3e3;
                            setAndStartTimer({
                                timeout: k,
                                contextObservable: s._xrSessionManager.onXRFrameObservable,
                                onEnded: function() {
                                    s._currentTeleportationControllerId === d.xrController.uniqueId && d.teleportationState.forward && s._teleportForward(c.uniqueId)
                                }
                            })
                        } else
                            b.type === PointerEventTypes.POINTERUP && (d.teleportationState.forward = !1,
                            s._currentTeleportationControllerId = "")
                    })
            }
        }
        ,
        s._options.teleportationTargetMesh || s._createDefaultTargetMesh(),
        s._floorMeshes = s._options.floorMeshes || [],
        s._snapToPositions = s._options.snapPositions || [],
        s._setTargetMeshVisibility(!1),
        s
    }
    return Object.defineProperty(e.prototype, "rotationEnabled", {
        get: function() {
            return this._rotationEnabled
        },
        set: function(i) {
            if (this._rotationEnabled = i,
            this._options.teleportationTargetMesh) {
                var o = this._options.teleportationTargetMesh.getChildMeshes(!1, function(s) {
                    return s.name === "rotationCone"
                });
                o[0] && o[0].setEnabled(i)
            }
        },
        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(i) {
            this._options.snapPointsOnly = i
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addFloorMesh = function(i) {
        this._floorMeshes.push(i)
    }
    ,
    e.prototype.addBlockerMesh = function(i) {
        this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [],
        this._options.pickBlockerMeshes.push(i)
    }
    ,
    e.prototype.addSnapPoint = function(i) {
        this._snapToPositions.push(i)
    }
    ,
    e.prototype.attach = function() {
        var i = this;
        return a.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(o) {
            i._detachController(o.uniqueId)
        }),
        !0) : !1
    }
    ,
    e.prototype.detach = function() {
        var i = this;
        return a.prototype.detach.call(this) ? (Object.keys(this._controllers).forEach(function(o) {
            i._detachController(o)
        }),
        this._setTargetMeshVisibility(!1),
        this._currentTeleportationControllerId = "",
        this._controllers = {},
        !0) : !1
    }
    ,
    e.prototype.dispose = function() {
        a.prototype.dispose.call(this),
        this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.dispose(!1, !0)
    }
    ,
    e.prototype.removeFloorMesh = function(i) {
        var o = this._floorMeshes.indexOf(i);
        o !== -1 && this._floorMeshes.splice(o, 1)
    }
    ,
    e.prototype.removeBlockerMesh = function(i) {
        this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [];
        var o = this._options.pickBlockerMeshes.indexOf(i);
        o !== -1 && this._options.pickBlockerMeshes.splice(o, 1)
    }
    ,
    e.prototype.removeFloorMeshByName = function(i) {
        var o = this._xrSessionManager.scene.getMeshByName(i);
        o && this.removeFloorMesh(o)
    }
    ,
    e.prototype.removeSnapPoint = function(i) {
        var o = this._snapToPositions.indexOf(i);
        if (o === -1) {
            for (var s = 0; s < this._snapToPositions.length; ++s)
                if (this._snapToPositions[s].equals(i)) {
                    o = s;
                    break
                }
        }
        return o !== -1 ? (this._snapToPositions.splice(o, 1),
        !0) : !1
    }
    ,
    e.prototype.setSelectionFeature = function(i) {
        this._selectionFeature = i
    }
    ,
    e.prototype._onXRFrame = function(i) {
        var o = this
          , s = this._xrSessionManager.currentFrame
          , c = this._xrSessionManager.scene;
        if (!(!this.attach || !s)) {
            var d = this._options.teleportationTargetMesh;
            if (this._currentTeleportationControllerId) {
                if (!d)
                    return;
                d.rotationQuaternion = d.rotationQuaternion || new Quaternion;
                var _ = this._controllers[this._currentTeleportationControllerId];
                if (_ && _.teleportationState.forward) {
                    Quaternion.RotationYawPitchRollToRef(_.teleportationState.currentRotation + _.teleportationState.baseRotation, 0, 0, d.rotationQuaternion);
                    var b = !1;
                    if (_.xrController.getWorldPointerRayToRef(this._tmpRay),
                    this.straightRayEnabled) {
                        var k = c.pickWithRay(this._tmpRay, function(et) {
                            if (o._options.pickBlockerMeshes && o._options.pickBlockerMeshes.indexOf(et) !== -1)
                                return !0;
                            var tt = o._floorMeshes.indexOf(et);
                            return tt === -1 ? !1 : o._floorMeshes[tt].absolutePosition.y < o._options.xrInput.xrCamera.globalPosition.y
                        });
                        if (k && k.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(k.pickedMesh) !== -1)
                            return;
                        k && k.pickedPoint && (b = !0,
                        this._setTargetMeshPosition(k),
                        this._setTargetMeshVisibility(!0),
                        this._showParabolicPath(k))
                    }
                    if (this.parabolicRayEnabled && !b) {
                        var j = _.xrController.pointer.rotationQuaternion.toEulerAngles().x
                          , $ = 1 + (Math.PI / 2 - Math.abs(j))
                          , _e = this.parabolicCheckRadius * $;
                        this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(_e * 2), this._tmpVector),
                        this._tmpVector.y = this._tmpRay.origin.y,
                        this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(_e)),
                        this._tmpVector.subtractToRef(this._tmpRay.origin, this._tmpRay.direction),
                        this._tmpRay.direction.normalize();
                        var k = c.pickWithRay(this._tmpRay, function(tt) {
                            return o._options.pickBlockerMeshes && o._options.pickBlockerMeshes.indexOf(tt) !== -1 ? !0 : o._floorMeshes.indexOf(tt) !== -1
                        });
                        if (k && k.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(k.pickedMesh) !== -1)
                            return;
                        k && k.pickedPoint && (b = !0,
                        this._setTargetMeshPosition(k),
                        this._setTargetMeshVisibility(!0),
                        this._showParabolicPath(k))
                    }
                    this._setTargetMeshVisibility(b)
                } else
                    this._setTargetMeshVisibility(!1)
            } else
                this._setTargetMeshVisibility(!1)
        }
    }
    ,
    e.prototype._createDefaultTargetMesh = function() {
        this._options.defaultTargetMeshOptions = this._options.defaultTargetMeshOptions || {};
        var i = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._xrSessionManager.scene
          , o = CreateGround("teleportationTarget", {
            width: 2,
            height: 2,
            subdivisions: 2
        }, i);
        o.isPickable = !1;
        var s = 512
          , c = new DynamicTexture("teleportationPlaneDynamicTexture",s,i,!0);
        c.hasAlpha = !0;
        var d = c.getContext()
          , _ = s / 2
          , b = s / 2
          , k = 200;
        d.beginPath(),
        d.arc(_, b, k, 0, 2 * Math.PI, !1),
        d.fillStyle = this._options.defaultTargetMeshOptions.teleportationFillColor || "#444444",
        d.fill(),
        d.lineWidth = 10,
        d.strokeStyle = this._options.defaultTargetMeshOptions.teleportationBorderColor || "#FFFFFF",
        d.stroke(),
        d.closePath(),
        c.update();
        var j = new StandardMaterial("teleportationPlaneMaterial",i);
        j.diffuseTexture = c,
        o.material = j;
        var $ = CreateTorus("torusTeleportation", {
            diameter: .75,
            thickness: .1,
            tessellation: 20
        }, i);
        if ($.isPickable = !1,
        $.parent = o,
        !this._options.defaultTargetMeshOptions.disableAnimation) {
            var _e = new Animation("animationInnerCircle","position.y",30,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE)
              , et = [];
            et.push({
                frame: 0,
                value: 0
            }),
            et.push({
                frame: 30,
                value: .4
            }),
            et.push({
                frame: 60,
                value: 0
            }),
            _e.setKeys(et);
            var tt = new SineEase;
            tt.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),
            _e.setEasingFunction(tt),
            $.animations = [],
            $.animations.push(_e),
            i.beginAnimation($, 0, 60, !0)
        }
        var rt = CreateCylinder("rotationCone", {
            diameterTop: 0,
            tessellation: 4
        }, i);
        if (rt.isPickable = !1,
        rt.scaling.set(.5, .12, .2),
        rt.rotate(Axis.X, Math.PI / 2),
        rt.position.z = .6,
        rt.parent = $,
        this._options.defaultTargetMeshOptions.torusArrowMaterial)
            $.material = this._options.defaultTargetMeshOptions.torusArrowMaterial,
            rt.material = this._options.defaultTargetMeshOptions.torusArrowMaterial;
        else {
            var it = new StandardMaterial("torusConsMat",i);
            it.disableLighting = !!this._options.defaultTargetMeshOptions.disableLighting,
            it.disableLighting ? it.emissiveColor = new Color3(.3,.3,1) : it.diffuseColor = new Color3(.3,.3,1),
            it.alpha = .9,
            $.material = it,
            rt.material = it,
            this._teleportationRingMaterial = it
        }
        this._options.renderingGroupId !== void 0 && (o.renderingGroupId = this._options.renderingGroupId,
        $.renderingGroupId = this._options.renderingGroupId,
        rt.renderingGroupId = this._options.renderingGroupId),
        this._options.teleportationTargetMesh = o
    }
    ,
    e.prototype._detachController = function(i) {
        var o = this._controllers[i];
        !o || (o.teleportationComponent && (o.onAxisChangedObserver && o.teleportationComponent.onAxisValueChangedObservable.remove(o.onAxisChangedObserver),
        o.onButtonChangedObserver && o.teleportationComponent.onButtonStateChangedObservable.remove(o.onButtonChangedObserver)),
        delete this._controllers[i])
    }
    ,
    e.prototype._findClosestSnapPointWithRadius = function(i, o) {
        o === void 0 && (o = this._options.snapToPositionRadius || .8);
        var s = null
          , c = Number.MAX_VALUE;
        if (this._snapToPositions.length) {
            var d = o * o;
            this._snapToPositions.forEach(function(_) {
                var b = Vector3.DistanceSquared(_, i);
                b <= d && b < c && (c = b,
                s = _)
            })
        }
        return s
    }
    ,
    e.prototype._setTargetMeshPosition = function(i) {
        var o = i.pickedPoint;
        if (!(!this._options.teleportationTargetMesh || !o)) {
            var s = this._findClosestSnapPointWithRadius(o);
            this._snappedToPoint = !!s,
            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(s || o),
            this._options.teleportationTargetMesh.position.y += .01,
            this.onTargetMeshPositionUpdatedObservable.notifyObservers(i)
        }
    }
    ,
    e.prototype._setTargetMeshVisibility = function(i) {
        !this._options.teleportationTargetMesh || this._options.teleportationTargetMesh.isVisible !== i && (this._options.teleportationTargetMesh.isVisible = i,
        this._options.teleportationTargetMesh.getChildren(void 0, !1).forEach(function(o) {
            o.isVisible = i
        }),
        i ? this._selectionFeature && this._selectionFeature.detach() : (this._quadraticBezierCurve && (this._quadraticBezierCurve.dispose(),
        this._quadraticBezierCurve = null),
        this._selectionFeature && this._selectionFeature.attach()))
    }
    ,
    e.prototype._showParabolicPath = function(i) {
        if (!!i.pickedPoint) {
            var o = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._xrSessionManager.scene
              , s = this._controllers[this._currentTeleportationControllerId]
              , c = Curve3.CreateQuadraticBezier(s.xrController.pointer.absolutePosition, i.ray.origin, i.pickedPoint, 25);
            this._options.generateRayPathMesh ? this._quadraticBezierCurve = this._options.generateRayPathMesh(c.getPoints(), i) : this._quadraticBezierCurve = CreateLines("teleportation path line", {
                points: c.getPoints(),
                instance: this._quadraticBezierCurve,
                updatable: !0
            }, o),
            this._quadraticBezierCurve.isPickable = !1,
            this._options.renderingGroupId !== void 0 && (this._quadraticBezierCurve.renderingGroupId = this._options.renderingGroupId)
        }
    }
    ,
    e.prototype._teleportForward = function(i) {
        var o = this._controllers[i];
        if (!(!o || !o.teleportationState.forward || !this.teleportationEnabled) && (o.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 s = 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 += s,
                Quaternion.FromEulerAngles(0, o.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(a, e) {
    return function() {
        return new WebXRMotionControllerTeleportation(a,e)
    }
}, WebXRMotionControllerTeleportation.Version, !0);
var WebXRDefaultExperience = function() {
    function a() {}
    return a.CreateAsync = function(e, i) {
        i === void 0 && (i = {});
        var o = new a;
        if (!i.disableDefaultUI) {
            var s = __assign({
                renderTarget: o.renderTarget
            }, i.uiOptions || {});
            i.optionalFeatures && (typeof i.optionalFeatures == "boolean" ? s.optionalFeatures = ["hit-test", "anchors", "plane-detection", "hand-tracking"] : s.optionalFeatures = i.optionalFeatures),
            o.enterExitUI = new WebXREnterExitUI(e,s)
        }
        return WebXRExperienceHelper.CreateAsync(e).then(function(c) {
            if (o.baseExperience = c,
            i.ignoreNativeCameraTransformation && (o.baseExperience.camera.compensateOnFirstFrame = !1),
            o.input = new WebXRInput(c.sessionManager,c.camera,__assign({
                controllerOptions: {
                    renderingGroupId: i.renderingGroupId
                }
            }, i.inputOptions || {})),
            !i.disablePointerSelection) {
                var d = __assign(__assign({}, i.pointerSelectionOptions), {
                    xrInput: o.input,
                    renderingGroupId: i.renderingGroupId
                });
                o.pointerSelection = o.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name, i.useStablePlugins ? "stable" : "latest", d),
                i.disableTeleportation || (o.teleportation = o.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name, i.useStablePlugins ? "stable" : "latest", {
                    floorMeshes: i.floorMeshes,
                    xrInput: o.input,
                    renderingGroupId: i.renderingGroupId
                }),
                o.teleportation.setSelectionFeature(o.pointerSelection))
            }
            if (i.disableNearInteraction || (o.nearInteraction = o.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name, i.useStablePlugins ? "stable" : "latest", {
                xrInput: o.input,
                farInteractionFeature: o.pointerSelection,
                renderingGroupId: i.renderingGroupId,
                useUtilityLayer: !0,
                enableNearInteractionOnAllControllers: !0
            })),
            o.renderTarget = o.baseExperience.sessionManager.getWebXRRenderTarget(i.outputCanvasOptions),
            !i.disableDefaultUI)
                return o.enterExitUI.setHelperAsync(o.baseExperience, o.renderTarget)
        }).then(function() {
            return o
        }).catch(function(c) {
            return Logger$2.Error("Error initializing XR"),
            Logger$2.Error(c),
            o
        })
    }
    ,
    a.prototype.dispose = function() {
        this.baseExperience && this.baseExperience.dispose(),
        this.input && this.input.dispose(),
        this.enterExitUI && this.enterExitUI.dispose(),
        this.renderTarget && this.renderTarget.dispose()
    }
    ,
    a
}();
Scene.prototype.createDefaultLight = function(a) {
    if (a === void 0 && (a = !1),
    a && 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(a, e, i) {
    if (a === void 0 && (a = !1),
    e === void 0 && (e = !1),
    i === void 0 && (i = !1),
    e && this.activeCamera && (this.activeCamera.dispose(),
    this.activeCamera = null),
    !this.activeCamera) {
        var o = this.getWorldExtends(function(j) {
            return j.isVisible && j.isEnabled()
        }), s = o.max.subtract(o.min), c = o.min.add(s.scale(.5)), d, _ = s.length() * 1.5;
        if (isFinite(_) || (_ = 1,
        c.copyFromFloats(0, 0, 0)),
        a) {
            var b = new ArcRotateCamera("default camera",-(Math.PI / 2),Math.PI / 2,_,c,this);
            b.lowerRadiusLimit = _ * .01,
            b.wheelPrecision = 100 / _,
            d = b
        } else {
            var k = new FreeCamera("default camera",new Vector3(c.x,c.y,-_),this);
            k.setTarget(c),
            d = k
        }
        d.minZ = _ * .01,
        d.maxZ = _ * 1e3,
        d.speed = _ * .2,
        this.activeCamera = d,
        i && d.attachControl()
    }
}
;
Scene.prototype.createDefaultCameraOrLight = function(a, e, i) {
    a === void 0 && (a = !1),
    e === void 0 && (e = !1),
    i === void 0 && (i = !1),
    this.createDefaultLight(e),
    this.createDefaultCamera(a, e, i)
}
;
Scene.prototype.createDefaultSkybox = function(a, e, i, o, s) {
    if (e === void 0 && (e = !1),
    i === void 0 && (i = 1e3),
    o === void 0 && (o = 0),
    s === void 0 && (s = !0),
    !a)
        return Logger$2.Warn("Can not create default skybox without environment texture."),
        null;
    s && a && (this.environmentTexture = a);
    var c = CreateBox("hdrSkyBox", {
        size: i
    }, this);
    if (e) {
        var d = new PBRMaterial("skyBox",this);
        d.backFaceCulling = !1,
        d.reflectionTexture = a.clone(),
        d.reflectionTexture && (d.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE),
        d.microSurface = 1 - o,
        d.disableLighting = !0,
        d.twoSidedLighting = !0,
        c.material = d
    } else {
        var _ = new StandardMaterial("skyBox",this);
        _.backFaceCulling = !1,
        _.reflectionTexture = a.clone(),
        _.reflectionTexture && (_.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE),
        _.disableLighting = !0,
        c.material = _
    }
    return c.isPickable = !1,
    c.infiniteDistance = !0,
    c.ignoreCameraMaxZ = !0,
    c
}
;
Scene.prototype.createDefaultEnvironment = function(a) {
    return EnvironmentHelper ? new EnvironmentHelper(a,this) : null
}
;
Scene.prototype.createDefaultVRExperience = function(a) {
    return a === void 0 && (a = {}),
    new VRExperienceHelper(this,a)
}
;
Scene.prototype.createDefaultXRExperienceAsync = function(a) {
    return a === void 0 && (a = {}),
    WebXRDefaultExperience.CreateAsync(this, a).then(function(e) {
        return e
    })
}
;
var EMeshType = (a=>(a.XAvatar = "XAvatar",
a.XStaticMesh = "XStaticMesh",
a.XBreathPoint = "breathpoint",
a.Decal = "decal",
a.Cgplane = "cgplane",
a.Tv = "tv",
a.XSubSequence = "XSubSequence",
a.XBillboard = "XBillboard",
a))(EMeshType || {});
const checkOS = ()=>{
    const a = navigator.userAgent
      , e = /(?:Windows Phone)/.test(a)
      , i = /(?:SymbianOS)/.test(a) || e
      , o = /(?:Android)/.test(a)
      , s = /(?:Firefox)/.test(a);
    /(?:Chrome|CriOS)/.test(a);
    const c = /(?:iPad|PlayBook)/.test(a) || o && !/(?:Mobile)/.test(a) || s && /(?:Tablet)/.test(a)
      , d = /(?:iPhone|ipad|ipod)/.test(a) && !c
      , _ = !d && !o && !i;
    return {
        isTablet: c,
        isPhone: d,
        isIOS: /iPhone|iPod|iPad/.test(navigator.userAgent),
        isAndroid: o,
        isPc: _
    }
}
  , ue4Rotation2Xverse = a=>isRotationCorrect() ? (a.pitch >= 89.5 ? a.pitch = 89.5 : a.pitch <= -89.5 && (a.pitch = -89.5),
new Vector3(-1 * Math.PI * a.pitch / 180,Math.PI * a.yaw / 180 - Math.PI * 27 / 18,Math.PI * a.roll / 180 < .001 ? 0 : Math.PI * a.roll / 180)) : null
  , ue4Rotation2Xverse_mesh = a=>isRotationCorrect() ? new Vector3(Math.PI * a.pitch / 180,Math.PI * a.yaw / 180,Math.abs(Math.PI * a.roll) / 180 < .001 ? 0 : -1 * (Math.PI * a.roll) / 180) : null
  , scaleFromUE4toXverse = 100
  , ue4Scaling2Xverse = a=>isScalingCorrect() ? new Vector3(a.x,a.z,-1 * a.y) : null
  , ue4Position2Xverse = a=>isPositionCorrect() ? new Vector3(a.x * .01,a.z * .01,-1 * a.y * .01) : null
  , xversePosition2Ue4 = a=>isPositionCorrect() ? {
    x: a.x * 100,
    y: -1 * a.z * 100,
    z: a.y * 100
} : null
  , xverseRotation2Ue4 = a=>{
    if (isPositionCorrect()) {
        let e = 0;
        return a.z == 0 ? e = 0 : e = 180 * a.z / Math.PI,
        {
            pitch: 180 * a.x * -1 / Math.PI,
            yaw: (a.y + Math.PI * 27 / 18) * 180 / Math.PI,
            roll: e
        }
    } else
        return null
}
  , xverseRotation2Ue4_mesh = a=>{
    if (isPositionCorrect()) {
        let e = 0;
        return a.z == 0 ? e = 0 : e = -1 * (180 * a.z) / Math.PI,
        {
            pitch: 180 * a.x / Math.PI,
            yaw: a.y * 180 / Math.PI,
            roll: e
        }
    } else
        return null
}
  , calcDistance3D = (a,e)=>Math.sqrt((a.x - e.x) * (a.x - e.x) + (a.y - e.y) * (a.y - e.y) + (a.z - e.z) * (a.z - e.z))
  , calcDistance3DVector = (a,e)=>Math.sqrt((a.x - e.x) * (a.x - e.x) + (a.y - e.y) * (a.y - e.y) + (a.z - e.z) * (a.z - e.z))
  , isPositionCorrect = a=>!0
  , isScalingCorrect = a=>!0
  , calcDistance3DAngle = (a,e)=>Math.sqrt((a.roll - e.roll) * (a.roll - e.roll) + (a.pitch - e.pitch) * (a.pitch - e.pitch) + (a.yaw - e.yaw) * (a.yaw - e.yaw))
  , isRotationCorrect = a=>!0
  , getStringBoundaries = (a,e,i=new Map)=>{
    let o = 0
      , s = ""
      , c = -1
      , d = 0;
    const _ = [0];
    for (let b = 0; b < a.length; b++) {
        const k = a.codePointAt(b);
        let j = i.get(k);
        if (j)
            o += j,
            s += a[b],
            k > 64 && k < 91 || k > 96 && k < 123 ? (c == -1 && (c = b),
            d += j) : (c = -1,
            d = 0);
        else if (k < 975 || k > 1024 && k < 1920)
            j = 1,
            o++,
            s += a[b],
            k > 64 && k < 91 || k > 96 && k < 123 ? (c == -1 && (c = b),
            d += j) : (c = -1,
            d = 0);
        else if (k > 4499 && k < 4600 || k > 8207 && k < 8232 || k > 8238 && k < 8287 || k > 8238 && k < 8287 || k > 8304 && k < 8384 || k > 8447 && k < 9211 || k > 11263 && k < 11624 || k > 11646 && k < 11671 || k > 11679 && k < 11845 || k > 11903 && k < 12020 || k > 12031 && k < 12246 || k > 12287 && k < 12544 || k > 12548 && k < 12728 || k > 12735 && k < 12772 || k > 12783 && k < 19894 || k > 19967 && k < 40918 || k > 42191 && k < 42240 || k > 44031 && k < 55204 || k > 59276 && k < 59287 || k > 59412 && k < 59493 || k > 63743 && k < 64207 || k > 65039 && k < 65050 || k > 65071 && k < 65510)
            j = 2,
            o += 2,
            c = -1,
            d = 0,
            s += a[b];
        else if (k > 9311 && k < 11158) {
            j = 2,
            o += 2,
            c = -1,
            d = 0,
            s += a[b];
            const $ = a.codePointAt(b + 1);
            $ > 65023 && $ < 65040 && (s += a[b + 1],
            b++)
        } else
            k > 126979 && k < 129783 && (j = 2,
            o += 2,
            c = -1,
            d = 0,
            b++,
            s += String.fromCodePoint(k));
        if (b == _[_.length - 1] + 1 && c > 0 ? (_[_.length - 1] = c,
        o = 0 + d) : o > e && (_.push(b),
        d >= o && (d = 0 + j,
        c = 0),
        o = 0 + j),
        b >= a.length - 1)
            break
    }
    return _[_.length - 1] != a.length && _.push(a.length),
    [s, _]
}
  , getAlphaWidthMap = (a,e)=>{
    const i = new DynamicTexture("test",3,e)
      , o = new Map;
    for (let s = 32; s < 127; s++) {
        const c = String.fromCodePoint(s)
          , d = 2 + "px " + a;
        i.drawText(c, null, null, d, "#000000", "#ffffff", !0);
        const _ = i.getContext();
        _.font = d;
        const b = _.measureText(c).width;
        o.set(s, b)
    }
    return i.dispose(),
    o
}
  , _RegisteredClass = {};
function RegisterXObjectClass(a, e) {
    _RegisteredClass[a] = e
}
function GetXObjectClass(a) {
    return _RegisteredClass[a]
}
const DEFAULT_LOGGER = {
    debug: console.log,
    info: console.log,
    warn: console.warn,
    error: console.error
}
  , _Logger = class {
    static setLogger(a) {
        _Logger.instance = a
    }
    constructor(a) {
        this.module = a
    }
    debug(...a) {
        return _Logger.instance.debug(...a)
    }
    info(...a) {
        return _Logger.instance.info(...a)
    }
    warn(...a) {
        return _Logger.instance.warn(...a)
    }
    error(...a) {
        return _Logger.instance.error(...a)
    }
}
;
let Logger$1 = _Logger;
Logger$1.instance = DEFAULT_LOGGER;
new Logger$1("Serialization");
const __decoratorInitialStore = {}
  , __mergedStore = {}
  , deepCopy = function(a, e, i) {
    let o;
    if (e || (e = ""),
    i || (i = !1),
    a == null || typeof a != "object")
        return a;
    if (a instanceof Date)
        return o = new Date,
        o.setTime(a.getTime()),
        o;
    if (a instanceof Array) {
        o = [];
        for (let s = 0, c = a.length; s < c; s++)
            o[s] = deepCopy(a[s], e, i);
        return o
    }
    if (a instanceof Object) {
        if (a instanceof XObject)
            return o = _copySource(a, e, i),
            o;
        if (a instanceof AssetContainer)
            return i ? o = a.clone(e, !1, {
                doNotInstantiate: !0
            }, !1) : o = a.clone(e),
            o;
        for (const s in a)
            Object.prototype.hasOwnProperty.call(a, s) && (o[s] = deepCopy(a[s]));
        return o
    }
    throw new Error("Unable to copy obj! Its type isn't supported.")
}
  , _copySource = function(a, e, i) {
    const o = GetXObjectClass(a.getClassName())
      , s = new o
      , c = getPropertiesMarkAsSerializable(s);
    e || (e = ""),
    i || (i = !1);
    for (const d in c) {
        const _ = a[d];
        if (_ != null) {
            const b = s;
            _ instanceof XObject ? b[d] = _copySource(_, e, i) : b[d] = deepCopy(_, e, i)
        }
    }
    return s.name = e,
    s
};
function getDirectStore(a) {
    const e = a.getClassName();
    return __decoratorInitialStore[e] || (__decoratorInitialStore[e] = {}),
    __decoratorInitialStore[e]
}
function generateSerializableMember(a, e) {
    return (i,o)=>{
        const s = getDirectStore(i);
        s[o] || (s[o] = {
            type: a,
            sourceName: e
        })
    }
}
function xProperty(a) {
    return generateSerializableMember(0, a)
}
function getPropertiesMarkAsSerializable(a) {
    const e = a.getClassName();
    if (__mergedStore[e])
        return __mergedStore[e];
    __mergedStore[e] = {};
    const i = __mergedStore[e];
    let o = a
      , s = e;
    for (; s; ) {
        const c = __decoratorInitialStore[s];
        for (const b in c)
            i[b] = c[b];
        let d, _ = !1;
        do {
            if (d = Object.getPrototypeOf(o),
            !d.getClassName) {
                _ = !0;
                break
            }
            if (d.getClassName() !== s)
                break;
            o = d
        } while (d);
        if (_)
            break;
        s = d.getClassName(),
        o = d
    }
    return i
}
class XArchive {
    constructor() {
        this.loadingPromises = new Array
    }
    static serialize(e) {
        if (!e.outer)
            return {
                className: "",
                uuid: 0,
                xobjectInfo: {},
                sceneInfo: ""
            };
        const o = e.outer.uuid
          , s = {
            className: "",
            uuid: 0,
            xobjectInfo: {},
            sceneInfo: ""
        };
        s.className = e.getClassName(),
        s.uuid = o;
        const c = getPropertiesMarkAsSerializable(e);
        for (const d in c) {
            const b = c[d].sourceName || d
              , k = e[d];
            s.xobjectInfo[b] = k
        }
        return s
    }
    async deserializeObject(e, i="") {
        if (e == null || typeof e != "object" || e instanceof Date)
            return e;
        if (e instanceof Array) {
            for (let o = 0, s = e.length; o < s; o++)
                e[o] = this.deserializeObject(e[o], i);
            return e
        }
        if (e instanceof Object) {
            if (e.className)
                GetXObjectClass(e.className) && this.deserialize(e, i);
            else
                return e;
            return e
        }
        throw new Error("Unable to copy obj! Its type isn't supported.")
    }
    async deserialize(e, i="") {
        const o = GetXObjectClass(e.className);
        if (!o)
            throw new Error("Unable to deserialize obj! Its type isn't XObject.");
        const s = new o
          , c = getPropertiesMarkAsSerializable(s);
        for (const d in c) {
            const _ = c[d]
              , b = e.xobjectInfo[_.sourceName || d];
            if (b != null)
                if (s[d]instanceof AssetContainer) {
                    const k = await SceneLoader.LoadAssetContainerAsync(i, b.sceneInfo, EngineStore.LastCreatedScene);
                    s[d] = k,
                    k.addAllToScene()
                } else
                    s[d]instanceof XObject ? s[d] = await this.deserialize(b, i) : s[d] = await this.deserializeObject(b, i)
        }
        return s.postLoad(),
        s
    }
    static clone(e, i, o) {
        return deepCopy(e, i, o)
    }
}
var __defProp$3 = Object.defineProperty
  , __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor
  , __decorateClass$3 = (a,e,i,o)=>{
    for (var s = o > 1 ? void 0 : o ? __getOwnPropDesc$3(e, i) : e, c = a.length - 1, d; c >= 0; c--)
        (d = a[c]) && (s = (o ? d(e, i, s) : d(s)) || s);
    return o && s && __defProp$3(e, i, s),
    s
}
;
class XObject {
    constructor() {
        this._name = "",
        this._outer = null
    }
    set outer(e) {
        this._outer = e
    }
    get outer() {
        return this._outer
    }
    get name() {
        return this._name
    }
    set name(e) {
        this._name = e
    }
    getClassName() {
        return "XObject"
    }
    toJSON() {
        return XArchive.serialize(this)
    }
    dispose() {}
    postLoad() {}
    clone(e) {
        return XArchive.clone(this, e)
    }
}
__decorateClass$3([xProperty("name")], XObject.prototype, "_name", 2);
RegisterXObjectClass("XObject", XObject);
var Codes$2 = (a=>(a[a.Success = 0] = "Success",
a[a.Timeout = 1003] = "Timeout",
a))(Codes$2 || {});
const COMPONENT_LIST_PREFIX = "/component_list.json";
class XverseError$1 extends Error {
    constructor(e, i) {
        super(i),
        this.code = e
    }
    toJSON() {
        return {
            code: this.code,
            message: this.message
        }
    }
    toString() {
        if (Object(this) !== this)
            throw new TypeError;
        let i = this.name;
        i = i === void 0 ? "Error" : String(i);
        let o = this.message;
        o = o === void 0 ? "" : String(o);
        const s = this.code;
        return o = s === void 0 ? o : s + "," + o,
        i === "" ? o : o === "" ? i : i + ": " + o
    }
}
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 = (a,e)=>e + "_" + a;
var _GLTFUtilities = function() {
    function a() {}
    return a._CreateBufferView = function(e, i, o, s, c) {
        var d = {
            buffer: e,
            byteLength: o
        };
        return i && (d.byteOffset = i),
        c && (d.name = c),
        s && (d.byteStride = s),
        d
    }
    ,
    a._CreateAccessor = function(e, i, o, s, c, d, _, b) {
        var k = {
            name: i,
            bufferView: e,
            componentType: s,
            count: c,
            type: o
        };
        return _ != null && (k.min = _),
        b != null && (k.max = b),
        d != null && (k.byteOffset = d),
        k
    }
    ,
    a._CalculateMinMaxPositions = function(e, i, o, s) {
        var c = [1 / 0, 1 / 0, 1 / 0], d = [-1 / 0, -1 / 0, -1 / 0], _ = 3, b, k, j;
        if (o)
            for (var $ = i, _e = i + o; $ < _e; ++$) {
                b = _ * $,
                k = Vector3.FromArray(e, b),
                s && a._GetRightHandedPositionVector3FromRef(k),
                j = k.asArray();
                for (var et = 0; et < _; ++et) {
                    var tt = j[et];
                    tt < c[et] && (c[et] = tt),
                    tt > d[et] && (d[et] = tt),
                    ++b
                }
            }
        return {
            min: c,
            max: d
        }
    }
    ,
    a._GetRightHandedPositionVector3 = function(e) {
        return new Vector3(e.x,e.y,-e.z)
    }
    ,
    a._GetRightHandedPositionVector3FromRef = function(e) {
        e.z *= -1
    }
    ,
    a._GetRightHandedPositionArray3FromRef = function(e) {
        e[2] *= -1
    }
    ,
    a._GetRightHandedNormalVector3 = function(e) {
        return new Vector3(e.x,e.y,-e.z)
    }
    ,
    a._GetRightHandedNormalVector3FromRef = function(e) {
        e.z *= -1
    }
    ,
    a._GetRightHandedNormalArray3FromRef = function(e) {
        e[2] *= -1
    }
    ,
    a._GetRightHandedVector4FromRef = function(e) {
        e.z *= -1,
        e.w *= -1
    }
    ,
    a._GetRightHandedArray4FromRef = function(e) {
        e[2] *= -1,
        e[3] *= -1
    }
    ,
    a._GetRightHandedQuaternionFromRef = function(e) {
        e.x *= -1,
        e.y *= -1
    }
    ,
    a._GetRightHandedQuaternionArrayFromRef = function(e) {
        e[0] *= -1,
        e[1] *= -1
    }
    ,
    a._NormalizeTangentFromRef = function(e) {
        var i = Math.sqrt(e.x * e.x + e.y * e.y + e.z * e.z);
        i > 0 && (e.x /= i,
        e.y /= i,
        e.z /= i)
    }
    ,
    a._GetDataAccessorElementCount = function(e) {
        switch (e) {
        case "MAT2":
            return 4;
        case "MAT3":
            return 9;
        case "MAT4":
            return 16;
        case "SCALAR":
            return 1;
        case "VEC2":
            return 2;
        case "VEC3":
            return 3;
        case "VEC4":
            return 4
        }
    }
    ,
    a
}(), _TangentType;
(function(a) {
    a[a.INTANGENT = 0] = "INTANGENT",
    a[a.OUTTANGENT = 1] = "OUTTANGENT"
}
)(_TangentType || (_TangentType = {}));
var _GLTFAnimation = function() {
    function a() {}
    return a._CreateNodeAnimation = function(e, i, o, s, c, d) {
        var _ = []
          , b = []
          , k = i.getKeys()
          , j = a.calculateMinMaxKeyFrames(k)
          , $ = a._DeduceInterpolation(k, o, c)
          , _e = j.max - j.min
          , et = $.interpolationType
          , tt = $.shouldBakeAnimation;
        if (tt ? a._CreateBakedAnimation(e, i, o, j.min, j.max, i.framePerSecond, d, _, b, j, s, c) : et === "LINEAR" || et === "STEP" ? a._CreateLinearOrStepAnimation(e, i, o, _e, _, b, s, c) : et === "CUBICSPLINE" ? a._CreateCubicSplineAnimation(e, i, o, _e, _, b, s, c) : a._CreateBakedAnimation(e, i, o, j.min, j.max, i.framePerSecond, d, _, b, j, s, c),
        _.length && b.length) {
            var rt = {
                inputs: _,
                outputs: b,
                samplerInterpolation: et,
                inputsMin: tt ? j.min : Tools.FloatRound(j.min / i.framePerSecond),
                inputsMax: tt ? j.max : Tools.FloatRound(j.max / i.framePerSecond)
            };
            return rt
        }
        return null
    }
    ,
    a._DeduceAnimationInfo = function(e) {
        var i = null
          , o = "VEC3"
          , s = !1
          , c = e.targetProperty.split(".");
        switch (c[0]) {
        case "scaling":
            {
                i = "scale";
                break
            }
        case "position":
            {
                i = "translation";
                break
            }
        case "rotation":
            {
                o = "VEC4",
                i = "rotation";
                break
            }
        case "rotationQuaternion":
            {
                o = "VEC4",
                s = !0,
                i = "rotation";
                break
            }
        case "influence":
            {
                o = "SCALAR",
                i = "weights";
                break
            }
        default:
            Tools.Error("Unsupported animatable property " + c[0])
        }
        return i ? {
            animationChannelTargetPath: i,
            dataAccessorType: o,
            useQuaternion: s
        } : (Tools.Error("animation channel target path and data accessor type could be deduced"),
        null)
    }
    ,
    a._CreateNodeAnimationFromNodeAnimations = function(e, i, o, s, c, d, _, b, k, j) {
        var $;
        if (e instanceof TransformNode && e.animations)
            for (var _e = 0, et = e.animations; _e < et.length; _e++) {
                var tt = et[_e]
                  , rt = a._DeduceAnimationInfo(tt);
                rt && ($ = {
                    name: tt.name,
                    samplers: [],
                    channels: []
                },
                a.AddAnimation("" + tt.name, tt.hasRunningRuntimeAnimations ? i : $, e, tt, rt.dataAccessorType, rt.animationChannelTargetPath, s, d, _, b, k, rt.useQuaternion, j),
                $.samplers.length && $.channels.length && o.push($))
            }
    }
    ,
    a._CreateMorphTargetAnimationFromMorphTargetAnimations = function(e, i, o, s, c, d, _, b, k, j) {
        var $;
        if (e instanceof Mesh) {
            var _e = e.morphTargetManager;
            if (_e)
                for (var et = 0; et < _e.numTargets; ++et)
                    for (var tt = _e.getTarget(et), rt = 0, it = tt.animations; rt < it.length; rt++) {
                        for (var nt = it[rt], ot = new Animation("" + nt.name,"influence",nt.framePerSecond,nt.dataType,nt.loopMode,nt.enableBlending), at = [], st = nt.getKeys(), ut = 0; ut < st.length; ++ut)
                            for (var ct = st[ut], lt = 0; lt < _e.numTargets; ++lt)
                                lt == et ? at.push(ct) : at.push({
                                    frame: ct.frame,
                                    value: 0
                                });
                        ot.setKeys(at);
                        var ft = a._DeduceAnimationInfo(ot);
                        ft && ($ = {
                            name: ot.name,
                            samplers: [],
                            channels: []
                        },
                        a.AddAnimation(nt.name, nt.hasRunningRuntimeAnimations ? i : $, e, ot, ft.dataAccessorType, ft.animationChannelTargetPath, s, d, _, b, k, ft.useQuaternion, j, _e.numTargets),
                        $.samplers.length && $.channels.length && o.push($))
                    }
        }
    }
    ,
    a._CreateNodeAndMorphAnimationFromAnimationGroups = function(e, i, o, s, c, d, _, b, k) {
        var j, $;
        if (e.animationGroups)
            for (var _e = e.animationGroups, et = function(nt) {
                var ot = new Map
                  , at = new Map
                  , st = new Set
                  , ut = nt.to - nt.from;
                $ = {
                    name: nt.name,
                    channels: [],
                    samplers: []
                };
                for (var ct = function(ft) {
                    var ht = nt.targetedAnimations[ft]
                      , pt = ht.target
                      , dt = ht.animation;
                    if (pt instanceof TransformNode || pt.length === 1 && pt[0]instanceof TransformNode) {
                        var _t = a._DeduceAnimationInfo(ht.animation);
                        if (_t) {
                            var mt = pt instanceof TransformNode ? pt : pt[0]
                              , vt = b[mt.uniqueId];
                            a.AddAnimation("" + dt.name, $, mt, dt, _t.dataAccessorType, _t.animationChannelTargetPath, o, c, d, _, vt, _t.useQuaternion, k)
                        }
                    } else if (pt instanceof MorphTarget || pt.length === 1 && pt[0]instanceof MorphTarget) {
                        var _t = a._DeduceAnimationInfo(ht.animation);
                        if (_t) {
                            var yt = pt instanceof MorphTarget ? pt : pt[0];
                            if (yt) {
                                var Et = e.morphTargetManagers.find(function(St) {
                                    for (var xt = 0; xt < St.numTargets; ++xt)
                                        if (St.getTarget(xt) === yt)
                                            return !0;
                                    return !1
                                });
                                if (Et) {
                                    var At = e.meshes.find(function(St) {
                                        return St.morphTargetManager === Et
                                    });
                                    At && (ot.has(At) || ot.set(At, new Map),
                                    (j = ot.get(At)) === null || j === void 0 || j.set(yt, dt),
                                    st.add(At),
                                    at.set(At, dt))
                                }
                            }
                        }
                    }
                }, lt = 0; lt < nt.targetedAnimations.length; ++lt)
                    ct(lt);
                st.forEach(function(ft) {
                    for (var ht = ft.morphTargetManager, pt = null, dt = [], _t = at.get(ft), mt = _t.getKeys(), vt = mt.length, yt = 0; yt < vt; ++yt)
                        for (var Et = 0; Et < ht.numTargets; ++Et) {
                            var At = ht.getTarget(Et)
                              , gt = ot.get(ft);
                            if (gt) {
                                var St = gt.get(At);
                                St ? (pt || (pt = new Animation(nt.name + "_" + ft.name + "_MorphWeightAnimation","influence",St.framePerSecond,Animation.ANIMATIONTYPE_FLOAT,St.loopMode,St.enableBlending)),
                                dt.push(St.getKeys()[yt])) : dt.push({
                                    frame: nt.from + ut / vt * yt,
                                    value: At.influence,
                                    inTangent: mt[0].inTangent ? 0 : void 0,
                                    outTangent: mt[0].outTangent ? 0 : void 0
                                })
                            }
                        }
                    pt.setKeys(dt);
                    var xt = a._DeduceAnimationInfo(pt);
                    xt && a.AddAnimation(nt.name + "_" + ft.name + "_MorphWeightAnimation", $, ft, pt, xt.dataAccessorType, xt.animationChannelTargetPath, o, c, d, _, !1, xt.useQuaternion, k, ht == null ? void 0 : ht.numTargets)
                }),
                $.channels.length && $.samplers.length && i.push($)
            }, tt = 0, rt = _e; tt < rt.length; tt++) {
                var it = rt[tt];
                et(it)
            }
    }
    ,
    a.AddAnimation = function(e, i, o, s, c, d, _, b, k, j, $, _e, et, tt) {
        var rt = a._CreateNodeAnimation(o, s, d, $, _e, et), it, nt, ot, at, st, ut, ct;
        if (rt) {
            if (tt) {
                for (var lt = 0, ft = 0, ht = []; rt.inputs.length > 0; )
                    ft = rt.inputs.shift(),
                    lt % tt == 0 && ht.push(ft),
                    lt++;
                rt.inputs = ht
            }
            var pt = _[o.uniqueId]
              , dt = rt.inputs.length * 4;
            it = _GLTFUtilities._CreateBufferView(0, b.getByteOffset(), dt, void 0, e + "  keyframe data view"),
            k.push(it),
            rt.inputs.forEach(function(_t) {
                b.setFloat32(_t)
            }),
            nt = _GLTFUtilities._CreateAccessor(k.length - 1, e + "  keyframes", "SCALAR", 5126, rt.inputs.length, null, [rt.inputsMin], [rt.inputsMax]),
            j.push(nt),
            ot = j.length - 1,
            st = rt.outputs.length,
            dt = _GLTFUtilities._GetDataAccessorElementCount(c) * 4 * rt.outputs.length,
            it = _GLTFUtilities._CreateBufferView(0, b.getByteOffset(), dt, void 0, e + "  data view"),
            k.push(it),
            rt.outputs.forEach(function(_t) {
                _t.forEach(function(mt) {
                    b.setFloat32(mt)
                })
            }),
            nt = _GLTFUtilities._CreateAccessor(k.length - 1, e + "  data", c, 5126, st, null, null, null),
            j.push(nt),
            at = j.length - 1,
            ut = {
                interpolation: rt.samplerInterpolation,
                input: ot,
                output: at
            },
            i.samplers.push(ut),
            ct = {
                sampler: i.samplers.length - 1,
                target: {
                    node: pt,
                    path: d
                }
            },
            i.channels.push(ct)
        }
    }
    ,
    a._CreateBakedAnimation = function(e, i, o, s, c, d, _, b, k, j, $, _e) {
        var et, tt = Quaternion.Identity(), rt = null, it, nt = null, ot = null, at = null, st = null, ut = null;
        j.min = Tools.FloatRound(s / d);
        for (var ct = i.getKeys(), lt = 0, ft = ct.length; lt < ft; ++lt) {
            if (ut = null,
            ot = ct[lt],
            lt + 1 < ft)
                if (at = ct[lt + 1],
                ot.value.equals && ot.value.equals(at.value) || ot.value === at.value)
                    if (lt === 0)
                        ut = ot.frame;
                    else
                        continue;
                else
                    ut = at.frame;
            else {
                if (st = ct[lt - 1],
                ot.value.equals && ot.value.equals(st.value) || ot.value === st.value)
                    continue;
                ut = c
            }
            if (ut) {
                for (var ht = ot.frame; ht <= ut; ht += _)
                    if (it = Tools.FloatRound(ht / d),
                    it !== rt) {
                        rt = it,
                        nt = it;
                        var pt = {
                            key: 0,
                            repeatCount: 0,
                            loopMode: i.loopMode
                        };
                        et = i._interpolate(ht, pt),
                        a._SetInterpolatedValue(e, et, it, i, o, tt, b, k, $, _e)
                    }
            }
        }
        nt && (j.max = nt)
    }
    ,
    a._ConvertFactorToVector3OrQuaternion = function(e, i, o, s, c, d, _) {
        var b, k, j = null, $ = a._GetBasePositionRotationOrScale(i, c, d, _);
        if (s === Animation.ANIMATIONTYPE_FLOAT)
            switch (b = o.targetProperty.split("."),
            k = b ? b[1] : "",
            j = _ ? Quaternion.FromArray($).normalize() : Vector3.FromArray($),
            k) {
            case "x":
                {
                    j[k] = d && _ && c !== "scale" ? -e : e;
                    break
                }
            case "y":
                {
                    j[k] = d && _ && c !== "scale" ? -e : e;
                    break
                }
            case "z":
                {
                    j[k] = d && !_ && c !== "scale" ? -e : e;
                    break
                }
            case "w":
                {
                    j.w = e;
                    break
                }
            default:
                Tools.Error('glTFAnimation: Unsupported component type "' + k + '" for scale animation!')
            }
        return j
    }
    ,
    a._SetInterpolatedValue = function(e, i, o, s, c, d, _, b, k, j) {
        var $ = s.dataType, _e;
        _.push(o),
        typeof i == "number" && e instanceof TransformNode && (i = this._ConvertFactorToVector3OrQuaternion(i, e, s, $, c, k, j)),
        i && (c === "rotation" ? (j ? d = i : (_e = i,
        Quaternion.RotationYawPitchRollToRef(_e.y, _e.x, _e.z, d)),
        k && (_GLTFUtilities._GetRightHandedQuaternionFromRef(d),
        e.parent || (d = Quaternion.FromArray([0, 1, 0, 0]).multiply(d))),
        b.push(d.asArray())) : c === "weights" ? b.push([i]) : (_e = i,
        k && c !== "scale" && (_GLTFUtilities._GetRightHandedPositionVector3FromRef(_e),
        e.parent || (_e.x *= -1,
        _e.z *= -1)),
        b.push(_e.asArray())))
    }
    ,
    a._CreateLinearOrStepAnimation = function(e, i, o, s, c, d, _, b) {
        for (var k = 0, j = i.getKeys(); k < j.length; k++) {
            var $ = j[k];
            c.push($.frame / i.framePerSecond),
            a._AddKeyframeValue($, i, d, o, e, _, b)
        }
    }
    ,
    a._CreateCubicSplineAnimation = function(e, i, o, s, c, d, _, b) {
        i.getKeys().forEach(function(k) {
            c.push(k.frame / i.framePerSecond),
            a.AddSplineTangent(e, _TangentType.INTANGENT, d, o, "CUBICSPLINE", k, s, b, _),
            a._AddKeyframeValue(k, i, d, o, e, _, b),
            a.AddSplineTangent(e, _TangentType.OUTTANGENT, d, o, "CUBICSPLINE", k, s, b, _)
        })
    }
    ,
    a._GetBasePositionRotationOrScale = function(e, i, o, s) {
        var c;
        return i === "rotation" ? s ? e.rotationQuaternion ? (c = e.rotationQuaternion.asArray(),
        o && (_GLTFUtilities._GetRightHandedQuaternionArrayFromRef(c),
        e.parent || (c = Quaternion.FromArray([0, 1, 0, 0]).multiply(Quaternion.FromArray(c)).asArray()))) : c = Quaternion.Identity().asArray() : (c = e.rotation.asArray(),
        _GLTFUtilities._GetRightHandedNormalArray3FromRef(c)) : i === "translation" ? (c = e.position.asArray(),
        o && _GLTFUtilities._GetRightHandedPositionArray3FromRef(c)) : c = e.scaling.asArray(),
        c
    }
    ,
    a._AddKeyframeValue = function(e, i, o, s, c, d, _) {
        var b, k, j = i.dataType;
        if (j === Animation.ANIMATIONTYPE_VECTOR3) {
            if (b = e.value.asArray(),
            s === "rotation") {
                var $ = Vector3.FromArray(b)
                  , _e = Quaternion.RotationYawPitchRoll($.y, $.x, $.z);
                d && (_GLTFUtilities._GetRightHandedQuaternionFromRef(_e),
                c.parent || (_e = Quaternion.FromArray([0, 1, 0, 0]).multiply(_e))),
                b = _e.asArray()
            } else
                s === "translation" && d && (_GLTFUtilities._GetRightHandedNormalArray3FromRef(b),
                c.parent || (b[0] *= -1,
                b[2] *= -1));
            o.push(b)
        } else if (j === Animation.ANIMATIONTYPE_FLOAT) {
            if (s === "weights")
                o.push([e.value]);
            else if (k = this._ConvertFactorToVector3OrQuaternion(e.value, c, i, j, s, d, _),
            k) {
                if (s === "rotation") {
                    var et = _ ? k : Quaternion.RotationYawPitchRoll(k.y, k.x, k.z).normalize();
                    d && (_GLTFUtilities._GetRightHandedQuaternionFromRef(et),
                    c.parent || (et = Quaternion.FromArray([0, 1, 0, 0]).multiply(et))),
                    o.push(et.asArray())
                } else
                    s === "translation" && d && (_GLTFUtilities._GetRightHandedNormalVector3FromRef(k),
                    c.parent || (k.x *= -1,
                    k.z *= -1));
                o.push(k.asArray())
            }
        } else
            j === Animation.ANIMATIONTYPE_QUATERNION ? (b = e.value.normalize().asArray(),
            d && (_GLTFUtilities._GetRightHandedQuaternionArrayFromRef(b),
            c.parent || (b = Quaternion.FromArray([0, 1, 0, 0]).multiply(Quaternion.FromArray(b)).asArray())),
            o.push(b)) : Tools.Error("glTFAnimation: Unsupported key frame values for animation!")
    }
    ,
    a._DeduceInterpolation = function(e, i, o) {
        var s, c = !1, d;
        if (i === "rotation" && !o)
            return {
                interpolationType: "LINEAR",
                shouldBakeAnimation: !0
            };
        for (var _ = 0, b = e.length; _ < b; ++_)
            if (d = e[_],
            d.inTangent || d.outTangent)
                if (s) {
                    if (s !== "CUBICSPLINE") {
                        s = "LINEAR",
                        c = !0;
                        break
                    }
                } else
                    s = "CUBICSPLINE";
            else if (s) {
                if (s === "CUBICSPLINE" || d.interpolation && d.interpolation === AnimationKeyInterpolation.STEP && s !== "STEP") {
                    s = "LINEAR",
                    c = !0;
                    break
                }
            } else
                d.interpolation && d.interpolation === AnimationKeyInterpolation.STEP ? s = "STEP" : s = "LINEAR";
        return s || (s = "LINEAR"),
        {
            interpolationType: s,
            shouldBakeAnimation: c
        }
    }
    ,
    a.AddSplineTangent = function(e, i, o, s, c, d, _, b, k) {
        var j, $ = i === _TangentType.INTANGENT ? d.inTangent : d.outTangent;
        if (c === "CUBICSPLINE") {
            if (s === "rotation")
                if ($) {
                    if (b)
                        j = $.asArray();
                    else {
                        var _e = $;
                        j = Quaternion.RotationYawPitchRoll(_e.y, _e.x, _e.z).asArray()
                    }
                    k && (_GLTFUtilities._GetRightHandedQuaternionArrayFromRef(j),
                    e.parent || (j = Quaternion.FromArray([0, 1, 0, 0]).multiply(Quaternion.FromArray(j)).asArray()))
                } else
                    j = [0, 0, 0, 0];
            else
                s === "weights" ? $ ? j = [$] : j = [0] : $ ? (j = $.asArray(),
                k && s === "translation" && (_GLTFUtilities._GetRightHandedPositionArray3FromRef(j),
                e.parent || (j[0] *= -1,
                j[2] *= -1))) : j = [0, 0, 0];
            o.push(j)
        }
    }
    ,
    a.calculateMinMaxKeyFrames = function(e) {
        var i = 1 / 0
          , o = -1 / 0;
        return e.forEach(function(s) {
            i = Math.min(i, s.frame),
            o = Math.max(o, s.frame)
        }),
        {
            min: i,
            max: o
        }
    }
    ,
    a
}()
  , GLTFData = function() {
    function a() {
        this.glTFFiles = {}
    }
    return a.prototype.downloadFiles = function() {
        function e(d, _) {
            return d.indexOf(_, d.length - _.length) !== -1
        }
        for (var i in this.glTFFiles) {
            var o = document.createElement("a");
            document.body.appendChild(o),
            o.setAttribute("type", "hidden"),
            o.download = i;
            var s = this.glTFFiles[i]
              , c = void 0;
            e(i, ".glb") ? c = {
                type: "model/gltf-binary"
            } : e(i, ".bin") ? c = {
                type: "application/octet-stream"
            } : e(i, ".gltf") ? c = {
                type: "model/gltf+json"
            } : e(i, ".jpeg") || e(i, ".jpg") ? c = {
                type: "image/jpeg"
            } : e(i, ".png") && (c = {
                type: "image/png"
            }),
            o.href = window.URL.createObjectURL(new Blob([s],c)),
            o.click()
        }
    }
    ,
    a
}()
  , _GLTFMaterialExporter = function() {
    function a(e) {
        this._textureMap = {},
        this._textureMap = {},
        this._exporter = e
    }
    return a.FuzzyEquals = function(e, i, o) {
        return Scalar.WithinEpsilon(e.r, i.r, o) && Scalar.WithinEpsilon(e.g, i.g, o) && Scalar.WithinEpsilon(e.b, i.b, o)
    }
    ,
    a.prototype._convertMaterialsToGLTFAsync = function(e, i, o) {
        for (var s = [], c = 0, d = e; c < d.length; c++) {
            var _ = d[c];
            _.getClassName() === "StandardMaterial" ? s.push(this._convertStandardMaterialAsync(_, i, o)) : _.getClassName().indexOf("PBR") !== -1 ? s.push(this._convertPBRMaterialAsync(_, i, o)) : Tools.Warn("Unsupported material type: " + _.name)
        }
        return Promise.all(s).then(function() {})
    }
    ,
    a.prototype._stripTexturesFromMaterial = function(e) {
        var i = {};
        if (e) {
            i.name = e.name,
            i.doubleSided = e.doubleSided,
            i.alphaMode = e.alphaMode,
            i.alphaCutoff = e.alphaCutoff,
            i.emissiveFactor = e.emissiveFactor;
            var o = e.pbrMetallicRoughness;
            o && (i.pbrMetallicRoughness = {},
            i.pbrMetallicRoughness.baseColorFactor = o.baseColorFactor,
            i.pbrMetallicRoughness.metallicFactor = o.metallicFactor,
            i.pbrMetallicRoughness.roughnessFactor = o.roughnessFactor)
        }
        return i
    }
    ,
    a.prototype._hasTexturesPresent = function(e) {
        var i;
        if (e.emissiveTexture || e.normalTexture || e.occlusionTexture)
            return !0;
        var o = e.pbrMetallicRoughness;
        if (o && (o.baseColorTexture || o.metallicRoughnessTexture))
            return !0;
        if (e.extensions)
            for (var s in e.extensions) {
                var c = e.extensions[s];
                if (c)
                    return (i = c.hasTextures) === null || i === void 0 ? void 0 : i.call(c)
            }
        return !1
    }
    ,
    a.prototype._getTextureInfo = function(e) {
        if (e) {
            var i = e.uid;
            if (i in this._textureMap)
                return this._textureMap[i]
        }
        return null
    }
    ,
    a.prototype._convertToGLTFPBRMetallicRoughness = function(e) {
        var i = new Vector2(0,1)
          , o = new Vector2(0,.1)
          , s = new Vector2(0,.1)
          , c = new Vector2(1300,.1);
        function d(et, tt, rt, it, nt) {
            return (1 - et) * (1 - et) * (1 - et) * tt + 3 * (1 - et) * (1 - et) * et * rt + 3 * (1 - et) * et * et * it + et * et * et * nt
        }
        function _(et) {
            var tt = Math.pow(et / c.x, .333333);
            return d(tt, i.y, o.y, s.y, c.y)
        }
        var b = e.diffuseColor.toLinearSpace().scale(.5)
          , k = e.alpha
          , j = Scalar.Clamp(e.specularPower, 0, a._MaxSpecularPower)
          , $ = _(j)
          , _e = {
            baseColorFactor: [b.r, b.g, b.b, k],
            metallicFactor: 0,
            roughnessFactor: $
        };
        return _e
    }
    ,
    a._SolveMetallic = function(e, i, o) {
        if (i < this._DielectricSpecular.r)
            return this._DielectricSpecular,
            0;
        var s = this._DielectricSpecular.r
          , c = e * o / (1 - this._DielectricSpecular.r) + i - 2 * this._DielectricSpecular.r
          , d = this._DielectricSpecular.r - i
          , _ = c * c - 4 * s * d;
        return Scalar.Clamp((-c + Math.sqrt(_)) / (2 * s), 0, 1)
    }
    ,
    a._SetAlphaMode = function(e, i) {
        i.needAlphaBlending() ? e.alphaMode = "BLEND" : i.needAlphaTesting() && (e.alphaMode = "MASK",
        e.alphaCutoff = i.alphaCutOff)
    }
    ,
    a.prototype._convertStandardMaterialAsync = function(e, i, o) {
        var s = this._exporter._materialMap
          , c = this._exporter._materials
          , d = []
          , _ = this._convertToGLTFPBRMetallicRoughness(e)
          , b = {
            name: e.name
        };
        return e.backFaceCulling != null && !e.backFaceCulling && (e.twoSidedLighting || Tools.Warn(e.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF."),
        b.doubleSided = !0),
        o && (e.diffuseTexture && d.push(this._exportTextureAsync(e.diffuseTexture, i).then(function(k) {
            k && (_.baseColorTexture = k)
        })),
        e.bumpTexture && d.push(this._exportTextureAsync(e.bumpTexture, i).then(function(k) {
            k && (b.normalTexture = k,
            e.bumpTexture != null && e.bumpTexture.level !== 1 && (b.normalTexture.scale = e.bumpTexture.level))
        })),
        e.emissiveTexture && (b.emissiveFactor = [1, 1, 1],
        d.push(this._exportTextureAsync(e.emissiveTexture, i).then(function(k) {
            k && (b.emissiveTexture = k)
        }))),
        e.ambientTexture && d.push(this._exportTextureAsync(e.ambientTexture, i).then(function(k) {
            if (k) {
                var j = {
                    index: k.index
                };
                b.occlusionTexture = j,
                j.strength = 1
            }
        }))),
        (e.alpha < 1 || e.opacityTexture) && (e.alphaMode === Constants.ALPHA_COMBINE ? b.alphaMode = "BLEND" : Tools.Warn(e.name + ": glTF 2.0 does not support alpha mode: " + e.alphaMode.toString())),
        e.emissiveColor && !a.FuzzyEquals(e.emissiveColor, Color3.Black(), a._Epsilon) && (b.emissiveFactor = e.emissiveColor.asArray()),
        b.pbrMetallicRoughness = _,
        a._SetAlphaMode(b, e),
        c.push(b),
        s[e.uniqueId] = c.length - 1,
        this._finishMaterial(d, b, e, i)
    }
    ,
    a.prototype._finishMaterial = function(e, i, o, s) {
        var c = this;
        return Promise.all(e).then(function() {
            for (var d = c._exporter._extensionsPostExportMaterialAdditionalTextures("exportMaterial", i, o), _ = null, b = 0, k = d; b < k.length; b++) {
                var j = k[b];
                _ || (_ = []),
                _.push(c._exportTextureAsync(j, s))
            }
            return _ || (_ = [Promise.resolve(null)]),
            Promise.all(_).then(function() {
                var $ = c._exporter._extensionsPostExportMaterialAsync("exportMaterial", i, o);
                return $ ? $.then(function() {
                    return i
                }) : i
            })
        })
    }
    ,
    a.prototype._convertPBRMetallicRoughnessMaterialAsync = function(e, i, o) {
        var s = this._exporter._materialMap
          , c = this._exporter._materials
          , d = []
          , _ = {};
        e.baseColor && (_.baseColorFactor = [e.baseColor.r, e.baseColor.g, e.baseColor.b, e.alpha]),
        e.metallic != null && e.metallic !== 1 && (_.metallicFactor = e.metallic),
        e.roughness != null && e.roughness !== 1 && (_.roughnessFactor = e.roughness);
        var b = {
            name: e.name
        };
        return e.doubleSided && (b.doubleSided = e.doubleSided),
        a._SetAlphaMode(b, e),
        o && (e.baseTexture != null && d.push(this._exportTextureAsync(e.baseTexture, i).then(function(k) {
            k && (_.baseColorTexture = k)
        })),
        e.normalTexture && d.push(this._exportTextureAsync(e.normalTexture, i).then(function(k) {
            k && (b.normalTexture = k,
            e.normalTexture.level !== 1 && (b.normalTexture.scale = e.normalTexture.level))
        })),
        e.occlusionTexture && d.push(this._exportTextureAsync(e.occlusionTexture, i).then(function(k) {
            k && (b.occlusionTexture = k,
            e.occlusionStrength != null && (b.occlusionTexture.strength = e.occlusionStrength))
        })),
        e.emissiveTexture && d.push(this._exportTextureAsync(e.emissiveTexture, i).then(function(k) {
            k && (b.emissiveTexture = k)
        }))),
        a.FuzzyEquals(e.emissiveColor, Color3.Black(), a._Epsilon) && (b.emissiveFactor = e.emissiveColor.asArray()),
        b.pbrMetallicRoughness = _,
        c.push(b),
        s[e.uniqueId] = c.length - 1,
        this._finishMaterial(d, b, e, i)
    }
    ,
    a.prototype._createBase64FromCanvasAsync = function(e, i, o, s) {
        var c = this;
        return new Promise(function(d, _) {
            return __awaiter(c, void 0, void 0, function() {
                var b, k, j, $, _e, et;
                return __generator(this, function(tt) {
                    switch (tt.label) {
                    case 0:
                        return b = Constants.TEXTURETYPE_UNSIGNED_INT,
                        k = this._exporter._babylonScene,
                        j = k.getEngine(),
                        $ = j.createRawTexture(e, i, o, Constants.TEXTUREFORMAT_RGBA, !1, !0, Texture.NEAREST_SAMPLINGMODE, null, b),
                        [4, TextureTools.ApplyPostProcess("pass", $, k, b, Constants.TEXTURE_NEAREST_SAMPLINGMODE, Constants.TEXTUREFORMAT_RGBA)];
                    case 1:
                        return tt.sent(),
                        [4, j._readTexturePixels($, i, o)];
                    case 2:
                        return _e = tt.sent(),
                        [4, Tools.DumpDataAsync(i, o, _e, s, void 0, !0, !1)];
                    case 3:
                        return et = tt.sent(),
                        d(et),
                        [2]
                    }
                })
            })
        }
        )
    }
    ,
    a.prototype._createWhiteTexture = function(e, i, o) {
        for (var s = new Uint8Array(e * i * 4), c = 0; c < s.length; c = c + 4)
            s[c] = s[c + 1] = s[c + 2] = s[c + 3] = 255;
        var d = RawTexture.CreateRGBATexture(s, e, i, o);
        return d
    }
    ,
    a.prototype._resizeTexturesToSameDimensions = function(e, i, o) {
        var s = e ? e.getSize() : {
            width: 0,
            height: 0
        }, c = i ? i.getSize() : {
            width: 0,
            height: 0
        }, d, _;
        return s.width < c.width ? (e && e instanceof Texture ? d = TextureTools.CreateResizedCopy(e, c.width, c.height, !0) : d = this._createWhiteTexture(c.width, c.height, o),
        _ = i) : s.width > c.width ? (i && i instanceof Texture ? _ = TextureTools.CreateResizedCopy(i, s.width, s.height, !0) : _ = this._createWhiteTexture(s.width, s.height, o),
        d = e) : (d = e,
        _ = i),
        {
            texture1: d,
            texture2: _
        }
    }
    ,
    a.prototype._convertPixelArrayToFloat32 = function(e) {
        if (e instanceof Uint8Array) {
            for (var i = e.length, o = new Float32Array(e.length), s = 0; s < i; ++s)
                o[s] = e[s] / 255;
            return o
        } else {
            if (e instanceof Float32Array)
                return e;
            throw new Error("Unsupported pixel format!")
        }
    }
    ,
    a.prototype._convertSpecularGlossinessTexturesToMetallicRoughnessAsync = function(e, i, o, s) {
        var c;
        return __awaiter(this, void 0, void 0, function() {
            var d, _, b, k, j, $, _e, et, tt, rt, it, nt, ot, at, st, ut, ct, Et, At, lt, ft, ht, pt, dt, _t, mt, vt, yt, Et, At, gt, St, xt, bt, Rt, Rt;
            return __generator(this, function(Mt) {
                switch (Mt.label) {
                case 0:
                    return d = [],
                    e || i ? (_ = e ? e.getScene() : i ? i.getScene() : null,
                    _ ? (b = this._resizeTexturesToSameDimensions(e, i, _),
                    k = (c = b.texture1) === null || c === void 0 ? void 0 : c.getSize(),
                    j = void 0,
                    $ = void 0,
                    _e = k.width,
                    et = k.height,
                    [4, b.texture1.readPixels()]) : [3, 3]) : [2, Promise.reject("_ConvertSpecularGlosinessTexturesToMetallicRoughness: diffuse and specular glossiness textures are not defined!")];
                case 1:
                    return tt = Mt.sent(),
                    [4, b.texture2.readPixels()];
                case 2:
                    if (rt = Mt.sent(),
                    tt)
                        j = this._convertPixelArrayToFloat32(tt);
                    else
                        return [2, Promise.reject("Failed to retrieve pixels from diffuse texture!")];
                    if (rt)
                        $ = this._convertPixelArrayToFloat32(rt);
                    else
                        return [2, Promise.reject("Failed to retrieve pixels from specular glossiness texture!")];
                    for (it = $.byteLength,
                    nt = new Uint8Array(it),
                    ot = new Uint8Array(it),
                    at = 4,
                    st = Color3.Black(),
                    ut = 0,
                    ct = 0,
                    Et = 0; Et < et; ++Et)
                        for (At = 0; At < _e; ++At)
                            lt = (_e * Et + At) * at,
                            ft = new Color3(j[lt],j[lt + 1],j[lt + 2]).toLinearSpace().multiply(o.diffuseColor),
                            ht = new Color3($[lt],$[lt + 1],$[lt + 2]).toLinearSpace().multiply(o.specularColor),
                            pt = $[lt + 3] * o.glossiness,
                            dt = {
                                diffuseColor: ft,
                                specularColor: ht,
                                glossiness: pt
                            },
                            _t = this._convertSpecularGlossinessToMetallicRoughness(dt),
                            st.r = Math.max(st.r, _t.baseColor.r),
                            st.g = Math.max(st.g, _t.baseColor.g),
                            st.b = Math.max(st.b, _t.baseColor.b),
                            ut = Math.max(ut, _t.metallic),
                            ct = Math.max(ct, _t.roughness),
                            ot[lt] = _t.baseColor.r * 255,
                            ot[lt + 1] = _t.baseColor.g * 255,
                            ot[lt + 2] = _t.baseColor.b * 255,
                            ot[lt + 3] = b.texture1.hasAlpha ? j[lt + 3] * 255 : 255,
                            nt[lt] = 0,
                            nt[lt + 1] = _t.roughness * 255,
                            nt[lt + 2] = _t.metallic * 255,
                            nt[lt + 3] = 255;
                    for (mt = {
                        baseColor: st,
                        metallic: ut,
                        roughness: ct
                    },
                    vt = !1,
                    yt = !1,
                    Et = 0; Et < et; ++Et)
                        for (At = 0; At < _e; ++At)
                            gt = (_e * Et + At) * at,
                            ot[gt] /= mt.baseColor.r > a._Epsilon ? mt.baseColor.r : 1,
                            ot[gt + 1] /= mt.baseColor.g > a._Epsilon ? mt.baseColor.g : 1,
                            ot[gt + 2] /= mt.baseColor.b > a._Epsilon ? mt.baseColor.b : 1,
                            St = Color3.FromInts(ot[gt], ot[gt + 1], ot[gt + 2]),
                            xt = St.toGammaSpace(),
                            ot[gt] = xt.r * 255,
                            ot[gt + 1] = xt.g * 255,
                            ot[gt + 2] = xt.b * 255,
                            a.FuzzyEquals(xt, Color3.White(), a._Epsilon) || (yt = !0),
                            nt[gt + 1] /= mt.roughness > a._Epsilon ? mt.roughness : 1,
                            nt[gt + 2] /= mt.metallic > a._Epsilon ? mt.metallic : 1,
                            bt = Color3.FromInts(255, nt[gt + 1], nt[gt + 2]),
                            a.FuzzyEquals(bt, Color3.White(), a._Epsilon) || (vt = !0);
                    return vt && (Rt = this._createBase64FromCanvasAsync(nt, _e, et, s).then(function(Pt) {
                        mt.metallicRoughnessTextureBase64 = Pt
                    }),
                    d.push(Rt)),
                    yt && (Rt = this._createBase64FromCanvasAsync(ot, _e, et, s).then(function(Pt) {
                        mt.baseColorTextureBase64 = Pt
                    }),
                    d.push(Rt)),
                    [2, Promise.all(d).then(function() {
                        return mt
                    })];
                case 3:
                    return [2, Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!")]
                }
            })
        })
    }
    ,
    a.prototype._convertSpecularGlossinessToMetallicRoughness = function(e) {
        var i = this._getPerceivedBrightness(e.diffuseColor)
          , o = this._getPerceivedBrightness(e.specularColor)
          , s = 1 - this._getMaxComponent(e.specularColor)
          , c = a._SolveMetallic(i, o, s)
          , d = e.diffuseColor.scale(s / (1 - a._DielectricSpecular.r) / Math.max(1 - c, a._Epsilon))
          , _ = e.specularColor.subtract(a._DielectricSpecular.scale(1 - c)).scale(1 / Math.max(c, a._Epsilon))
          , b = Color3.Lerp(d, _, c * c);
        b = b.clampToRef(0, 1, b);
        var k = {
            baseColor: b,
            metallic: c,
            roughness: 1 - e.glossiness
        };
        return k
    }
    ,
    a.prototype._getPerceivedBrightness = function(e) {
        return e ? Math.sqrt(.299 * e.r * e.r + .587 * e.g * e.g + .114 * e.b * e.b) : 0
    }
    ,
    a.prototype._getMaxComponent = function(e) {
        return e ? Math.max(e.r, Math.max(e.g, e.b)) : 0
    }
    ,
    a.prototype._convertMetalRoughFactorsToMetallicRoughnessAsync = function(e, i, o, s) {
        var c = []
          , d = e._albedoColor
          , _ = e._metallic
          , b = e._roughness
          , k = {
            baseColor: d,
            metallic: _,
            roughness: b
        };
        if (s) {
            var j = e._albedoTexture;
            j && c.push(this._exportTextureAsync(e._albedoTexture, i).then(function(_e) {
                _e && (o.baseColorTexture = _e)
            }));
            var $ = e._metallicTexture;
            $ && c.push(this._exportTextureAsync($, i).then(function(_e) {
                _e && (o.metallicRoughnessTexture = _e)
            }))
        }
        return Promise.all(c).then(function() {
            return k
        })
    }
    ,
    a.prototype._getGLTFTextureSampler = function(e) {
        var i = this._getGLTFTextureWrapModesSampler(e)
          , o = e instanceof Texture ? e.samplingMode : null;
        if (o != null)
            switch (o) {
            case Texture.LINEAR_LINEAR:
                {
                    i.magFilter = 9729,
                    i.minFilter = 9729;
                    break
                }
            case Texture.LINEAR_NEAREST:
                {
                    i.magFilter = 9729,
                    i.minFilter = 9728;
                    break
                }
            case Texture.NEAREST_LINEAR:
                {
                    i.magFilter = 9728,
                    i.minFilter = 9729;
                    break
                }
            case Texture.NEAREST_LINEAR_MIPLINEAR:
                {
                    i.magFilter = 9728,
                    i.minFilter = 9987;
                    break
                }
            case Texture.NEAREST_NEAREST:
                {
                    i.magFilter = 9728,
                    i.minFilter = 9728;
                    break
                }
            case Texture.NEAREST_LINEAR_MIPNEAREST:
                {
                    i.magFilter = 9728,
                    i.minFilter = 9985;
                    break
                }
            case Texture.LINEAR_NEAREST_MIPNEAREST:
                {
                    i.magFilter = 9729,
                    i.minFilter = 9984;
                    break
                }
            case Texture.LINEAR_NEAREST_MIPLINEAR:
                {
                    i.magFilter = 9729,
                    i.minFilter = 9986;
                    break
                }
            case Texture.NEAREST_NEAREST_MIPLINEAR:
                {
                    i.magFilter = 9728,
                    i.minFilter = 9986;
                    break
                }
            case Texture.LINEAR_LINEAR_MIPLINEAR:
                {
                    i.magFilter = 9729,
                    i.minFilter = 9987;
                    break
                }
            case Texture.LINEAR_LINEAR_MIPNEAREST:
                {
                    i.magFilter = 9729,
                    i.minFilter = 9985;
                    break
                }
            case Texture.NEAREST_NEAREST_MIPNEAREST:
                {
                    i.magFilter = 9728,
                    i.minFilter = 9984;
                    break
                }
            }
        return i
    }
    ,
    a.prototype._getGLTFTextureWrapMode = function(e) {
        switch (e) {
        case Texture.WRAP_ADDRESSMODE:
            return 10497;
        case Texture.CLAMP_ADDRESSMODE:
            return 33071;
        case Texture.MIRROR_ADDRESSMODE:
            return 33648;
        default:
            return Tools.Error("Unsupported Texture Wrap Mode " + e + "!"),
            10497
        }
    }
    ,
    a.prototype._getGLTFTextureWrapModesSampler = function(e) {
        var i = this._getGLTFTextureWrapMode(e instanceof Texture ? e.wrapU : Texture.WRAP_ADDRESSMODE)
          , o = this._getGLTFTextureWrapMode(e instanceof Texture ? e.wrapV : Texture.WRAP_ADDRESSMODE);
        return i === 10497 && o === 10497 ? {} : {
            wrapS: i,
            wrapT: o
        }
    }
    ,
    a.prototype._convertSpecGlossFactorsToMetallicRoughnessAsync = function(e, i, o, s) {
        var c = this;
        return Promise.resolve().then(function() {
            var d = c._exporter._samplers
              , _ = c._exporter._textures
              , b = e._albedoColor
              , k = e._reflectivityColor
              , j = e._microSurface
              , $ = {
                diffuseColor: b,
                specularColor: k,
                glossiness: j
            }
              , _e = null
              , et = e._albedoTexture
              , tt = e._reflectivityTexture;
            if (et) {
                var rt = c._getGLTFTextureSampler(et);
                rt.magFilter != null && rt.minFilter != null && rt.wrapS != null && rt.wrapT != null && (d.push(rt),
                _e = d.length - 1)
            }
            var it = e._useMicroSurfaceFromReflectivityMapAlpha;
            return tt && !it ? Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported") : (et || tt) && s ? c._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(et, tt, $, i).then(function(nt) {
                if (nt.baseColorTextureBase64) {
                    var ot = c._getTextureInfoFromBase64(nt.baseColorTextureBase64, "bjsBaseColorTexture_" + _.length + ".png", i, et ? et.coordinatesIndex : null, _e);
                    ot && (o.baseColorTexture = ot)
                }
                if (nt.metallicRoughnessTextureBase64) {
                    var at = c._getTextureInfoFromBase64(nt.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + _.length + ".png", i, tt ? tt.coordinatesIndex : null, _e);
                    at && (o.metallicRoughnessTexture = at)
                }
                return nt
            }) : c._convertSpecularGlossinessToMetallicRoughness($)
        })
    }
    ,
    a.prototype._convertPBRMaterialAsync = function(e, i, o) {
        var s = this
          , c = {}
          , d = {
            name: e.name
        }
          , _ = e.isMetallicWorkflow();
        if (_) {
            var b = e._albedoColor
              , k = e.alpha;
            return b && (c.baseColorFactor = [b.r, b.g, b.b, k]),
            this._convertMetalRoughFactorsToMetallicRoughnessAsync(e, i, c, o).then(function(j) {
                return s.setMetallicRoughnessPbrMaterial(j, e, d, c, i, o)
            })
        } else
            return this._convertSpecGlossFactorsToMetallicRoughnessAsync(e, i, c, o).then(function(j) {
                return s.setMetallicRoughnessPbrMaterial(j, e, d, c, i, o)
            })
    }
    ,
    a.prototype.setMetallicRoughnessPbrMaterial = function(e, i, o, s, c, d) {
        var _ = this._exporter._materialMap
          , b = this._exporter._materials
          , k = [];
        if (e) {
            if (a._SetAlphaMode(o, i),
            a.FuzzyEquals(e.baseColor, Color3.White(), a._Epsilon) && i.alpha >= a._Epsilon || (s.baseColorFactor = [e.baseColor.r, e.baseColor.g, e.baseColor.b, i.alpha]),
            e.metallic != null && e.metallic !== 1 && (s.metallicFactor = e.metallic),
            e.roughness != null && e.roughness !== 1 && (s.roughnessFactor = e.roughness),
            i.backFaceCulling != null && !i.backFaceCulling && (i._twoSidedLighting || Tools.Warn(i.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF."),
            o.doubleSided = !0),
            d) {
                var j = i._bumpTexture;
                if (j) {
                    var $ = this._exportTextureAsync(j, c).then(function(rt) {
                        rt && (o.normalTexture = rt,
                        j.level !== 1 && (o.normalTexture.scale = j.level))
                    });
                    k.push($)
                }
                var _e = i._ambientTexture;
                if (_e) {
                    var $ = this._exportTextureAsync(_e, c).then(function(it) {
                        if (it) {
                            var nt = {
                                index: it.index,
                                texCoord: it.texCoord
                            };
                            o.occlusionTexture = nt;
                            var ot = i._ambientTextureStrength;
                            ot && (nt.strength = ot)
                        }
                    });
                    k.push($)
                }
                var et = i._emissiveTexture;
                if (et) {
                    var $ = this._exportTextureAsync(et, c).then(function(it) {
                        it && (o.emissiveTexture = it)
                    });
                    k.push($)
                }
            }
            var tt = i._emissiveColor;
            a.FuzzyEquals(tt, Color3.Black(), a._Epsilon) || (o.emissiveFactor = tt.asArray()),
            o.pbrMetallicRoughness = s,
            b.push(o),
            _[i.uniqueId] = b.length - 1
        }
        return this._finishMaterial(k, o, i, c)
    }
    ,
    a.prototype.getPixelsFromTexture = function(e) {
        var i = (e.textureType === Constants.TEXTURETYPE_UNSIGNED_INT,
        e.readPixels());
        return i
    }
    ,
    a.prototype._exportTextureAsync = function(e, i) {
        var o = this
          , s = this._exporter._extensionsPreExportTextureAsync("exporter", e, i);
        return s ? s.then(function(c) {
            return c ? o._exportTextureInfoAsync(c, i) : o._exportTextureInfoAsync(e, i)
        }) : this._exportTextureInfoAsync(e, i)
    }
    ,
    a.prototype._exportTextureInfoAsync = function(e, i) {
        var o = this;
        return Promise.resolve().then(function() {
            return __awaiter(o, void 0, void 0, function() {
                var s, c, d, _, b, k, j, $, _e, et = this;
                return __generator(this, function(tt) {
                    switch (tt.label) {
                    case 0:
                        return s = e.uid,
                        s in this._textureMap ? [2, this._textureMap[s]] : [3, 1];
                    case 1:
                        return [4, this.getPixelsFromTexture(e)];
                    case 2:
                        if (c = tt.sent(),
                        !c)
                            return [2, null];
                        for (d = this._exporter._samplers,
                        _ = this._getGLTFTextureSampler(e),
                        b = null,
                        k = null,
                        j = 0; j < d.length; ++j)
                            if ($ = d[j],
                            $.minFilter === _.minFilter && $.magFilter === _.magFilter && $.wrapS === _.wrapS && $.wrapT === _.wrapT) {
                                k = j;
                                break
                            }
                        if (k == null ? (d.push(_),
                        b = d.length - 1) : b = k,
                        _e = e.getSize(),
                        e.mimeType)
                            switch (e.mimeType) {
                            case "image/jpeg":
                                i = "image/jpeg";
                                break;
                            case "image/png":
                                i = "image/png";
                                break
                            }
                        return [2, this._createBase64FromCanvasAsync(c, _e.width, _e.height, i).then(function(rt) {
                            var it = et._getTextureInfoFromBase64(rt, e.name.replace(/\.\/|\/|\.\\|\\/g, "_"), i, e.coordinatesIndex, b);
                            return it && (et._textureMap[s] = it,
                            et._exporter._extensionsPostExportTextures("linkTextureInfo", it, e)),
                            it
                        })]
                    }
                })
            })
        })
    }
    ,
    a.prototype._getTextureInfoFromBase64 = function(e, i, o, s, c) {
        var d = this._exporter._textures
          , _ = this._exporter._images
          , b = this._exporter._imageData
          , k = null
          , j = {
            source: _.length,
            name: i
        };
        c != null && (j.sampler = c);
        for (var $ = atob(e.split(",")[1]), _e = new ArrayBuffer($.length), et = new Uint8Array(_e), tt = 0, rt = $.length; tt < rt; ++tt)
            et[tt] = $.charCodeAt(tt);
        var it = {
            data: et,
            mimeType: o
        }
          , nt = o === "image/jpeg" ? ".jpeg" : ".png"
          , ot = i + nt
          , at = ot;
        if (ot in b && (ot = i + "_" + Tools.RandomId() + nt),
        b[ot] = it,
        o === "image/jpeg" || o === "image/png") {
            for (var st = {
                name: i,
                uri: ot
            }, ut = null, tt = 0; tt < _.length; ++tt)
                if (_[tt].uri === at) {
                    ut = tt;
                    break
                }
            ut == null ? (_.push(st),
            j.source = _.length - 1) : j.source = ut,
            d.push(j),
            k = {
                index: d.length - 1
            },
            s != null && (k.texCoord = s)
        } else
            Tools.Error("Unsupported texture mime type " + o);
        return k
    }
    ,
    a._DielectricSpecular = new Color3(.04,.04,.04),
    a._MaxSpecularPower = 1024,
    a._Epsilon = 1e-6,
    a
}()
  , _Exporter = function() {
    function a(e, i) {
        this._includeCoordinateSystemConversionNodes = !1,
        this._extensions = {},
        this._glTF = {
            asset: {
                generator: "BabylonJS",
                version: "2.0"
            }
        },
        this._babylonScene = e,
        this._bufferViews = [],
        this._accessors = [],
        this._meshes = [],
        this._scenes = [],
        this._nodes = [],
        this._images = [],
        this._materials = [],
        this._materialMap = [],
        this._textures = [],
        this._samplers = [],
        this._skins = [],
        this._animations = [],
        this._imageData = {},
        this._orderedImageData = [],
        this._options = i || {},
        this._animationSampleRate = i && i.animationSampleRate ? i.animationSampleRate : 1 / 60,
        this._includeCoordinateSystemConversionNodes = !!(i && i.includeCoordinateSystemConversionNodes),
        this._glTFMaterialExporter = new _GLTFMaterialExporter(this),
        this._loadExtensions()
    }
    return a.prototype._applyExtension = function(e, i, o, s) {
        var c = this;
        if (o >= i.length)
            return Promise.resolve(e);
        var d = s(i[o], e);
        return d ? d.then(function(_) {
            return c._applyExtension(_, i, o + 1, s)
        }) : this._applyExtension(e, i, o + 1, s)
    }
    ,
    a.prototype._applyExtensions = function(e, i) {
        for (var o = [], s = 0, c = a._ExtensionNames; s < c.length; s++) {
            var d = c[s];
            o.push(this._extensions[d])
        }
        return this._applyExtension(e, o, 0, i)
    }
    ,
    a.prototype._extensionsPreExportTextureAsync = function(e, i, o) {
        return this._applyExtensions(i, function(s, c) {
            return s.preExportTextureAsync && s.preExportTextureAsync(e, c, o)
        })
    }
    ,
    a.prototype._extensionsPostExportMeshPrimitiveAsync = function(e, i, o, s) {
        return this._applyExtensions(i, function(c, d) {
            return c.postExportMeshPrimitiveAsync && c.postExportMeshPrimitiveAsync(e, d, o, s)
        })
    }
    ,
    a.prototype._extensionsPostExportNodeAsync = function(e, i, o, s) {
        return this._applyExtensions(i, function(c, d) {
            return c.postExportNodeAsync && c.postExportNodeAsync(e, d, o, s)
        })
    }
    ,
    a.prototype._extensionsPostExportMaterialAsync = function(e, i, o) {
        return this._applyExtensions(i, function(s, c) {
            return s.postExportMaterialAsync && s.postExportMaterialAsync(e, c, o)
        })
    }
    ,
    a.prototype._extensionsPostExportMaterialAdditionalTextures = function(e, i, o) {
        for (var s = [], c = 0, d = a._ExtensionNames; c < d.length; c++) {
            var _ = d[c]
              , b = this._extensions[_];
            b.postExportMaterialAdditionalTextures && s.push.apply(s, b.postExportMaterialAdditionalTextures(e, i, o))
        }
        return s
    }
    ,
    a.prototype._extensionsPostExportTextures = function(e, i, o) {
        for (var s = 0, c = a._ExtensionNames; s < c.length; s++) {
            var d = c[s]
              , _ = this._extensions[d];
            _.postExportTexture && _.postExportTexture(e, i, o)
        }
    }
    ,
    a.prototype._forEachExtensions = function(e) {
        for (var i = 0, o = a._ExtensionNames; i < o.length; i++) {
            var s = o[i]
              , c = this._extensions[s];
            c.enabled && e(c)
        }
    }
    ,
    a.prototype._extensionsOnExporting = function() {
        var e = this;
        this._forEachExtensions(function(i) {
            i.wasUsed && (e._glTF.extensionsUsed == null && (e._glTF.extensionsUsed = []),
            e._glTF.extensionsUsed.indexOf(i.name) === -1 && e._glTF.extensionsUsed.push(i.name),
            i.required && (e._glTF.extensionsRequired == null && (e._glTF.extensionsRequired = []),
            e._glTF.extensionsRequired.indexOf(i.name) === -1 && e._glTF.extensionsRequired.push(i.name)),
            e._glTF.extensions == null && (e._glTF.extensions = {}),
            i.onExporting && i.onExporting())
        })
    }
    ,
    a.prototype._loadExtensions = function() {
        for (var e = 0, i = a._ExtensionNames; e < i.length; e++) {
            var o = i[e]
              , s = a._ExtensionFactories[o](this);
            this._extensions[o] = s
        }
    }
    ,
    a.prototype.dispose = function() {
        for (var e in this._extensions) {
            var i = this._extensions[e];
            i.dispose()
        }
    }
    ,
    a.RegisterExtension = function(e, i) {
        a.UnregisterExtension(e) && Tools.Warn("Extension with the name " + e + " already exists"),
        a._ExtensionFactories[e] = i,
        a._ExtensionNames.push(e)
    }
    ,
    a.UnregisterExtension = function(e) {
        if (!a._ExtensionFactories[e])
            return !1;
        delete a._ExtensionFactories[e];
        var i = a._ExtensionNames.indexOf(e);
        return i !== -1 && a._ExtensionNames.splice(i, 1),
        !0
    }
    ,
    a.prototype.reorderIndicesBasedOnPrimitiveMode = function(e, i, o, s, c) {
        switch (i) {
        case Material.TriangleFillMode:
            {
                s || (s = 0);
                for (var d = e.indexStart, _ = e.indexStart + e.indexCount; d < _; d = d + 3) {
                    var b = s + d * 4
                      , k = c.getUInt32(b + 4)
                      , j = c.getUInt32(b + 8);
                    c.setUInt32(j, b + 4),
                    c.setUInt32(k, b + 8)
                }
                break
            }
        case Material.TriangleFanDrawMode:
            {
                for (var d = e.indexStart + e.indexCount - 1, $ = e.indexStart; d >= $; --d)
                    c.setUInt32(o[d], s),
                    s += 4;
                break
            }
        case Material.TriangleStripDrawMode:
            {
                e.indexCount >= 3 && (c.setUInt32(o[e.indexStart + 2], s + 4),
                c.setUInt32(o[e.indexStart + 1], s + 8));
                break
            }
        }
    }
    ,
    a.prototype.reorderVertexAttributeDataBasedOnPrimitiveMode = function(e, i, o, s, c, d, _, b) {
        if (b && o === Material.ClockWiseSideOrientation)
            switch (i) {
            case Material.TriangleFillMode:
                {
                    this.reorderTriangleFillMode(e, i, o, s, c, d, _, b);
                    break
                }
            case Material.TriangleStripDrawMode:
                {
                    this.reorderTriangleStripDrawMode(e, i, o, s, c, d, _, b);
                    break
                }
            case Material.TriangleFanDrawMode:
                {
                    this.reorderTriangleFanMode(e, i, o, s, c, d, _, b);
                    break
                }
            }
    }
    ,
    a.prototype.reorderTriangleFillMode = function(e, i, o, s, c, d, _, b) {
        var k = this.getVertexBufferFromMesh(s, e.getMesh());
        if (k) {
            var j = k.byteStride / VertexBuffer.GetTypeByteLength(k.type);
            if (e.verticesCount % 3 !== 0)
                Tools.Error("The submesh vertices for the triangle fill mode is not divisible by 3!");
            else {
                var $ = []
                  , _e = 0;
                switch (s) {
                case VertexBuffer.PositionKind:
                case VertexBuffer.NormalKind:
                    {
                        for (var et = e.verticesStart; et < e.verticesStart + e.verticesCount; et = et + 3)
                            _e = et * j,
                            $.push(Vector3.FromArray(c, _e)),
                            $.push(Vector3.FromArray(c, _e + 2 * j)),
                            $.push(Vector3.FromArray(c, _e + j));
                        break
                    }
                case VertexBuffer.TangentKind:
                    {
                        for (var et = e.verticesStart; et < e.verticesStart + e.verticesCount; et = et + 3)
                            _e = et * j,
                            $.push(Vector4.FromArray(c, _e)),
                            $.push(Vector4.FromArray(c, _e + 2 * j)),
                            $.push(Vector4.FromArray(c, _e + j));
                        break
                    }
                case VertexBuffer.ColorKind:
                    {
                        for (var tt = k.getSize(), et = e.verticesStart; et < e.verticesStart + e.verticesCount; et = et + tt)
                            _e = et * j,
                            tt === 4 ? ($.push(Vector4.FromArray(c, _e)),
                            $.push(Vector4.FromArray(c, _e + 2 * j)),
                            $.push(Vector4.FromArray(c, _e + j))) : ($.push(Vector3.FromArray(c, _e)),
                            $.push(Vector3.FromArray(c, _e + 2 * j)),
                            $.push(Vector3.FromArray(c, _e + j)));
                        break
                    }
                case VertexBuffer.UVKind:
                case VertexBuffer.UV2Kind:
                    {
                        for (var et = e.verticesStart; et < e.verticesStart + e.verticesCount; et = et + 3)
                            _e = et * j,
                            $.push(Vector2.FromArray(c, _e)),
                            $.push(Vector2.FromArray(c, _e + 2 * j)),
                            $.push(Vector2.FromArray(c, _e + j));
                        break
                    }
                default:
                    Tools.Error("Unsupported Vertex Buffer type: " + s)
                }
                this.writeVertexAttributeData($, d, s, c, _, b)
            }
        } else
            Tools.Warn("reorderTriangleFillMode: Vertex Buffer Kind " + s + " not present!")
    }
    ,
    a.prototype.reorderTriangleStripDrawMode = function(e, i, o, s, c, d, _, b) {
        var k = this.getVertexBufferFromMesh(s, e.getMesh());
        if (k) {
            var j = k.byteStride / VertexBuffer.GetTypeByteLength(k.type)
              , $ = []
              , _e = 0;
            switch (s) {
            case VertexBuffer.PositionKind:
            case VertexBuffer.NormalKind:
                {
                    _e = e.verticesStart,
                    $.push(Vector3.FromArray(c, _e + 2 * j)),
                    $.push(Vector3.FromArray(c, _e + j));
                    break
                }
            case VertexBuffer.TangentKind:
                {
                    for (var et = e.verticesStart + e.verticesCount - 1; et >= e.verticesStart; --et)
                        _e = et * j,
                        $.push(Vector4.FromArray(c, _e));
                    break
                }
            case VertexBuffer.ColorKind:
                {
                    for (var et = e.verticesStart + e.verticesCount - 1; et >= e.verticesStart; --et)
                        _e = et * j,
                        k.getSize() === 4 ? $.push(Vector4.FromArray(c, _e)) : $.push(Vector3.FromArray(c, _e));
                    break
                }
            case VertexBuffer.UVKind:
            case VertexBuffer.UV2Kind:
                {
                    for (var et = e.verticesStart + e.verticesCount - 1; et >= e.verticesStart; --et)
                        _e = et * j,
                        $.push(Vector2.FromArray(c, _e));
                    break
                }
            default:
                Tools.Error("Unsupported Vertex Buffer type: " + s)
            }
            this.writeVertexAttributeData($, d + 12, s, c, _, b)
        } else
            Tools.Warn("reorderTriangleStripDrawMode: Vertex buffer kind " + s + " not present!")
    }
    ,
    a.prototype.reorderTriangleFanMode = function(e, i, o, s, c, d, _, b) {
        var k = this.getVertexBufferFromMesh(s, e.getMesh());
        if (k) {
            var j = k.byteStride / VertexBuffer.GetTypeByteLength(k.type)
              , $ = []
              , _e = 0;
            switch (s) {
            case VertexBuffer.PositionKind:
            case VertexBuffer.NormalKind:
                {
                    for (var et = e.verticesStart + e.verticesCount - 1; et >= e.verticesStart; --et)
                        _e = et * j,
                        $.push(Vector3.FromArray(c, _e));
                    break
                }
            case VertexBuffer.TangentKind:
                {
                    for (var et = e.verticesStart + e.verticesCount - 1; et >= e.verticesStart; --et)
                        _e = et * j,
                        $.push(Vector4.FromArray(c, _e));
                    break
                }
            case VertexBuffer.ColorKind:
                {
                    for (var et = e.verticesStart + e.verticesCount - 1; et >= e.verticesStart; --et)
                        _e = et * j,
                        $.push(Vector4.FromArray(c, _e)),
                        k.getSize() === 4 ? $.push(Vector4.FromArray(c, _e)) : $.push(Vector3.FromArray(c, _e));
                    break
                }
            case VertexBuffer.UVKind:
            case VertexBuffer.UV2Kind:
                {
                    for (var et = e.verticesStart + e.verticesCount - 1; et >= e.verticesStart; --et)
                        _e = et * j,
                        $.push(Vector2.FromArray(c, _e));
                    break
                }
            default:
                Tools.Error("Unsupported Vertex Buffer type: " + s)
            }
            this.writeVertexAttributeData($, d, s, c, _, b)
        } else
            Tools.Warn("reorderTriangleFanMode: Vertex buffer kind " + s + " not present!")
    }
    ,
    a.prototype.writeVertexAttributeData = function(e, i, o, s, c, d) {
        for (var _ = 0, b = e; _ < b.length; _++) {
            var k = b[_];
            d && o !== VertexBuffer.ColorKind && !(k instanceof Vector2) && (k instanceof Vector3 ? o === VertexBuffer.NormalKind ? _GLTFUtilities._GetRightHandedNormalVector3FromRef(k) : o === VertexBuffer.PositionKind ? _GLTFUtilities._GetRightHandedPositionVector3FromRef(k) : Tools.Error("Unsupported vertex attribute kind!") : _GLTFUtilities._GetRightHandedVector4FromRef(k)),
            o === VertexBuffer.NormalKind ? k.normalize() : o === VertexBuffer.TangentKind && k instanceof Vector4 && _GLTFUtilities._NormalizeTangentFromRef(k);
            for (var j = 0, $ = k.asArray(); j < $.length; j++) {
                var _e = $[j];
                c.setFloat32(_e, i),
                i += 4
            }
        }
    }
    ,
    a.prototype.writeAttributeData = function(e, i, o, s, c, d, _) {
        var b = [], k;
        switch (e) {
        case VertexBuffer.PositionKind:
            {
                for (var j = 0, $ = o.length / s; j < $; ++j) {
                    k = j * s;
                    var _e = Vector3.FromArray(o, k);
                    d && _GLTFUtilities._GetRightHandedPositionVector3FromRef(_e),
                    b.push(_e.asArray())
                }
                break
            }
        case VertexBuffer.NormalKind:
            {
                for (var j = 0, et = o.length / s; j < et; ++j) {
                    k = j * s;
                    var _e = Vector3.FromArray(o, k);
                    d && _GLTFUtilities._GetRightHandedNormalVector3FromRef(_e),
                    _e.normalize(),
                    b.push(_e.asArray())
                }
                break
            }
        case VertexBuffer.TangentKind:
            {
                for (var j = 0, tt = o.length / s; j < tt; ++j) {
                    k = j * s;
                    var _e = Vector4.FromArray(o, k);
                    d && _GLTFUtilities._GetRightHandedVector4FromRef(_e),
                    _GLTFUtilities._NormalizeTangentFromRef(_e),
                    b.push(_e.asArray())
                }
                break
            }
        case VertexBuffer.ColorKind:
            {
                for (var rt = _.material, it = rt ? rt.getClassName() === "StandardMaterial" : !0, _e = s === 3 ? new Color3 : new Color4, j = 0, nt = o.length / s; j < nt; ++j)
                    k = j * s,
                    s === 3 ? (Color3.FromArrayToRef(o, k, _e),
                    it && _e.toLinearSpaceToRef(_e)) : (Color4.FromArrayToRef(o, k, _e),
                    it && _e.toLinearSpaceToRef(_e)),
                    b.push(_e.asArray());
                break
            }
        case VertexBuffer.UVKind:
        case VertexBuffer.UV2Kind:
            {
                for (var j = 0, ot = o.length / s; j < ot; ++j)
                    k = j * s,
                    b.push(d ? [o[k], o[k + 1]] : [o[k], o[k + 1]]);
                break
            }
        case VertexBuffer.MatricesIndicesKind:
        case VertexBuffer.MatricesIndicesExtraKind:
            {
                for (var j = 0, at = o.length / s; j < at; ++j) {
                    k = j * s;
                    var _e = Vector4.FromArray(o, k);
                    b.push(_e.asArray())
                }
                break
            }
        case VertexBuffer.MatricesWeightsKind:
        case VertexBuffer.MatricesWeightsExtraKind:
            {
                for (var j = 0, st = o.length / s; j < st; ++j) {
                    k = j * s;
                    var _e = Vector4.FromArray(o, k);
                    b.push(_e.asArray())
                }
                break
            }
        default:
            Tools.Warn("Unsupported Vertex Buffer Type: " + e),
            b = []
        }
        var ut;
        switch (i) {
        case 5121:
            {
                ut = c.setUInt8.bind(c);
                break
            }
        case 5123:
            {
                ut = c.setUInt16.bind(c);
                break
            }
        case 5125:
            ut = c.setUInt32.bind(c);
        case 5126:
            {
                ut = c.setFloat32.bind(c);
                break
            }
        default:
            {
                Tools.Warn("Unsupported Attribute Component kind: " + i);
                return
            }
        }
        for (var ct = 0, lt = b; ct < lt.length; ct++)
            for (var ft = lt[ct], ht = 0, pt = ft; ht < pt.length; ht++) {
                var dt = pt[ht];
                ut(dt)
            }
    }
    ,
    a.prototype.writeMorphTargetAttributeData = function(e, i, o, s, c, d, _, b, k, j) {
        var $ = [], _e, et = new Vector3, tt = new Vector4(0,0,0,0);
        switch (e) {
        case VertexBuffer.PositionKind:
            {
                for (var rt = o.verticesStart; rt < o.verticesCount; ++rt) {
                    _e = o.indexStart + rt * _;
                    var it = Vector3.FromArray(c, _e)
                      , nt = Vector3.FromArray(d, _e);
                    et = nt.subtractToRef(it, et),
                    k && _GLTFUtilities._GetRightHandedPositionVector3FromRef(et),
                    j && (j.min.copyFromFloats(Math.min(et.x, j.min.x), Math.min(et.y, j.min.y), Math.min(et.z, j.min.z)),
                    j.max.copyFromFloats(Math.max(et.x, j.max.x), Math.max(et.y, j.max.y), Math.max(et.z, j.max.z))),
                    $.push(et.asArray())
                }
                break
            }
        case VertexBuffer.NormalKind:
            {
                for (var rt = o.verticesStart; rt < o.verticesCount; ++rt) {
                    _e = o.indexStart + rt * _;
                    var it = Vector3.FromArray(c, _e);
                    it.normalize();
                    var nt = Vector3.FromArray(d, _e);
                    nt.normalize(),
                    et = nt.subtractToRef(it, et),
                    k && _GLTFUtilities._GetRightHandedNormalVector3FromRef(et),
                    $.push(et.asArray())
                }
                break
            }
        case VertexBuffer.TangentKind:
            {
                for (var rt = o.verticesStart; rt < o.verticesCount; ++rt) {
                    _e = o.indexStart + rt * (_ + 1);
                    var it = Vector4.FromArray(c, _e);
                    _GLTFUtilities._NormalizeTangentFromRef(it);
                    var nt = Vector4.FromArray(d, _e);
                    _GLTFUtilities._NormalizeTangentFromRef(nt),
                    tt = nt.subtractToRef(it, tt),
                    k && _GLTFUtilities._GetRightHandedVector4FromRef(tt),
                    $.push([tt.x, tt.y, tt.z])
                }
                break
            }
        default:
            Tools.Warn("Unsupported Vertex Buffer Type: " + e),
            $ = []
        }
        var ot;
        switch (i) {
        case 5121:
            {
                ot = b.setUInt8.bind(b);
                break
            }
        case 5123:
            {
                ot = b.setUInt16.bind(b);
                break
            }
        case 5125:
            ot = b.setUInt32.bind(b);
        case 5126:
            {
                ot = b.setFloat32.bind(b);
                break
            }
        default:
            {
                Tools.Warn("Unsupported Attribute Component kind: " + i);
                return
            }
        }
        for (var at = 0, st = $; at < st.length; at++)
            for (var ut = st[at], ct = 0, lt = ut; ct < lt.length; ct++) {
                var ft = lt[ct];
                ot(ft)
            }
    }
    ,
    a.prototype.generateJSON = function(e, i, o) {
        var s = this, c = {
            byteLength: this._totalByteLength
        }, d, _, b, k = this._totalByteLength;
        c.byteLength && (this._glTF.buffers = [c]),
        this._nodes && this._nodes.length && (this._glTF.nodes = this._nodes),
        this._meshes && this._meshes.length && (this._glTF.meshes = this._meshes),
        this._scenes && this._scenes.length && (this._glTF.scenes = this._scenes,
        this._glTF.scene = 0),
        this._bufferViews && this._bufferViews.length && (this._glTF.bufferViews = this._bufferViews),
        this._accessors && this._accessors.length && (this._glTF.accessors = this._accessors),
        this._animations && this._animations.length && (this._glTF.animations = this._animations),
        this._materials && this._materials.length && (this._glTF.materials = this._materials),
        this._textures && this._textures.length && (this._glTF.textures = this._textures),
        this._samplers && this._samplers.length && (this._glTF.samplers = this._samplers),
        this._skins && this._skins.length && (this._glTF.skins = this._skins),
        this._images && this._images.length && (e ? (this._glTF.images = [],
        this._images.forEach(function($) {
            $.uri && (_ = s._imageData[$.uri],
            s._orderedImageData.push(_),
            d = $.uri.split(".")[0] + " image",
            b = _GLTFUtilities._CreateBufferView(0, k, _.data.length, void 0, d),
            k += _.data.buffer.byteLength,
            s._bufferViews.push(b),
            $.bufferView = s._bufferViews.length - 1,
            $.name = d,
            $.mimeType = _.mimeType,
            $.uri = void 0,
            s._glTF.images || (s._glTF.images = []),
            s._glTF.images.push($))
        }),
        c.byteLength = k) : this._glTF.images = this._images),
        e || (c.uri = i + ".bin");
        var j = o ? JSON.stringify(this._glTF, null, 2) : JSON.stringify(this._glTF);
        return j
    }
    ,
    a.prototype._generateGLTFAsync = function(e, i) {
        var o = this;
        return i === void 0 && (i = !0),
        this._generateBinaryAsync().then(function(s) {
            o._extensionsOnExporting();
            var c = o.generateJSON(!1, e, !0)
              , d = new Blob([s],{
                type: "application/octet-stream"
            })
              , _ = e + ".gltf"
              , b = e + ".bin"
              , k = new GLTFData;
            if (k.glTFFiles[_] = c,
            k.glTFFiles[b] = d,
            o._imageData)
                for (var j in o._imageData)
                    k.glTFFiles[j] = new Blob([o._imageData[j].data],{
                        type: o._imageData[j].mimeType
                    });
            return i && o.dispose(),
            k
        })
    }
    ,
    a.prototype._generateBinaryAsync = function() {
        var e = this
          , i = new _BinaryWriter(4);
        return this.createSceneAsync(this._babylonScene, i).then(function() {
            return e._localEngine && e._localEngine.dispose(),
            i.getArrayBuffer()
        })
    }
    ,
    a.prototype._getPadding = function(e) {
        var i = e % 4
          , o = i === 0 ? i : 4 - i;
        return o
    }
    ,
    a.prototype._generateGLBAsync = function(e, i) {
        var o = this;
        return i === void 0 && (i = !0),
        this._generateBinaryAsync().then(function(s) {
            o._extensionsOnExporting();
            var c = o.generateJSON(!0), d = e + ".glb", _ = 12, b = 8, k = c.length, j, $ = 0;
            if (typeof TextEncoder != "undefined") {
                var _e = new TextEncoder;
                j = _e.encode(c),
                k = j.length
            }
            for (var et = 0; et < o._orderedImageData.length; ++et)
                $ += o._orderedImageData[et].data.byteLength;
            var tt = o._getPadding(k)
              , rt = o._getPadding(s.byteLength)
              , it = o._getPadding($)
              , nt = _ + 2 * b + k + tt + s.byteLength + rt + $ + it
              , ot = new ArrayBuffer(_)
              , at = new DataView(ot);
            at.setUint32(0, 1179937895, !0),
            at.setUint32(4, 2, !0),
            at.setUint32(8, nt, !0);
            var st = new ArrayBuffer(b + k + tt)
              , ut = new DataView(st);
            ut.setUint32(0, k + tt, !0),
            ut.setUint32(4, 1313821514, !0);
            var ct = new Uint8Array(st,b);
            if (j)
                ct.set(j);
            else
                for (var lt = "_".charCodeAt(0), et = 0; et < k; ++et) {
                    var ft = c.charCodeAt(et);
                    ft != c.codePointAt(et) ? ct[et] = lt : ct[et] = ft
                }
            for (var ht = new Uint8Array(st,b + k), et = 0; et < tt; ++et)
                ht[et] = 32;
            var pt = new ArrayBuffer(b)
              , dt = new DataView(pt);
            dt.setUint32(0, s.byteLength + $ + it, !0),
            dt.setUint32(4, 5130562, !0);
            for (var _t = new ArrayBuffer(rt), mt = new Uint8Array(_t), et = 0; et < rt; ++et)
                mt[et] = 0;
            for (var vt = new ArrayBuffer(it), yt = new Uint8Array(vt), et = 0; et < it; ++et)
                yt[et] = 0;
            for (var Et = [ot, st, pt, s], et = 0; et < o._orderedImageData.length; ++et)
                Et.push(o._orderedImageData[et].data.buffer);
            Et.push(_t),
            Et.push(vt);
            var At = new Blob(Et,{
                type: "application/octet-stream"
            })
              , gt = new GLTFData;
            return gt.glTFFiles[d] = At,
            o._localEngine != null && o._localEngine.dispose(),
            i && o.dispose(),
            gt
        })
    }
    ,
    a.prototype.setNodeTransformation = function(e, i, o) {
        i.getPivotPoint().equalsToFloats(0, 0, 0) || Tools.Warn("Pivot points are not supported in the glTF serializer"),
        i.position.equalsToFloats(0, 0, 0) || (e.translation = o ? _GLTFUtilities._GetRightHandedPositionVector3(i.position).asArray() : i.position.asArray()),
        i.scaling.equalsToFloats(1, 1, 1) || (e.scale = i.scaling.asArray());
        var s = Quaternion.RotationYawPitchRoll(i.rotation.y, i.rotation.x, i.rotation.z);
        i.rotationQuaternion && s.multiplyInPlace(i.rotationQuaternion),
        s.x === 0 && s.y === 0 && s.z === 0 && s.w === 1 || (o && _GLTFUtilities._GetRightHandedQuaternionFromRef(s),
        e.rotation = s.normalize().asArray())
    }
    ,
    a.prototype.getVertexBufferFromMesh = function(e, i) {
        if (i.isVerticesDataPresent(e)) {
            var o = i.getVertexBuffer(e);
            if (o)
                return o
        }
        return null
    }
    ,
    a.prototype.createBufferViewKind = function(e, i, o, s, c, d) {
        var _ = o instanceof Mesh ? o : o instanceof InstancedMesh ? o.sourceMesh : null;
        if (_) {
            var b = _.getVertexBuffer(e)
              , k = _.getVerticesData(e);
            if (b && k) {
                var j = VertexBuffer.GetTypeByteLength(i)
                  , $ = k.length * j
                  , _e = _GLTFUtilities._CreateBufferView(0, s.getByteOffset(), $, c, e + " - " + _.name);
                this._bufferViews.push(_e),
                this.writeAttributeData(e, i, k, c / j, s, d, o)
            }
        }
    }
    ,
    a.prototype.setMorphTargetAttributes = function(e, i, o, s, c) {
        if (o) {
            i.targets || (i.targets = []);
            var d = {};
            if (o.hasNormals) {
                var _ = e.getMesh().getVerticesData(VertexBuffer.NormalKind)
                  , b = o.getNormals()
                  , k = e.verticesCount
                  , j = 12
                  , $ = k * j
                  , _e = _GLTFUtilities._CreateBufferView(0, s.getByteOffset(), $, j, o.name + "_NORMAL");
                this._bufferViews.push(_e);
                var et = this._bufferViews.length - 1
                  , tt = _GLTFUtilities._CreateAccessor(et, o.name + " - NORMAL", "VEC3", 5126, k, 0, null, null);
                this._accessors.push(tt),
                d.NORMAL = this._accessors.length - 1,
                this.writeMorphTargetAttributeData(VertexBuffer.NormalKind, 5126, e, o, _, b, j / 4, s, c)
            }
            if (o.hasPositions) {
                var rt = e.getMesh().getVerticesData(VertexBuffer.PositionKind)
                  , it = o.getPositions()
                  , k = e.verticesCount
                  , j = 12
                  , $ = k * j
                  , _e = _GLTFUtilities._CreateBufferView(0, s.getByteOffset(), $, j, o.name + "_POSITION");
                this._bufferViews.push(_e);
                var et = this._bufferViews.length - 1
                  , nt = {
                    min: new Vector3(1 / 0,1 / 0,1 / 0),
                    max: new Vector3(-1 / 0,-1 / 0,-1 / 0)
                }
                  , tt = _GLTFUtilities._CreateAccessor(et, o.name + " - POSITION", "VEC3", 5126, k, 0, null, null);
                this._accessors.push(tt),
                d.POSITION = this._accessors.length - 1,
                this.writeMorphTargetAttributeData(VertexBuffer.PositionKind, 5126, e, o, rt, it, j / 4, s, c, nt),
                tt.min = nt.min.asArray(),
                tt.max = nt.max.asArray()
            }
            if (o.hasTangents) {
                var ot = e.getMesh().getVerticesData(VertexBuffer.TangentKind)
                  , at = o.getTangents()
                  , k = e.verticesCount
                  , j = 12
                  , $ = k * j
                  , _e = _GLTFUtilities._CreateBufferView(0, s.getByteOffset(), $, j, o.name + "_NORMAL");
                this._bufferViews.push(_e);
                var et = this._bufferViews.length - 1
                  , tt = _GLTFUtilities._CreateAccessor(et, o.name + " - TANGENT", "VEC3", 5126, k, 0, null, null);
                this._accessors.push(tt),
                d.TANGENT = this._accessors.length - 1,
                this.writeMorphTargetAttributeData(VertexBuffer.TangentKind, 5126, e, o, ot, at, j / 4, s, c)
            }
            i.targets.push(d)
        }
    }
    ,
    a.prototype.getMeshPrimitiveMode = function(e) {
        return e instanceof LinesMesh ? Material.LineListDrawMode : e.material ? e.material.fillMode : Material.TriangleFillMode
    }
    ,
    a.prototype.setPrimitiveMode = function(e, i) {
        switch (i) {
        case Material.TriangleFillMode:
            break;
        case Material.TriangleStripDrawMode:
            {
                e.mode = 5;
                break
            }
        case Material.TriangleFanDrawMode:
            {
                e.mode = 6;
                break
            }
        case Material.PointListDrawMode:
            e.mode = 0;
        case Material.PointFillMode:
            {
                e.mode = 0;
                break
            }
        case Material.LineLoopDrawMode:
            {
                e.mode = 2;
                break
            }
        case Material.LineListDrawMode:
            {
                e.mode = 1;
                break
            }
        case Material.LineStripDrawMode:
            {
                e.mode = 3;
                break
            }
        }
    }
    ,
    a.prototype.setAttributeKind = function(e, i) {
        switch (i) {
        case VertexBuffer.PositionKind:
            {
                e.attributes.POSITION = this._accessors.length - 1;
                break
            }
        case VertexBuffer.NormalKind:
            {
                e.attributes.NORMAL = this._accessors.length - 1;
                break
            }
        case VertexBuffer.ColorKind:
            {
                e.attributes.COLOR_0 = this._accessors.length - 1;
                break
            }
        case VertexBuffer.TangentKind:
            {
                e.attributes.TANGENT = this._accessors.length - 1;
                break
            }
        case VertexBuffer.UVKind:
            {
                e.attributes.TEXCOORD_0 = this._accessors.length - 1;
                break
            }
        case VertexBuffer.UV2Kind:
            {
                e.attributes.TEXCOORD_1 = this._accessors.length - 1;
                break
            }
        case VertexBuffer.MatricesIndicesKind:
            {
                e.attributes.JOINTS_0 = this._accessors.length - 1;
                break
            }
        case VertexBuffer.MatricesIndicesExtraKind:
            {
                e.attributes.JOINTS_1 = this._accessors.length - 1;
                break
            }
        case VertexBuffer.MatricesWeightsKind:
            {
                e.attributes.WEIGHTS_0 = this._accessors.length - 1;
                break
            }
        case VertexBuffer.MatricesWeightsExtraKind:
            {
                e.attributes.WEIGHTS_1 = this._accessors.length - 1;
                break
            }
        default:
            Tools.Warn("Unsupported Vertex Buffer Type: " + i)
        }
    }
    ,
    a.prototype.setPrimitiveAttributesAsync = function(e, i, o, s) {
        var c, d = [], _ = null, b, k;
        i instanceof Mesh ? _ = i : i instanceof InstancedMesh && (_ = i.sourceMesh);
        var j = [{
            kind: VertexBuffer.PositionKind,
            accessorType: "VEC3",
            accessorComponentType: 5126,
            byteStride: 12
        }, {
            kind: VertexBuffer.NormalKind,
            accessorType: "VEC3",
            accessorComponentType: 5126,
            byteStride: 12
        }, {
            kind: VertexBuffer.ColorKind,
            accessorType: "VEC4",
            accessorComponentType: 5126,
            byteStride: 16
        }, {
            kind: VertexBuffer.TangentKind,
            accessorType: "VEC4",
            accessorComponentType: 5126,
            byteStride: 16
        }, {
            kind: VertexBuffer.UVKind,
            accessorType: "VEC2",
            accessorComponentType: 5126,
            byteStride: 8
        }, {
            kind: VertexBuffer.UV2Kind,
            accessorType: "VEC2",
            accessorComponentType: 5126,
            byteStride: 8
        }, {
            kind: VertexBuffer.MatricesIndicesKind,
            accessorType: "VEC4",
            accessorComponentType: 5123,
            byteStride: 8
        }, {
            kind: VertexBuffer.MatricesIndicesExtraKind,
            accessorType: "VEC4",
            accessorComponentType: 5123,
            byteStride: 8
        }, {
            kind: VertexBuffer.MatricesWeightsKind,
            accessorType: "VEC4",
            accessorComponentType: 5126,
            byteStride: 16
        }, {
            kind: VertexBuffer.MatricesWeightsExtraKind,
            accessorType: "VEC4",
            accessorComponentType: 5126,
            byteStride: 16
        }];
        if (_) {
            for (var $ = null, _e = this.getMeshPrimitiveMode(_), et = {}, tt = _.morphTargetManager, rt = 0, it = j; rt < it.length; rt++) {
                var nt = it[rt]
                  , ot = nt.kind
                  , at = nt.accessorComponentType;
                if (_.isVerticesDataPresent(ot)) {
                    var st = this.getVertexBufferFromMesh(ot, _);
                    nt.byteStride = st ? st.getSize() * VertexBuffer.GetTypeByteLength(nt.accessorComponentType) : VertexBuffer.DeduceStride(ot) * 4,
                    nt.byteStride === 12 && (nt.accessorType = "VEC3"),
                    this.createBufferViewKind(ot, at, i, o, nt.byteStride, s),
                    nt.bufferViewIndex = this._bufferViews.length - 1,
                    et[ot] = nt.bufferViewIndex
                }
            }
            if (_.getTotalIndices()) {
                var ut = _.getIndices();
                if (ut) {
                    var ct = ut.length * 4;
                    b = _GLTFUtilities._CreateBufferView(0, o.getByteOffset(), ct, void 0, "Indices - " + _.name),
                    this._bufferViews.push(b),
                    $ = this._bufferViews.length - 1;
                    for (var lt = 0, ft = ut.length; lt < ft; ++lt)
                        o.setUInt32(ut[lt])
                }
            }
            if (_.subMeshes)
                for (var ht = 0, pt = _.subMeshes; ht < pt.length; ht++) {
                    var dt = pt[ht]
                      , _t = dt.getMaterial() || _.getScene().defaultMaterial
                      , mt = null;
                    if (_t)
                        if (_ instanceof LinesMesh) {
                            var vt = {
                                name: _.name + " material"
                            };
                            (!_.color.equals(Color3.White()) || _.alpha < 1) && (vt.pbrMetallicRoughness = {
                                baseColorFactor: _.color.asArray().concat([_.alpha])
                            }),
                            this._materials.push(vt),
                            mt = this._materials.length - 1
                        } else if (_t.getClassName() === "MultiMaterial") {
                            var yt = _t.subMaterials[dt.materialIndex];
                            yt && (_t = yt,
                            mt = this._materialMap[_t.uniqueId])
                        } else
                            mt = this._materialMap[_t.uniqueId];
                    var Et = mt != null ? this._materials[mt] : null
                      , At = {
                        attributes: {}
                    };
                    this.setPrimitiveMode(At, _e);
                    for (var gt = 0, St = j; gt < St.length; gt++) {
                        var nt = St[gt]
                          , ot = nt.kind;
                        if (!((ot === VertexBuffer.UVKind || ot === VertexBuffer.UV2Kind) && !this._options.exportUnusedUVs && Et && !this._glTFMaterialExporter._hasTexturesPresent(Et))) {
                            var xt = _.getVerticesData(ot);
                            if (xt) {
                                var st = this.getVertexBufferFromMesh(ot, _);
                                if (st) {
                                    var bt = st.getSize()
                                      , Rt = nt.bufferViewIndex;
                                    if (Rt != null) {
                                        k = {
                                            min: null,
                                            max: null
                                        },
                                        ot == VertexBuffer.PositionKind && (k = _GLTFUtilities._CalculateMinMaxPositions(xt, 0, xt.length / bt, s));
                                        var Mt = _GLTFUtilities._CreateAccessor(Rt, ot + " - " + i.name, nt.accessorType, nt.accessorComponentType, xt.length / bt, 0, k.min, k.max);
                                        this._accessors.push(Mt),
                                        this.setAttributeKind(At, ot)
                                    }
                                }
                            }
                        }
                    }
                    if ($) {
                        var Mt = _GLTFUtilities._CreateAccessor($, "indices - " + i.name, "SCALAR", 5125, dt.indexCount, dt.indexStart * 4, null, null);
                        this._accessors.push(Mt),
                        At.indices = this._accessors.length - 1
                    }
                    if (mt != null && Object.keys(At.attributes).length > 0) {
                        var Pt = _.overrideMaterialSideOrientation !== null ? _.overrideMaterialSideOrientation : _t.sideOrientation;
                        if (Pt == Material.ClockWiseSideOrientation && this._babylonScene.useRightHandedSystem || Pt == Material.ClockWiseSideOrientation && s && _.overrideMaterialSideOrientation !== ((c = _.material) === null || c === void 0 ? void 0 : c.sideOrientation)) {
                            var It = $ != null ? this._bufferViews[$].byteOffset : null;
                            It == null && (It = 0);
                            var Dt = null;
                            if ($ != null && (Dt = _.getIndices()),
                            Dt)
                                this.reorderIndicesBasedOnPrimitiveMode(dt, _e, Dt, It, o);
                            else
                                for (var Ct = 0, Ot = j; Ct < Ot.length; Ct++) {
                                    var nt = Ot[Ct]
                                      , xt = _.getVerticesData(nt.kind);
                                    if (xt) {
                                        var wt = this._bufferViews[et[nt.kind]].byteOffset;
                                        wt || (wt = 0),
                                        this.reorderVertexAttributeDataBasedOnPrimitiveMode(dt, _e, Pt, nt.kind, xt, wt, o, s)
                                    }
                                }
                        }
                        At.material = mt
                    }
                    if (tt)
                        for (var Nt = void 0, Ft = 0; Ft < tt.numTargets; ++Ft)
                            Nt = tt.getTarget(Ft),
                            this.setMorphTargetAttributes(dt, At, Nt, o, s);
                    e.primitives.push(At),
                    this._extensionsPostExportMeshPrimitiveAsync("postExport", At, dt, o),
                    d.push()
                }
        }
        return Promise.all(d).then(function() {})
    }
    ,
    a.prototype.isBabylonCoordinateSystemConvertingNode = function(e) {
        if (e instanceof TransformNode) {
            if (e.name !== "__root__")
                return !1;
            for (var i = e.getWorldMatrix(), o = Matrix.Compose(this._convertToRightHandedSystem ? new Vector3(-1,1,1) : Vector3.One(), Quaternion.Identity(), Vector3.Zero()), s = i.multiply(o), c = Matrix.IdentityReadOnly, d = 0; d < 16; d++)
                if (Math.abs(s.m[d] - c.m[d]) > Epsilon)
                    return !1;
            return !(e instanceof Mesh && e.geometry !== null || e instanceof InstancedMesh && e.sourceMesh.geometry !== null || this._includeCoordinateSystemConversionNodes)
        }
        return !1
    }
    ,
    a.prototype.createSceneAsync = function(e, i) {
        var o = this, s = {
            nodes: []
        }, c, d, _, b = __spreadArray(__spreadArray(__spreadArray([], e.transformNodes, !0), e.meshes, !0), e.lights, !0), k = [];
        return this._convertToRightHandedSystem = !e.useRightHandedSystem,
        this._convertToRightHandedSystemMap = {},
        e.rootNodes.forEach(function(j) {
            o._convertToRightHandedSystemMap[j.uniqueId] = o._convertToRightHandedSystem,
            j.getDescendants(!1).forEach(function($) {
                o._convertToRightHandedSystemMap[$.uniqueId] = o._convertToRightHandedSystem
            })
        }),
        e.rootNodes.forEach(function(j) {
            if (o.isBabylonCoordinateSystemConvertingNode(j)) {
                k.push(j);
                var $ = b.indexOf(j);
                $ !== -1 && b.splice($, 1),
                j.getDescendants(!1).forEach(function(_e) {
                    o._convertToRightHandedSystemMap[_e.uniqueId] = !1
                })
            }
        }),
        this._glTFMaterialExporter._convertMaterialsToGLTFAsync(e.materials, "image/png", !0).then(function() {
            return o.createNodeMapAndAnimationsAsync(e, b, i).then(function(j) {
                return o.createSkinsAsync(e, j, i).then(function($) {
                    if (o._nodeMap = j,
                    o._totalByteLength = i.getByteOffset(),
                    o._totalByteLength == null)
                        throw new Error("undefined byte length!");
                    for (var _e = 0, et = b; _e < et.length; _e++) {
                        var tt = et[_e];
                        if (c = o._nodeMap[tt.uniqueId],
                        c !== void 0) {
                            if (d = o._nodes[c],
                            tt.metadata && (o._options.metadataSelector ? d.extras = o._options.metadataSelector(tt.metadata) : tt.metadata.gltf && (d.extras = tt.metadata.gltf.extras)),
                            !tt.parent || k.indexOf(tt.parent) !== -1)
                                if (o._options.shouldExportNode && !o._options.shouldExportNode(tt))
                                    Tools.Log("Omitting " + tt.name + " from scene.");
                                else {
                                    var rt = o._convertToRightHandedSystemMap[tt.uniqueId];
                                    rt && (d.translation && (d.translation[2] *= -1,
                                    d.translation[0] *= -1),
                                    d.rotation = d.rotation ? Quaternion.FromArray([0, 1, 0, 0]).multiply(Quaternion.FromArray(d.rotation)).asArray() : Quaternion.FromArray([0, 1, 0, 0]).asArray()),
                                    s.nodes.push(c)
                                }
                            if (tt instanceof Mesh) {
                                var it = tt;
                                it.skeleton && (d.skin = $[it.skeleton.uniqueId])
                            }
                            if (_ = tt.getDescendants(!0),
                            !d.children && _ && _.length) {
                                for (var nt = [], ot = 0, at = _; ot < at.length; ot++) {
                                    var st = at[ot];
                                    o._nodeMap[st.uniqueId] != null && nt.push(o._nodeMap[st.uniqueId])
                                }
                                nt.length && (d.children = nt)
                            }
                        }
                    }
                    s.nodes.length && o._scenes.push(s)
                })
            })
        })
    }
    ,
    a.prototype.createNodeMapAndAnimationsAsync = function(e, i, o) {
        for (var s = this, c = Promise.resolve(), d = {}, _, b = {
            name: "runtime animations",
            channels: [],
            samplers: []
        }, k = [], j = function(rt) {
            !$._options.shouldExportNode || $._options.shouldExportNode(rt) ? c = c.then(function() {
                var it = s._convertToRightHandedSystemMap[rt.uniqueId];
                return s.createNodeAsync(rt, o, it, d).then(function(nt) {
                    var ot = s._extensionsPostExportNodeAsync("createNodeAsync", nt, rt, d);
                    return ot == null ? (Tools.Warn("Not exporting node " + rt.name),
                    Promise.resolve()) : ot.then(function(at) {
                        !at || (s._nodes.push(at),
                        _ = s._nodes.length - 1,
                        d[rt.uniqueId] = _,
                        e.animationGroups.length || (_GLTFAnimation._CreateMorphTargetAnimationFromMorphTargetAnimations(rt, b, k, d, s._nodes, o, s._bufferViews, s._accessors, it, s._animationSampleRate),
                        rt.animations.length && _GLTFAnimation._CreateNodeAnimationFromNodeAnimations(rt, b, k, d, s._nodes, o, s._bufferViews, s._accessors, it, s._animationSampleRate)))
                    })
                })
            }) : "" + rt.name
        }, $ = this, _e = 0, et = i; _e < et.length; _e++) {
            var tt = et[_e];
            j(tt)
        }
        return c.then(function() {
            return b.channels.length && b.samplers.length && s._animations.push(b),
            k.forEach(function(rt) {
                rt.channels.length && rt.samplers.length && s._animations.push(rt)
            }),
            e.animationGroups.length && _GLTFAnimation._CreateNodeAndMorphAnimationFromAnimationGroups(e, s._animations, d, s._nodes, o, s._bufferViews, s._accessors, s._convertToRightHandedSystemMap, s._animationSampleRate),
            d
        })
    }
    ,
    a.prototype.createNodeAsync = function(e, i, o, s) {
        var c = this;
        return Promise.resolve().then(function() {
            var d = {}
              , _ = {
                primitives: []
            };
            if (e.name && (d.name = e.name),
            e instanceof TransformNode) {
                if (c.setNodeTransformation(d, e, o),
                e instanceof Mesh) {
                    var b = e.morphTargetManager;
                    if (b && b.numTargets > 0) {
                        _.weights = [];
                        for (var k = 0; k < b.numTargets; ++k)
                            _.weights.push(b.getTarget(k).influence)
                    }
                }
                return c.setPrimitiveAttributesAsync(_, e, i, o).then(function() {
                    return _.primitives.length && (c._meshes.push(_),
                    d.mesh = c._meshes.length - 1),
                    d
                })
            } else
                return d
        })
    }
    ,
    a.prototype.createSkinsAsync = function(e, i, o) {
        for (var s, c = Promise.resolve(), d = {}, _ = 0, b = e.skeletons; _ < b.length; _++) {
            for (var k = b[_], j = {
                joints: []
            }, $ = [], _e = {}, et = -1, tt = 0; tt < k.bones.length; ++tt) {
                var rt = k.bones[tt]
                  , it = (s = rt.getIndex()) !== null && s !== void 0 ? s : tt;
                it !== -1 && (_e[it] = rt,
                it > et && (et = it))
            }
            for (var it = 0; it <= et; ++it) {
                var rt = _e[it];
                $.push(rt.getInvertedAbsoluteTransform());
                var nt = rt.getTransformNode();
                nt ? j.joints.push(i[nt.uniqueId]) : Tools.Warn("Exporting a bone without a linked transform node is currently unsupported")
            }
            var ot = 64
              , at = $.length * ot
              , st = o.getByteOffset()
              , ut = _GLTFUtilities._CreateBufferView(0, st, at, void 0, "InverseBindMatrices - " + k.name);
            this._bufferViews.push(ut);
            var ct = this._bufferViews.length - 1
              , lt = _GLTFUtilities._CreateAccessor(ct, "InverseBindMatrices - " + k.name, "MAT4", 5126, $.length, null, null, null)
              , ft = this._accessors.push(lt) - 1;
            j.inverseBindMatrices = ft,
            this._skins.push(j),
            d[k.uniqueId] = this._skins.length - 1,
            $.forEach(function(ht) {
                ht.m.forEach(function(pt) {
                    o.setFloat32(pt)
                })
            })
        }
        return c.then(function() {
            return d
        })
    }
    ,
    a._ExtensionNames = new Array,
    a._ExtensionFactories = {},
    a
}()
  , _BinaryWriter = function() {
    function a(e) {
        this._arrayBuffer = new ArrayBuffer(e),
        this._dataView = new DataView(this._arrayBuffer),
        this._byteOffset = 0
    }
    return a.prototype.resizeBuffer = function(e) {
        for (var i = new ArrayBuffer(e), o = new Uint8Array(this._arrayBuffer), s = new Uint8Array(i), c = 0, d = s.byteLength; c < d; ++c)
            s[c] = o[c];
        return this._arrayBuffer = i,
        this._dataView = new DataView(this._arrayBuffer),
        i
    }
    ,
    a.prototype.getArrayBuffer = function() {
        return this.resizeBuffer(this.getByteOffset())
    }
    ,
    a.prototype.getByteOffset = function() {
        if (this._byteOffset == null)
            throw new Error("Byte offset is undefined!");
        return this._byteOffset
    }
    ,
    a.prototype.setUInt8 = function(e, i) {
        i != null ? i < this._byteOffset ? this._dataView.setUint8(i, e) : Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!") : (this._byteOffset + 1 > this._arrayBuffer.byteLength && this.resizeBuffer(this._arrayBuffer.byteLength * 2),
        this._dataView.setUint8(this._byteOffset, e),
        this._byteOffset += 1)
    }
    ,
    a.prototype.setUInt16 = function(e, i) {
        i != null ? i < this._byteOffset ? this._dataView.setUint16(i, e, !0) : Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!") : (this._byteOffset + 2 > this._arrayBuffer.byteLength && this.resizeBuffer(this._arrayBuffer.byteLength * 2),
        this._dataView.setUint16(this._byteOffset, e, !0),
        this._byteOffset += 2)
    }
    ,
    a.prototype.getUInt32 = function(e) {
        if (e < this._byteOffset)
            return this._dataView.getUint32(e, !0);
        throw Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"),
        new Error("BinaryWriter: byteoffset is greater than the current binary buffer length!")
    }
    ,
    a.prototype.getVector3Float32FromRef = function(e, i) {
        i + 8 > this._byteOffset ? Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!") : (e.x = this._dataView.getFloat32(i, !0),
        e.y = this._dataView.getFloat32(i + 4, !0),
        e.z = this._dataView.getFloat32(i + 8, !0))
    }
    ,
    a.prototype.setVector3Float32FromRef = function(e, i) {
        i + 8 > this._byteOffset ? Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!") : (this._dataView.setFloat32(i, e.x, !0),
        this._dataView.setFloat32(i + 4, e.y, !0),
        this._dataView.setFloat32(i + 8, e.z, !0))
    }
    ,
    a.prototype.getVector4Float32FromRef = function(e, i) {
        i + 12 > this._byteOffset ? Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!") : (e.x = this._dataView.getFloat32(i, !0),
        e.y = this._dataView.getFloat32(i + 4, !0),
        e.z = this._dataView.getFloat32(i + 8, !0),
        e.w = this._dataView.getFloat32(i + 12, !0))
    }
    ,
    a.prototype.setVector4Float32FromRef = function(e, i) {
        i + 12 > this._byteOffset ? Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!") : (this._dataView.setFloat32(i, e.x, !0),
        this._dataView.setFloat32(i + 4, e.y, !0),
        this._dataView.setFloat32(i + 8, e.z, !0),
        this._dataView.setFloat32(i + 12, e.w, !0))
    }
    ,
    a.prototype.setFloat32 = function(e, i) {
        isNaN(e) && Tools.Error("Invalid data being written!"),
        i != null && (i < this._byteOffset ? this._dataView.setFloat32(i, e, !0) : Tools.Error("BinaryWriter: byteoffset is greater than the current binary length!")),
        this._byteOffset + 4 > this._arrayBuffer.byteLength && this.resizeBuffer(this._arrayBuffer.byteLength * 2),
        this._dataView.setFloat32(this._byteOffset, e, !0),
        this._byteOffset += 4
    }
    ,
    a.prototype.setUInt32 = function(e, i) {
        i != null ? i < this._byteOffset ? this._dataView.setUint32(i, e, !0) : Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!") : (this._byteOffset + 4 > this._arrayBuffer.byteLength && this.resizeBuffer(this._arrayBuffer.byteLength * 2),
        this._dataView.setUint32(this._byteOffset, e, !0),
        this._byteOffset += 4)
    }
    ,
    a
}()
  , name = "textureTransformPixelShader"
  , shader = `precision highp float;
varying vec2 vUV;
uniform sampler2D textureSampler;
uniform mat4 textureTransformMat;
void main(void) {
vec2 uvTransformed=(textureTransformMat*vec4(vUV.xy,1,1)).xy;
gl_FragColor=texture2D(textureSampler,uvTransformed);
}`;
ShaderStore.ShadersStore[name] = shader;
var NAME$4 = "KHR_texture_transform"
  , KHR_texture_transform = function() {
    function a(e) {
        this._recordedTextures = [],
        this.name = NAME$4,
        this.enabled = !0,
        this.required = !1,
        this._wasUsed = !1
    }
    return a.prototype.dispose = function() {
        for (var e = 0, i = this._recordedTextures; e < i.length; e++) {
            var o = i[e];
            o.dispose()
        }
    }
    ,
    Object.defineProperty(a.prototype, "wasUsed", {
        get: function() {
            return this._wasUsed
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.postExportTexture = function(e, i, o) {
        var s = o && (o.uAng === 0 && o.wAng === 0 && o.vAng === 0 || o.uRotationCenter === 0 && o.vRotationCenter === 0);
        if (s) {
            var c = {}
              , d = !1;
            if ((o.uOffset !== 0 || o.vOffset !== 0) && (c.offset = [o.uOffset, o.vOffset],
            d = !0),
            (o.uScale !== 1 || o.vScale !== 1) && (c.scale = [o.uScale, o.vScale],
            d = !0),
            o.wAng !== 0 && (c.rotation = o.wAng,
            d = !0),
            o.coordinatesIndex !== 0 && (c.texCoord = o.coordinatesIndex,
            d = !0),
            !d)
                return;
            this._wasUsed = !0,
            i.extensions || (i.extensions = {}),
            i.extensions[NAME$4] = c
        }
    }
    ,
    a.prototype.preExportTextureAsync = function(e, i, o) {
        var s = this;
        return new Promise(function(c, d) {
            var _ = i.getScene();
            if (!_) {
                d(e + ': "scene" is not defined for Babylon texture ' + i.name + "!");
                return
            }
            var b = !1;
            if ((i.uAng !== 0 || i.wAng !== 0 || i.vAng !== 0) && (i.uRotationCenter !== 0 || i.vRotationCenter !== 0) && (b = !0),
            !b) {
                c(i);
                return
            }
            return s._textureTransformTextureAsync(i, _).then(function(k) {
                c(k)
            }).catch(function(k) {
                d(k)
            })
        }
        )
    }
    ,
    a.prototype._textureTransformTextureAsync = function(e, i) {
        var o = this;
        return new Promise(function(s) {
            var c = new ProceduralTexture("" + e.name,e.getSize(),"textureTransform",i);
            c || (Tools.Log("Cannot create procedural texture for " + e.name + "!"),
            s(e)),
            c.reservedDataStore = {
                hidden: !0,
                source: e
            },
            o._recordedTextures.push(c),
            c.coordinatesIndex = e.coordinatesIndex,
            c.setTexture("textureSampler", e),
            c.setMatrix("textureTransformMat", e.getTextureMatrix()),
            c.isReady() ? (c.render(),
            s(c)) : c.getEffect().executeWhenCompiled(function() {
                c.render(),
                s(c)
            })
        }
        )
    }
    ,
    a
}();
_Exporter.RegisterExtension(NAME$4, function(a) {
    return new KHR_texture_transform(a)
});
var NAME$3 = "KHR_lights_punctual"
  , KHR_lights_punctual = function() {
    function a(e) {
        this.name = NAME$3,
        this.enabled = !0,
        this.required = !1,
        this._exporter = e
    }
    return a.prototype.dispose = function() {
        this._lights = null
    }
    ,
    Object.defineProperty(a.prototype, "wasUsed", {
        get: function() {
            return !!this._lights
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.onExporting = function() {
        this._exporter._glTF.extensions[NAME$3] = this._lights
    }
    ,
    a.prototype.postExportNodeAsync = function(e, i, o, s) {
        var c = this;
        return new Promise(function(d, _) {
            if (i && o instanceof ShadowLight) {
                var b = o
                  , k = void 0
                  , j = b.getTypeID() == Light.LIGHTTYPEID_POINTLIGHT ? "point" : b.getTypeID() == Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "directional" : b.getTypeID() == Light.LIGHTTYPEID_SPOTLIGHT ? "spot" : null;
                if (j == null)
                    Logger$2.Warn(e + ": Light " + b.name + " is not supported in " + NAME$3);
                else {
                    var $ = b.position.clone()
                      , _e = c._exporter._convertToRightHandedSystemMap[o.uniqueId];
                    if ($.equals(Vector3.Zero()) || (_e && _GLTFUtilities._GetRightHandedPositionVector3FromRef($),
                    i.translation = $.asArray()),
                    j !== "point") {
                        var et = b.direction
                          , tt = -Math.atan2(et.z * (c._exporter._babylonScene.useRightHandedSystem ? -1 : 1), et.x) + Math.PI / 2
                          , rt = Math.sqrt(et.x * et.x + et.z * et.z)
                          , it = -Math.atan2(et.y, rt)
                          , nt = Quaternion.RotationYawPitchRoll(tt, it, 0);
                        _e && _GLTFUtilities._GetRightHandedQuaternionFromRef(nt),
                        nt.equals(Quaternion.Identity()) || (i.rotation = nt.asArray())
                    }
                    if (b.falloffType !== Light.FALLOFF_GLTF && Logger$2.Warn(e + ": Light falloff for " + b.name + " does not match the " + NAME$3 + " specification!"),
                    k = {
                        type: j
                    },
                    b.diffuse.equals(Color3.White()) || (k.color = b.diffuse.asArray()),
                    b.intensity !== 1 && (k.intensity = b.intensity),
                    b.range !== Number.MAX_VALUE && (k.range = b.range),
                    j === "spot") {
                        var ot = b;
                        ot.angle !== Math.PI / 2 && (k.spot == null && (k.spot = {}),
                        k.spot.outerConeAngle = ot.angle / 2),
                        ot.innerAngle !== 0 && (k.spot == null && (k.spot = {}),
                        k.spot.innerConeAngle = ot.innerAngle / 2)
                    }
                    c._lights == null && (c._lights = {
                        lights: []
                    }),
                    c._lights.lights.push(k);
                    var at = {
                        light: c._lights.lights.length - 1
                    }
                      , st = o.parent;
                    if (st && st.getChildren().length == 1) {
                        var ut = c._exporter._nodes[s[st.uniqueId]];
                        if (ut) {
                            var ct = TmpVectors.Matrix[0]
                              , lt = TmpVectors.Matrix[1]
                              , ft = ut.translation ? new Vector3(ut.translation[0],ut.translation[1],ut.translation[2]) : Vector3.Zero()
                              , ht = ut.rotation ? new Quaternion(ut.rotation[0],ut.rotation[1],ut.rotation[2],ut.rotation[3]) : Quaternion.Identity()
                              , pt = ut.scale ? new Vector3(ut.scale[0],ut.scale[1],ut.scale[2]) : Vector3.One();
                            Matrix.ComposeToRef(pt, ht, ft, ct),
                            ct.invertToRef(lt);
                            var dt = TmpVectors.Matrix[2]
                              , _t = i.translation ? new Vector3(i.translation[0],i.translation[1],i.translation[2]) : Vector3.Zero();
                            b instanceof DirectionalLight && _t.subtractInPlace(c._exporter._babylonScene.useRightHandedSystem ? b.direction : _GLTFUtilities._GetRightHandedPositionVector3(b.direction));
                            var mt = c._exporter._babylonScene.useRightHandedSystem ? Quaternion.Identity() : new Quaternion(0,1,0,0);
                            i.rotation && mt.multiplyInPlace(new Quaternion(i.rotation[0],i.rotation[1],i.rotation[2],i.rotation[3]));
                            var vt = i.scale ? new Vector3(i.scale[0],i.scale[1],i.scale[2]) : Vector3.One();
                            Matrix.ComposeToRef(vt, mt, _t, dt),
                            dt.multiplyToRef(lt, dt);
                            var yt = TmpVectors.Vector3[0]
                              , Et = TmpVectors.Quaternion[0]
                              , At = TmpVectors.Vector3[1];
                            dt.decompose(yt, Et, At),
                            ut.scale = yt.asArray(),
                            ut.rotation = Et.asArray(),
                            ut.translation = At.asArray(),
                            ut.extensions == null && (ut.extensions = {}),
                            ut.extensions[NAME$3] = at,
                            d(null);
                            return
                        }
                    }
                    i.extensions == null && (i.extensions = {}),
                    i.extensions[NAME$3] = at
                }
            }
            d(i)
        }
        )
    }
    ,
    a
}();
_Exporter.RegisterExtension(NAME$3, function(a) {
    return new KHR_lights_punctual(a)
});
var NAME$2 = "KHR_materials_clearcoat"
  , KHR_materials_clearcoat = function() {
    function a(e) {
        this.name = NAME$2,
        this.enabled = !0,
        this.required = !1,
        this._wasUsed = !1,
        this._exporter = e
    }
    return a.prototype.dispose = function() {}
    ,
    Object.defineProperty(a.prototype, "wasUsed", {
        get: function() {
            return this._wasUsed
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.postExportMaterialAdditionalTextures = function(e, i, o) {
        var s = [];
        return o instanceof PBRBaseMaterial && o.clearCoat.isEnabled ? (o.clearCoat.texture && s.push(o.clearCoat.texture),
        !o.clearCoat.useRoughnessFromMainTexture && o.clearCoat.textureRoughness && s.push(o.clearCoat.textureRoughness),
        o.clearCoat.bumpTexture && s.push(o.clearCoat.bumpTexture),
        s) : []
    }
    ,
    a.prototype.postExportMaterialAsync = function(e, i, o) {
        var s = this;
        return new Promise(function(c, d) {
            if (o instanceof PBRBaseMaterial) {
                if (!o.clearCoat.isEnabled) {
                    c(i);
                    return
                }
                s._wasUsed = !0,
                i.extensions = i.extensions || {};
                var _ = s._exporter._glTFMaterialExporter._getTextureInfo(o.clearCoat.texture)
                  , b = void 0;
                o.clearCoat.useRoughnessFromMainTexture ? b = s._exporter._glTFMaterialExporter._getTextureInfo(o.clearCoat.texture) : b = s._exporter._glTFMaterialExporter._getTextureInfo(o.clearCoat.textureRoughness),
                o.clearCoat.isTintEnabled && Tools.Warn("Clear Color tint is not supported for glTF export. Ignoring for: " + o.name),
                o.clearCoat.remapF0OnInterfaceChange && Tools.Warn("Clear Color F0 remapping is not supported for glTF export. Ignoring for: " + o.name);
                var k = s._exporter._glTFMaterialExporter._getTextureInfo(o.clearCoat.bumpTexture)
                  , j = {
                    clearcoatFactor: o.clearCoat.intensity,
                    clearcoatTexture: _ != null ? _ : void 0,
                    clearcoatRoughnessFactor: o.clearCoat.roughness,
                    clearcoatRoughnessTexture: b != null ? b : void 0,
                    clearcoatNormalTexture: k != null ? k : void 0,
                    hasTextures: function() {
                        return j.clearcoatTexture !== null || j.clearcoatRoughnessTexture !== null || j.clearcoatRoughnessTexture !== null
                    }
                };
                i.extensions[NAME$2] = j
            }
            c(i)
        }
        )
    }
    ,
    a
}();
_Exporter.RegisterExtension(NAME$2, function(a) {
    return new KHR_materials_clearcoat(a)
});
var NAME$1 = "KHR_materials_sheen"
  , KHR_materials_sheen = function() {
    function a(e) {
        this.name = NAME$1,
        this.enabled = !0,
        this.required = !1,
        this._wasUsed = !1,
        this._exporter = e
    }
    return a.prototype.dispose = function() {}
    ,
    Object.defineProperty(a.prototype, "wasUsed", {
        get: function() {
            return this._wasUsed
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.postExportMaterialAdditionalTextures = function(e, i, o) {
        return o instanceof PBRMaterial && o.sheen.isEnabled && o.sheen.texture ? [o.sheen.texture] : []
    }
    ,
    a.prototype.postExportMaterialAsync = function(e, i, o) {
        var s = this;
        return new Promise(function(c, d) {
            var _, b, k, j;
            if (o instanceof PBRMaterial) {
                if (!o.sheen.isEnabled) {
                    c(i);
                    return
                }
                s._wasUsed = !0,
                i.extensions == null && (i.extensions = {});
                var $ = {
                    sheenColorFactor: o.sheen.color.asArray(),
                    sheenRoughnessFactor: (_ = o.sheen.roughness) !== null && _ !== void 0 ? _ : 0,
                    hasTextures: function() {
                        return $.sheenColorTexture !== null || $.sheenRoughnessTexture !== null
                    }
                };
                o.sheen.texture && ($.sheenColorTexture = (b = s._exporter._glTFMaterialExporter._getTextureInfo(o.sheen.texture)) !== null && b !== void 0 ? b : void 0),
                o.sheen.textureRoughness && !o.sheen.useRoughnessFromMainTexture ? $.sheenRoughnessTexture = (k = s._exporter._glTFMaterialExporter._getTextureInfo(o.sheen.textureRoughness)) !== null && k !== void 0 ? k : void 0 : o.sheen.texture && o.sheen.useRoughnessFromMainTexture && ($.sheenRoughnessTexture = (j = s._exporter._glTFMaterialExporter._getTextureInfo(o.sheen.texture)) !== null && j !== void 0 ? j : void 0),
                i.extensions[NAME$1] = $
            }
            c(i)
        }
        )
    }
    ,
    a
}();
_Exporter.RegisterExtension(NAME$1, function(a) {
    return new KHR_materials_sheen(a)
});
var NAME = "KHR_materials_unlit"
  , KHR_materials_unlit = function() {
    function a(e) {
        this.name = NAME,
        this.enabled = !0,
        this.required = !1,
        this._wasUsed = !1
    }
    return Object.defineProperty(a.prototype, "wasUsed", {
        get: function() {
            return this._wasUsed
        },
        enumerable: !1,
        configurable: !0
    }),
    a.prototype.dispose = function() {}
    ,
    a.prototype.postExportMaterialAsync = function(e, i, o) {
        var s = this;
        return new Promise(function(c, d) {
            var _ = !1;
            o instanceof PBRMaterial ? _ = o.unlit : o instanceof StandardMaterial && (_ = o.disableLighting),
            _ && (s._wasUsed = !0,
            i.extensions == null && (i.extensions = {}),
            i.extensions[NAME] = {}),
            c(i)
        }
        )
    }
    ,
    a
}();
_Exporter.RegisterExtension(NAME, function(a) {
    return new KHR_materials_unlit(a)
});
new Logger$1("XPackage");
function LoadXObject(a, e) {
    return new Promise((i,o)=>{
        const s = JSON.parse(e);
        new XArchive().deserialize(s, a).then(d=>{
            i(d)
        }
        ).catch(d=>{
            o(d)
        }
        )
    }
    )
}
const log$K = new Logger$1("AvatarManager");
class XAvatarLoader {
    constructor() {
        this.containers = new Map,
        this.meshes = new Map,
        this.animations = new Map,
        this.aniPath = new Map,
        this.binPath = new Map,
        this.texPath = new Map,
        this.matPath = new Map,
        this.mshPath = new Map,
        this.rootPath = new Map,
        this.meshTexList = new Map,
        this._enableIdb = !0,
        this._mappings = new Map,
        this._sharedTex = new Map,
        this.avaliableAnimation = new Map,
        this.enableShareTexture = !0,
        this.enableShareAnimation = !0,
        this.fillEmptyLod = !0,
        this.pendantMap = new Map;
        const e = new GLTFFileLoader;
        SceneLoader.RegisterPlugin(e),
        e.preprocessUrlAsync = function(i) {
            const o = avatarLoader._mappings.get(i);
            return o ? Promise.resolve(o) : Promise.resolve(i)
        }
    }
    _parsePendant(e, i) {
        if (!e || !i) {
            log$K.error("[Engine] invalid id or url when loading pendant");
            return
        }
        const o = ".zip"
          , s = i.replace(o, "/");
        this.pendantMap.set(e, s)
    }
    pullAndLoadXObject(e, i) {
        const o = avatarLoader.pendantMap.get(i);
        return Tools.LoadFileAsync(o + `${i}.json`, !1).then(s=>{
            if (!(s instanceof ArrayBuffer))
                return LoadXObject(o, s).then(c=>c)
        }
        )
    }
    getParsedUrl(e, i, o, s="") {
        return new Promise((c,d)=>{
            if (!o || o.indexOf(".zip") === -1)
                return c(o);
            const _ = this.rootPath.get(o);
            if (_)
                return c(_);
            {
                const b = ".zip"
                  , k = o.replace(b, "") + COMPONENT_LIST_PREFIX;
                e.urlTransformer(k, !0).then(j=>{
                    if (!j)
                        return d("Loading Failed");
                    new Response(j).json().then($=>{
                        var tt, rt, it, nt, ot, at, st;
                        const _e = o.replace(b, "")
                          , et = _e + ((tt = $ == null ? void 0 : $.components) == null ? void 0 : tt.url.replace("./", ""));
                        if (this.rootPath.set(o, et),
                        $.components ? ($.components.url && this.mshPath.set(i, _e + "/" + ((rt = $ == null ? void 0 : $.components) == null ? void 0 : rt.url.replace("./", ""))),
                        $.components.url_lod2 && this.mshPath.set(i + "_" + avatarSetting.lod[1].level, _e + "/" + ((it = $ == null ? void 0 : $.components) == null ? void 0 : it.url_lod2.replace("./", ""))),
                        $.components.url_lod4 && this.mshPath.set(i + "_" + avatarSetting.lod[2].level, _e + "/" + ((nt = $ == null ? void 0 : $.components) == null ? void 0 : nt.url_lod4.replace("./", "")))) : ($.meshes.url && this.mshPath.set(i, _e + "/" + ((ot = $ == null ? void 0 : $.meshes) == null ? void 0 : ot.url.replace("./", ""))),
                        $.meshes.url_lod2 && this.mshPath.set(i + "_" + avatarSetting.lod[1].level, _e + "/" + ((at = $ == null ? void 0 : $.meshes) == null ? void 0 : at.url_lod2.replace("./", ""))),
                        $.meshes.url_lod4 && this.mshPath.set(i + "_" + avatarSetting.lod[2].level, _e + "/" + ((st = $ == null ? void 0 : $.meshes) == null ? void 0 : st.url_lod4.replace("./", "")))),
                        $.materials && $.materials.forEach(ut=>{
                            const ct = _e + "/" + ut.url;
                            this.matPath.set(ut.name, ct)
                        }
                        ),
                        $.bin) {
                            const ut = _e + "/" + $.bin.url;
                            this.binPath.set(i, ut);
                            const ct = _e + "/" + $.bin.url_lod2;
                            this.binPath.set(i + "_" + avatarSetting.lod[1].level, ct);
                            const lt = _e + "/" + $.bin.url_lod4;
                            this.binPath.set(i + "_" + avatarSetting.lod[2].level, lt)
                        }
                        return $.textures && $.textures.forEach(ut=>{
                            const ct = _e + "/" + ut.url;
                            this.texPath.set(ut.url, ct);
                            const lt = this.meshTexList.get($.components.url);
                            ut.type === "png" && (lt ? lt.find(ft=>ft === ut.name) || lt.push(ut.url) : this.meshTexList.set(i, [ut.name]))
                        }
                        ),
                        c(et)
                    }
                    ).catch($=>{
                        d(`[Engine] parse json file error,${$}`)
                    }
                    )
                }
                ).catch(j=>{
                    d(`[Engine] ulrtransform error, cannot find resource in db,${j}`)
                }
                )
            }
        }
        )
    }
    async parse(e, i) {
        const o = [];
        i.forEach(s=>{
            this._setAnimationList(s.id, s.animations),
            o.push(this.getParsedUrl(e, s.id, s.url)),
            s.components.forEach(c=>{
                c.name === "pendant" ? c.units.forEach(d=>{
                    this._parsePendant(d.id, d.url)
                }
                ) : c.units.forEach(d=>{
                    o.push(this.getParsedUrl(e, d.name, d.url))
                }
                )
            }
            )
        }
        ),
        await Promise.all(o)
    }
    _setAnimationList(e, i) {
        i ? i.forEach(o=>{
            this.aniPath.set(e + "_" + o.name, o.url)
        }
        ) : log$K.error("[Engine] no animation list exist, please check config for details")
    }
    disposeContainer() {
        const e = [];
        this.containers.forEach((i,o)=>{
            if (i.xReferenceCount < 1) {
                if (this.enableShareTexture && i.textures.length > 0) {
                    for (let s = 0; s < i.textures.length; ++s)
                        i.textures[s].xReferenceCount != null ? i.textures[s].xReferenceCount-- : i.textures[s].xReferenceCount = 0,
                        i.textures[s]._parentContainer = null;
                    i.textures = []
                }
                e.push(o)
            }
        }
        ),
        e.forEach(i=>{
            var o, s;
            (o = this.containers.get(i)) == null || o.removeAllFromScene(),
            (s = this.containers.get(i)) == null || s.dispose(),
            this.containers.delete(i)
        }
        ),
        this._sharedTex.forEach((i,o)=>{
            i.xReferenceCount == 0 && (i.dispose(),
            this._sharedTex.delete(o))
        }
        )
    }
    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, i) {
        return i && avatarSetting.lod[i] ? e + avatarSetting.lod[i].fileName.split(".")[0] : e
    }
    _getAnimPath(e, i) {
        let o = this.aniPath.get(i + "_animations_" + i.split("_")[1]);
        return o || (o = this.aniPath.get(i + "_" + e)),
        o
    }
    load(e, i, o, s) {
        return this.loadGlb(e, i, o).then(c=>c || Promise.reject("[Engine] container load failed")).catch(()=>Promise.reject("[Engine] container load failed"))
    }
    _searchAnimation(e, i) {
        let o;
        return this.containers.forEach((s,c)=>{
            const d = i.split("_")[0];
            c.indexOf(d) != -1 && c.indexOf(e) != -1 && (o = s)
        }
        ),
        o
    }
    loadAnimRes(e, i, o) {
        const s = this._getAnimPath(i, o)
          , c = getAnimationKey(i, o);
        return s && this.containers.get(s) ? Promise.resolve(this.containers.get(s)) : s ? this._loadGlbFromBlob(e, c, s).then(d=>d.animationGroups.length == 0 ? (this.containers.delete(c),
        d.dispose(),
        Promise.reject("container does not contains animation data")) : d) : Promise.reject("no such url")
    }
    loadGlb(e, i, o) {
        let s = this.getMeshUrl(this._getSourceKey(i, o));
        return !s && this.fillEmptyLod && (o = 0,
        s = this.getMeshUrl(this._getSourceKey(i, o))),
        s && this.containers.get(s) ? Promise.resolve(this.containers.get(s)) : s ? this._enableIdb ? this._loadGlbFromBlob(e, this._getSourceKey(i, o), s) : this._loadGlbFromUrl(e, this._getSourceKey(i, o), s) : Promise.reject("no such url")
    }
    loadGltf(e, i, o, s) {
        const c = this._getSourceKey(i, o || 0);
        let d = this.getGltfPath(c);
        return !d && this.fillEmptyLod && (d = this.getGltfPath(i)),
        d && this.containers.get(d) ? Promise.resolve(this.containers.get(d)) : this._enableIdb ? this._loadGltfFromBlob(e, i, o, s) : d ? this._loadGltfFromUrl(e, i, d.replace(i + ".gltf", "")) : Promise.reject()
    }
    loadSubsequence() {}
    loadVAT() {}
    getResourceName(e) {
        return this.meshTexList.get(e)
    }
    _loadGltfFromUrl(e, i, o) {
        return SceneLoader.LoadAssetContainerAsync(o, i + ".gltf", e.Scene, null, ".gltf")
    }
    _loadGlbFromBlob(e, i, o) {
        return e.urlTransformer(o).then(s=>SceneLoader.LoadAssetContainerAsync("", s, e.Scene, null, ".glb").then(c=>{
            if (c) {
                if (this.containers.get(o))
                    return c.dispose(),
                    this.containers.get(o);
                if (c.addAllToScene(),
                this.enableShareTexture && c.textures.length > 0) {
                    const d = [];
                    let _ = !1;
                    c.meshes.forEach(b=>{
                        if (b.material) {
                            const k = b.material._albedoTexture;
                            if (k) {
                                let j = k.name;
                                j = j.replace(" (Base Color)", "").split(".")[0];
                                const $ = this._sharedTex.get(j);
                                $ ? (_ = !0,
                                b.material._albedoTexture = $,
                                d.push($),
                                $._parentContainer = c,
                                $.xReferenceCount++) : (this._sharedTex.set(j, k),
                                c.textures[0].xReferenceCount = 1)
                            }
                        }
                    }
                    ),
                    _ && (c.textures.forEach(b=>{
                        e.Scene.removeTexture(b),
                        b.dispose()
                    }
                    ),
                    c.textures = d)
                }
                return c.xReferenceCount = 0,
                c.meshes.forEach(d=>{
                    d.setEnabled(!1)
                }
                ),
                this.containers.set(o, c),
                Promise.resolve(c)
            } else
                return Promise.reject("glb file load failed")
        }
        ))
    }
    _loadGlbFromUrl(e, i, o) {
        return SceneLoader.LoadAssetContainerAsync("", o, e.Scene, null, ".glb").then(s=>s ? (s.addAllToScene(),
        s.meshes.forEach(c=>{
            c.setEnabled(!1)
        }
        ),
        this.enableShareTexture && s.textures.length > 0 ? (s.meshes.forEach(c=>{
            if (c.material) {
                const d = c.material._albedoTexture;
                if (d) {
                    let _ = d.name;
                    _ = _.replace(" (Base Color)", "").split(".")[0];
                    const b = this._sharedTex.get(_);
                    b ? (c.material._albedoTexture = b,
                    b.xReferenceCount++) : (this._sharedTex.set(_, d),
                    s.textures[0].xReferenceCount = 1)
                }
            }
        }
        ),
        s.xReferenceCount = 0,
        this.containers.set(o, s),
        Promise.resolve(s)) : Promise.reject("glb file load failed"),
        s.xReferenceCount = 0,
        this.containers.set(o, s),
        Promise.resolve(s)) : Promise.reject("glb file load failed"))
    }
    _loadGltfFromBlob(e, i, o, s) {
        return new Promise((c,d)=>{
            const _ = [];
            let b = this._getSourceKey(i, o)
              , k = this.getGltfPath(b);
            if (!k && this.fillEmptyLod && (o = 0,
            b = this._getSourceKey(i, o),
            k = this.getGltfPath(b)),
            !k)
                return d(`[Engine] gltf path incorrect ${b},cancel.`);
            const j = this.mshPath.get(b + ".gltf");
            if (!j)
                return d("cannot find asset mshPath");
            const $ = this.binPath.get(b + ".bin");
            if (!$)
                return d("cannot find asset binPath");
            if (!s) {
                const tt = this.meshTexList.get(i);
                if (!tt || tt.length == 0)
                    return d("cannot find texture");
                s = tt[0]
            }
            const _e = this.texPath.get(s + ".png");
            if (!_e)
                return d();
            const et = this.texPath.get(s + "-astc.ktx");
            if (!et)
                return d();
            _.push(this._blobMapping(e, j)),
            _.push(this._blobMapping(e, $)),
            _.push(this._blobMapping(e, _e)),
            _.push(this._blobMapping(e, et)),
            Promise.all(_).then(()=>{
                const tt = k.replace(b + ".gltf", "");
                SceneLoader.LoadAssetContainerAsync(tt, b + ".gltf", e.Scene, null, ".gltf").then(rt=>{
                    var nt;
                    this.containers.set(k, rt),
                    rt.addAllToScene(),
                    rt.meshes.forEach(ot=>{
                        ot.setEnabled(!1)
                    }
                    );
                    const it = this._sharedTex.get(i);
                    it ? ((nt = rt.meshes[1].material._albedoTexture) == null || nt.dispose(),
                    rt.meshes[1].material._albedoTexture = it) : this._sharedTex.set(i, rt.meshes[1].material._albedoTexture),
                    c(rt)
                }
                )
            }
            )
        }
        )
    }
    _blobMapping(e, i) {
        return new Promise((o,s)=>{
            e.urlTransformer(i).then(c=>c ? (this._mappings.set(i, c),
            o(i)) : s(`[Engine] url urlTransformer parse error ${i}`))
        }
        )
    }
}
const avatarLoader = new XAvatarLoader
  , log$J = new Logger$1("AnimationController");
class XAnimationController {
    constructor(e) {
        this.iBodyAnim = void 0,
        this.animations = [],
        this.defaultAnimation = "Idle",
        this.onPlay = "Idle",
        this.loop = !0,
        this.animationExtras = [],
        this.enableBlend = !1,
        this.enableSkLod = !1,
        this._boneMap = new Map,
        this._lodMask = new Map,
        this.activeFaceAnimation = void 0,
        this.iFaceAnim = void 0,
        this.onPlayObservable = new Observable,
        this.playAnimation = (i,o,s=0,c,d,_)=>new Promise((b,k)=>{
            if (this._isPlaying(i, s) || (this._registerAnimInfo(i, o, s, c, d, _),
            !this._isAnimate()))
                return b(null);
            this._prerocess(i, o),
            this._avatar.avatarManager.loadAnimation(this._avatar.avatarType, i).then(j=>{
                if (!j)
                    return k(new AvatarAnimationError("animation group does not exist"));
                const $ = this._mappingSkeleton(j);
                if (!$)
                    return k(new AvatarAnimationError("mapping animation failed"));
                if ($ && this._isAnimationValid($))
                    return $.dispose(),
                    k(new AvatarAnimationError("mapping animation failed"));
                if (this.enableSkLod && this.skeletonMask($, s),
                this.detachAnimation(s),
                s == 0 ? this.iBodyAnim.animGroup = $ : s == 1 && (this.iFaceAnim.animGroup = $),
                !this._playAnimation(s))
                    return k(new AvatarAnimationError("[Engine] play animation failed, animtion resource does not match current character"));
                this._playEffect(),
                this.postObserver = $.onAnimationEndObservable.addOnce(()=>(this._postprocess(s),
                b(null)))
            }
            )
        }
        ),
        this.stopAnimation = (i=0)=>{
            var o, s, c, d;
            switch (i) {
            case 0:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((o = this.iBodyAnim) == null || o.animGroup.stop());
                break;
            case 1:
                this.iFaceAnim && this.iFaceAnim.animGroup && ((s = this.iFaceAnim) == null || s.animGroup.stop());
                break;
            case 2:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((c = this.iBodyAnim) == null || c.animGroup.stop()),
                this.iFaceAnim && this.iFaceAnim.animGroup && ((d = this.iFaceAnim) == null || d.animGroup.stop());
                break
            }
        }
        ,
        this.pauseAnimation = (i=0)=>{
            var o, s, c, d;
            switch (i) {
            case 0:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((o = this.iBodyAnim) == null || o.animGroup.pause());
                break;
            case 1:
                this.iFaceAnim && this.iFaceAnim.animGroup && ((s = this.iFaceAnim) == null || s.animGroup.pause());
                break;
            case 2:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((c = this.iBodyAnim) == null || c.animGroup.pause()),
                this.iFaceAnim && this.iFaceAnim.animGroup && ((d = this.iFaceAnim) == null || d.animGroup.pause());
                break
            }
        }
        ,
        this.resetAnimation = (i=0)=>{
            var o, s, c, d;
            switch (i) {
            case 0:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((o = this.iBodyAnim) == null || o.animGroup.reset());
                break;
            case 1:
                this.iFaceAnim && this.iFaceAnim.animGroup && ((s = this.iFaceAnim) == null || s.animGroup.reset());
                break;
            case 2:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((c = this.iBodyAnim) == null || c.animGroup.reset()),
                this.iFaceAnim && this.iFaceAnim.animGroup && ((d = this.iFaceAnim) == null || d.animGroup.reset());
                break
            }
        }
        ,
        this._avatar = e,
        this._scene = e.avatarManager.scene,
        this.animationExtras.push(action.Cheering.animName),
        this._boneMap = new Map
    }
    _isPlaying(e, i) {
        return i == 0 && this.iBodyAnim != null && this.iBodyAnim.animGroup && e == this.iBodyAnim.name ? !0 : !!(i == 1 && this.iFaceAnim != null && this.iFaceAnim.animGroup && e == this.iFaceAnim.name)
    }
    activeAnimation(e=0) {
        var i, o;
        switch (e) {
        case 0:
            return (i = this.iBodyAnim) == null ? void 0 : i.animGroup;
        case 1:
            return (o = this.iFaceAnim) == null ? void 0 : o.animGroup;
        default:
            return
        }
    }
    enableAnimationBlend(e=.1, i=0) {
        var o, s, c, d;
        if (i == 0 && ((o = this.iBodyAnim) == null ? void 0 : o.animGroup))
            for (const _ of (s = this.iBodyAnim) == null ? void 0 : s.animGroup.targetedAnimations)
                _.animation.enableBlending = !0,
                _.animation.blendingSpeed = e;
        else if (i == 0 && ((c = this.iFaceAnim) == null ? void 0 : c.animGroup))
            for (const _ of (d = this.iFaceAnim) == null ? void 0 : d.animGroup.targetedAnimations)
                _.animation.enableBlending = !0,
                _.animation.blendingSpeed = e
    }
    disableAnimationBlend(e=0) {
        var i, o, s, c;
        if (e == 0 && ((i = this.iBodyAnim) == null ? void 0 : i.animGroup))
            for (const d of (o = this.iBodyAnim) == null ? void 0 : o.animGroup.targetedAnimations)
                d.animation.enableBlending = !1;
        else if (e == 0 && ((s = this.iFaceAnim) == null ? void 0 : s.animGroup))
            for (const d of (c = this.iFaceAnim) == null ? void 0 : c.animGroup.targetedAnimations)
                d.animation.enableBlending = !1
    }
    skeletonMask(e, i=0) {
        if (i == 0) {
            const o = this._lodMask.get(this._avatar.distLevel);
            if (o)
                for (let s = 0; s < e.targetedAnimations.length; ++s)
                    o.includes(e.targetedAnimations[s].target.name) || (e.targetedAnimations.splice(s, 1),
                    s--);
            return !0
        }
        return !1
    }
    detachAnimation(e=2) {
        var i, o;
        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--,
            (i = this.iBodyAnim) == null || i.animGroup.stop(),
            (o = this.iBodyAnim) == null || o.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, i) {
        return avatarLoader.animations.get(getAnimationKey(i, e))
    }
    _mappingSkeleton(e) {
        if (e) {
            const i = e.clone(e.name, o=>{
                var c, d, _;
                const s = o.name.split(" ").length > 2 ? o.name.split(" ")[2] : o.name;
                if (this._boneMap.size === ((c = this._avatar.skeleton) == null ? void 0 : c.bones.length))
                    return this._boneMap.get(s);
                {
                    const b = (_ = (d = this._avatar.skeleton) == null ? void 0 : d.bones.find(k=>k.name === o.name || k.name === o.name.split(" ")[2])) == null ? void 0 : _.getTransformNode();
                    return b && (b.name = s,
                    this._boneMap.set(s, b)),
                    b
                }
            }
            );
            return i._parentContainer = e._parentContainer,
            i
        } else
            return
    }
    removeAnimation(e) {
        const i = avatarLoader.containers.get(e.name);
        i && (i.dispose(),
        avatarLoader.containers.delete(e.name),
        avatarLoader.animations.delete(getAnimationKey(e.name, e.skType)))
    }
    _setPosition(e, i) {
        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, i, o=0, s, c, d) {
        const _ = {
            name: e,
            skType: this._avatar.avatarType,
            loop: i,
            playSpeed: s,
            currentFrame: 0,
            startFrame: c,
            endFrame: d
        };
        o == 0 ? this.iBodyAnim == null ? this.iBodyAnim = _ : (this.iBodyAnim.name = e,
        this.iBodyAnim.skType = this._avatar.avatarType,
        this.iBodyAnim.loop = i,
        this.iBodyAnim.playSpeed = s,
        this.iBodyAnim.currentFrame = 0,
        this.iBodyAnim.startFrame = c,
        this.iBodyAnim.endFrame = d) : o == 1 && (this.iFaceAnim == null ? this.iFaceAnim = _ : (this.iFaceAnim.name = e,
        this.iFaceAnim.skType = this._avatar.avatarType,
        this.iFaceAnim.loop = i,
        this.iFaceAnim.playSpeed = s,
        this.iFaceAnim.currentFrame = 0,
        this.iFaceAnim.startFrame = c,
        this.iFaceAnim.endFrame = d)),
        this.onPlay = e,
        this.loop = i
    }
    _isAnimate() {
        var e;
        return !(!this._avatar.isRender || !this._avatar.skeleton || ((e = this._avatar.rootNode) == null ? void 0 : e.getChildMeshes().length) == 0)
    }
    _prerocess(e, i) {
        this._avatar.isRayCastEnable && this._setPosition(e, i),
        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(i=>{
            this._avatar.attachExtraProp(i.obj, i.bone, new Vector3(i.offset.x,i.offset.y,i.offset.z), new Vector3(i.rotate.x,i.rotate.y,i.rotate.z)),
            this._avatar.showExtra(i.obj)
        }
        )
    }
    _playAnimation(e=0) {
        var i, o;
        return e == 0 && this.iBodyAnim && ((i = this.iBodyAnim) == null ? void 0 : i.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 && ((o = this.iFaceAnim) == null ? void 0 : o.animGroup) ? (this.iFaceAnim.animGroup.start(this.loop, this.iFaceAnim.playSpeed, this.iFaceAnim.startFrame, this.iFaceAnim.endFrame, !1),
        !0) : !1
    }
    _postprocess(e) {
        var o, s;
        let i;
        e == 0 ? i = (o = this.iBodyAnim) == null ? void 0 : o.name : e == 1 && (i = (s = this.iFaceAnim) == null ? void 0 : s.name),
        i === action.Cheering.animName && this._avatar.disposeExtra()
    }
    _isAnimationValid(e) {
        for (let i = 0; i < e.targetedAnimations.length; ++i)
            if (e.targetedAnimations[i].target)
                return !1;
        return !0
    }
}
const log$I = new Logger$1("XAvatarComopnent");
class XAvatarComopnent {
    constructor() {
        this.resourceIdList = [],
        this.skeleton = void 0,
        this.extraProp = void 0,
        this.extras = [],
        this.body = void 0,
        this.accessories = new Map
    }
    addBodyComp(e, i) {
        return !e.rootNode || i.root.getChildMeshes().length === 0 ? (i.isRender = !1,
        !1) : (this.body = i,
        this.body.root.parent = e.rootNode,
        i.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 = i.skeleton,
        !0)
    }
    addClothesComp(e, i) {
        return !e.rootNode || !this.skeleton || !i.root ? (i.isRender = !1,
        !1) : (i.root.xtype = EMeshType.XAvatar,
        i.root.xid = e.id,
        i.isRender = !0,
        i.root.parent = e.rootNode.getChildMeshes()[0],
        this.resourceIdList.push(i),
        i.root.skeleton = this.skeleton,
        i.root.getChildMeshes().forEach(o=>{
            o.skeleton = this.skeleton
        }
        ),
        !0)
    }
    clearClothesComp(e) {
        e.root.getChildMeshes().forEach(i=>{
            i.skeleton = null,
            i.dispose(),
            i.xid = void 0
        }
        ),
        e.root.dispose(),
        this.resourceIdList = this.resourceIdList.filter(i=>i.uId != e.uId)
    }
    clearAllClothesComps() {
        this.resourceIdList.forEach(e=>{
            var i;
            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(o=>{
                o.skeleton = null,
                o.dispose()
            }
            ),
            (i = e.root.skeleton) == null || i.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$I.warn("[Engine] no body to dispose")
    }
    async attachPendant(e, i) {
        return Promise.resolve(avatarLoader.pullAndLoadXObject(e.avatarManager.sceneManager, i).then(o=>{
            const s = o
              , c = this.accessories.get(s.pointId);
            return c ? (c.dispose(),
            this.accessories.set(s.pointId, s),
            log$I.warn("[Engine] \u8BE5\u6302\u70B9\u5F53\u524D\u88AB\u5360\u7528\uFF0C\u5DF2\u66FF\u6362\u8BE5\u6302\u70B9")) : this.accessories.set(s.pointId, s),
            s.attachTo(e),
            s
        }
        ))
    }
    detachPendant(e, i=!0) {
        const o = this.accessories.get(e);
        o && (o.dispose(),
        this.accessories.delete(e))
    }
    changeClothesComp(e, i, o, s, c) {
        return new Promise(d=>{
            if (this.resourceIdList.some(_=>_.name === i))
                return d();
            if (e.isHide || !e.isRender)
                c.concat(o).forEach(b=>{
                    e.clothesList = e.clothesList.filter(j=>j.type != b);
                    const k = {
                        type: o,
                        id: i,
                        url: s,
                        lod: 0
                    };
                    e.clothesList.push(k)
                }
                ),
                d();
            else {
                const _ = c.concat(o);
                e.avatarManager.loadDecoration(o, i, 0).then(b=>{
                    if (b) {
                        e.attachDecoration(b);
                        const k = {
                            type: o,
                            id: i,
                            url: s
                        };
                        e.clothesList.push(k),
                        b.root.setEnabled(!0),
                        _.forEach(j=>{
                            const $ = this.resourceIdList.filter(_e=>_e.type === j);
                            if ($.length > 1) {
                                const _e = $.filter(et=>et.name === i);
                                if (_e.length > 1)
                                    for (let et = 1; et < _e.length; ++et) {
                                        e.detachDecoration(_e[et]),
                                        e.clothesList = e.clothesList.filter(rt=>rt.id != _e[et].name);
                                        const tt = {
                                            type: o,
                                            id: i,
                                            url: s
                                        };
                                        e.clothesList.push(tt)
                                    }
                            }
                            $[0] && $[0].name != i && this._readyToDetach(e, o) && (e.detachDecoration($[0]),
                            e.clothesList = e.clothesList.filter(_e=>_e.id != $[0].name))
                        }
                        )
                    }
                    return d()
                }
                )
            }
        }
        )
    }
    _readyToDetach(e, i) {
        return !((i == "clothes" || i == "pants") && e.clothesList.filter(s=>s.type === "suit").length == 1 && (!e.clothesList.some(s=>s.type === "pants") || !e.clothesList.some(s=>s.type === "clothes")))
    }
    addDecoComp(e, i, o, s, c) {
        if (e.isRender) {
            const d = e.avatarManager.extraComps.get(i)
              , _ = d == null ? void 0 : d.clone(i, void 0);
            if (!d) {
                log$I.error("\u6CA1\u6709\u5BF9\u5E94\u7684\u7EC4\u4EF6");
                return
            }
            this.extras.push(_);
            const b = this.skeleton.bones.find(k=>k.name === o);
            _.position = s,
            _.rotation = c,
            _.attachToBone(b, e.rootNode.getChildMeshes()[0])
        }
    }
    showExtra(e) {
        this.extras.forEach(i=>{
            i.name.indexOf(e) > 0 && i.setEnabled(!0)
        }
        )
    }
    hideExtra(e) {
        this.extras.forEach(i=>{
            i.name.indexOf(e) > 0 && i.setEnabled(!1)
        }
        )
    }
    disposeExtra() {
        this.extras.forEach(e=>{
            e.dispose()
        }
        ),
        this.extras = []
    }
}
function LinearBezierCurves(a, e, i) {
    return Vector3.Lerp(e, i, 1 - a)
}
function QuadraticBezierCurves(a, e, i, o) {
    let s = LinearBezierCurves(a, e, i)
      , c = LinearBezierCurves(a, i, o);
    return LinearBezierCurves(a, s, c)
}
function CubicBezierCurves(a, e, i, o, s) {
    let c = QuadraticBezierCurves(a, e, i, o)
      , d = QuadraticBezierCurves(a, i, o, s);
    return LinearBezierCurves(a, c, d)
}
function CardinalMultiply(a, e, i, o, s, c) {
    var d, _, b, k;
    return d = a[0] * e + a[1] * i + a[2] * o + a[3] * s,
    _ = a[4] * e + a[5] * i + a[6] * o + a[7] * s,
    b = a[8] * e + a[9] * i + a[10] * o + a[11] * s,
    k = a[12] * e + a[13] * i + a[14] * o + a[15] * s,
    k + c * (b + c * (_ + c * d))
}
function CardinalCurves(a, e, i, o, s, c) {
    let d = new Array(16)
      , _ = c;
    return d[0] = -_,
    d[1] = 2 - _,
    d[2] = _ - 2,
    d[3] = _,
    d[4] = 2 * _,
    d[5] = _ - 3,
    d[8] = -_,
    d[9] = 0,
    d[12] = 0,
    d[13] = 1,
    d[6] = 3 - 2 * _,
    d[7] = -_,
    d[10] = _,
    d[11] = 0,
    d[14] = 0,
    d[15] = 0,
    new Vector3(CardinalMultiply(d, e.x, i.x, o.x, s.x, a),CardinalMultiply(d, e.y, i.y, o.y, s.x, a),CardinalMultiply(d, e.z, i.z, o.z, s.x, a))
}
function HermiteCurves(a, e, i, o, s) {
    let c = Math.pow(a, 3)
      , d = Math.pow(a, 2)
      , _ = 2 * c - 3 * d + 1
      , b = -2 * c + 3 * d
      , k = c - 2 * d + a
      , j = c - d
      , $ = e.multiplyByFloats(_, _, _)
      , _e = i.multiplyByFloats(b, b, b)
      , et = o.multiplyByFloats(k, k, k)
      , tt = s.multiplyByFloats(j, j, j);
    return $.add(_e.add(et).add(tt))
}
const log$H = new Logger$1("XStateMachine");
class XStateMachine {
    constructor(e) {
        this._observer = void 0,
        this._movingObserver = void 0,
        this._scene = e
    }
    rotateTo(e, i, o, s) {
        return new Promise((c,d)=>{
            var $;
            const _ = e.avatarManager.scene;
            if (o && e.setRotation(o),
            i == o)
                return c();
            e.priority === 0 && log$H.info(`avatar ${e.id} starts to rotate from ${o} to ${i}`);
            let b = 0;
            const k = 1e3 / 25
              , j = calcDistance3DAngle(i, e.rotation) / k;
            this._movingObserver && _.onBeforeRenderObservable.remove(this._movingObserver),
            ($ = e.controller) == null || $.playAnimation(s || "Walking", !0),
            this._movingObserver = _ == null ? void 0 : _.onBeforeRenderObservable.add(()=>{
                var _e;
                if (b < 1) {
                    if (!e.rootNode)
                        return e.setRotation(i),
                        c();
                    const et = Vector3.Lerp(e.rootNode.rotation, ue4Rotation2Xverse(i), b);
                    e.setRotation(xverseRotation2Ue4(et)),
                    b += k / (j * 1e3)
                } else
                    return _.onBeforeRenderObservable.remove(this._movingObserver),
                    (_e = e.controller) == null || _e.playAnimation("Idle", !0),
                    c()
            }
            )
        }
        )
    }
    _filterPathPoint(e) {
        let i = 0;
        const o = 1e-4;
        if (e.length <= 1)
            return e;
        for (; i < e.length - 1; )
            calcDistance3D(e[i], e[i + 1]) < o ? e.splice(i, 1) : i++;
        return e
    }
    moveToHermite(e, i, o, s, c, d, _) {
        return new Promise((b,k)=>{
            var ot;
            const j = e.avatarManager.scene;
            e.priority === 0 && log$H.info(`avatar ${e.id} starts to move from ${i} to ${o}`);
            let$ = 0;
            var _e = ue4Position2Xverse(i), et, tt = e.rootNode.rotation.y, rt = new Vector3(-Math.sin(tt) * c,0,-Math.cos(tt) * c), it = rt.clone();
            it.x = -it.x,
            it.z = -it.z;
            const nt = 1e3 / 25;
            this._movingObserver && j.onBeforeRenderObservable.remove(this._movingObserver),
            (ot = e.controller) == null || ot.playAnimation(d, !0),
            this._movingObserver = j == null ? void 0 : j.onBeforeRenderObservable.add(()=>{
                var st;
                et = HermiteCurves($, ue4Position2Xverse(i), ue4Position2Xverse(o), rt, it),
                e.rootNode.lookAt(et);
                const at = xverseRotation2Ue4({
                    x: e.rootNode.rotation.x,
                    y: e.rootNode.rotation.y,
                    z: e.rootNode.rotation.z
                });
                if (at && (at.roll = 0,
                at.pitch = 0,
                e.setRotation(at)),
                $ <= 1) {
                    if (e.setPosition(xversePosition2Ue4(_e), _),
                    !e.rootNode)
                        return e.setPosition(o, _),
                        b();
                    $ += nt / s,
                    _e = et.clone()
                } else
                    return e.setPosition(o, _),
                    j.onBeforeRenderObservable.remove(this._movingObserver),
                    (st = e.controller) == null || st.playAnimation("Idle", !0),
                    b()
            }
            )
        }
        )
    }
    moveToCardinal(e, i, o, s, c, d, _, b) {
        return new Promise((k,j)=>{
            var ot;
            const $ = e.avatarManager.scene;
            e.priority === 0 && log$H.info(`avatar ${e.id} starts to move from ${i} to ${o}`);
            let _e = 0
              , et = ue4Position2Xverse(d[0])
              , tt = ue4Position2Xverse(d[1]);
            var rt = ue4Position2Xverse(i), it;
            const nt = 1e3 / 25;
            this._movingObserver && $.onBeforeRenderObservable.remove(this._movingObserver),
            (ot = e.controller) == null || ot.playAnimation(c, !0),
            this._movingObserver = $ == null ? void 0 : $.onBeforeRenderObservable.add(()=>{
                var st;
                it = CardinalCurves(_e, ue4Position2Xverse(i), et, tt, ue4Position2Xverse(o), _),
                e.rootNode.lookAt(it);
                const at = xverseRotation2Ue4({
                    x: e.rootNode.rotation.x,
                    y: e.rootNode.rotation.y,
                    z: e.rootNode.rotation.z
                });
                if (at && (at.roll = 0,
                at.pitch = 0,
                e.setRotation(at)),
                _e <= 1) {
                    if (e.setPosition(xversePosition2Ue4(rt), b),
                    !e.rootNode)
                        return e.setPosition(o, b),
                        k();
                    _e += nt / s,
                    rt = it.clone()
                } else
                    return e.setPosition(o, b),
                    $.onBeforeRenderObservable.remove(this._movingObserver),
                    (st = e.controller) == null || st.playAnimation("Idle", !0),
                    k()
            }
            )
        }
        )
    }
    moveToBezier(e, i, o, s, c) {
        return new Promise((d,_)=>{
            var tt;
            i.length < 2 && _("[Engine input Bezier control points error]");
            const b = e.avatarManager.scene;
            e.priority === 0 && log$H.info(`avatar ${e.id} starts to move in Bezier Curve, from ${i[0]} to ${i[i.length - 1]}`);
            let k = 0
              , j = new Array;
            i.forEach(rt=>{
                j.push(ue4Position2Xverse(rt))
            }
            );
            var $ = j[0], _e;
            const et = 1e3 / 25;
            this._movingObserver && b.onBeforeRenderObservable.remove(this._movingObserver),
            (tt = e.controller) == null || tt.playAnimation(s, !0),
            this._movingObserver = b == null ? void 0 : b.onBeforeRenderObservable.add(()=>{
                var rt;
                switch (i.length) {
                case 2:
                    _e = LinearBezierCurves(k, j[0], j[1]);
                    break;
                case 3:
                    _e = QuadraticBezierCurves(k, j[0], j[1], j[2]);
                    break;
                case 4:
                    _e = CubicBezierCurves(k, j[0], j[1], j[2], j[3]);
                    break
                }
                if (k != 0) {
                    e.rootNode.lookAt(_e);
                    const it = xverseRotation2Ue4({
                        x: e.rootNode.rotation.x,
                        y: e.rootNode.rotation.y,
                        z: e.rootNode.rotation.z
                    });
                    it && (it.roll = 0,
                    it.pitch = 0,
                    e.setRotation(it))
                }
                if (k < 1) {
                    if (e.setPosition(xversePosition2Ue4($), c),
                    !e.rootNode)
                        return e.setPosition(j[j.length - 1], c),
                        d();
                    k += et / o,
                    $ = _e.clone()
                } else
                    return b.onBeforeRenderObservable.remove(this._movingObserver),
                    (rt = e.controller) == null || rt.playAnimation("Idle", !0),
                    d()
            }
            )
        }
        )
    }
    moveTo(e, i, o, s, c, d, _) {
        return new Promise((b,k)=>{
            var nt;
            const j = e.avatarManager.scene;
            e.priority === 0 && log$H.info(`avatar ${e.id} starts to move from ${i} to ${o}`);
            let$ = 0;
            d ? d = d.concat(o) : d = [o],
            d = this._filterPathPoint(d);
            let _e = i
              , et = d.shift();
            if (!et)
                return k("[Engine input path error]");
            let tt = calcDistance3D(_e, et) / s;
            const rt = 1e3 / 25;
            e.rootNode.lookAt(ue4Position2Xverse(et));
            const it = xverseRotation2Ue4({
                x: e.rootNode.rotation.x,
                y: e.rootNode.rotation.y,
                z: e.rootNode.rotation.z
            });
            it && (it.roll = 0,
            it.pitch = 0,
            e.setRotation(it)),
            this._movingObserver && j.onBeforeRenderObservable.remove(this._movingObserver),
            (nt = e.controller) == null || nt.playAnimation(c, !0),
            this._movingObserver = j == null ? void 0 : j.onBeforeRenderObservable.add(()=>{
                var ot;
                if ($ < 1) {
                    const at = Vector3.Lerp(ue4Position2Xverse(_e), ue4Position2Xverse(et), $);
                    if (e.setPosition(xversePosition2Ue4(at), _),
                    !e.rootNode)
                        return e.setPosition(o, _),
                        b();
                    $ += rt / (tt * 1e3)
                } else if (_e = et,
                et = d.shift(),
                et) {
                    tt = calcDistance3D(_e, et) / s,
                    e.rootNode.lookAt(ue4Position2Xverse(et));
                    const at = xverseRotation2Ue4({
                        x: e.rootNode.rotation.x,
                        y: e.rootNode.rotation.y,
                        z: e.rootNode.rotation.z
                    });
                    at && (at.roll = 0,
                    at.pitch = 0,
                    e.setRotation(at)),
                    $ = 0
                } else
                    return j.onBeforeRenderObservable.remove(this._movingObserver),
                    (ot = e.controller) == null || ot.playAnimation("Idle", !0),
                    b()
            }
            )
        }
        )
    }
    lookAt(e, i, o) {
        return new Promise(s=>{
            var et, tt;
            const c = ue4Position2Xverse(i)
              , d = 1e-4;
            if (calcDistance3D(e.position, i) <= d)
                return s();
            const _ = new Vector3(e.rootNode.rotation.x % (Math.PI * 2),e.rootNode.rotation.y % (Math.PI * 2),e.rootNode.rotation.z % (Math.PI * 2));
            (et = e.rootNode) == null || et.lookAt(c);
            const b = new Vector3(e.rootNode.rotation.x % (Math.PI * 2),(e.rootNode.rotation.y + Math.PI) % (Math.PI * 2),e.rootNode.rotation.z % (Math.PI * 2));
            if (e.rootNode.rotation = _,
            b.y - _.y > Math.PI && (b.y -= 2 * Math.PI),
            b.y - _.y < -Math.PI && (b.y += 2 * Math.PI),
            e.rootNode && Math.abs(_.x / _.z - b.x / b.z) <= d)
                return s();
            let k = 0;
            const j = o || 1 / 100
              , $ = (tt = e.rootNode) == null ? void 0 : tt.getScene()
              , _e = $ == null ? void 0 : $.onBeforeRenderObservable.add(()=>{
                var nt;
                const rt = (nt = e.controller) == null ? void 0 : nt.animations.find(ot=>ot.name == "Idle");
                (rt == null ? void 0 : rt.isPlaying) != !0 && (rt == null || rt.play());
                const it = Vector3.Lerp(_, b, k);
                if (k < 1) {
                    const ot = xverseRotation2Ue4({
                        x: it.x,
                        y: it.y - Math.PI,
                        z: it.z
                    });
                    ot && (ot.roll = 0,
                    ot.pitch = 0,
                    e.setRotation(ot)),
                    k += j
                } else
                    _e && $.onBeforeRenderObservable.remove(_e),
                    s()
            }
            )
        }
        )
    }
    sendObjectTo(e, i, o, s=2, c=10, d={
        x: 0,
        y: 0,
        z: 150
    }) {
        return new Promise((_,b)=>{
            var k;
            if (!o.loaded)
                b("Gift has not inited!");
            else {
                const j = (k = e.rootNode) == null ? void 0 : k.getScene();
                let$ = 0;
                const _e = 1 / (s * 25)
                  , et = _e
                  , tt = c / 100
                  , rt = 8 * tt * _e * _e;
                let it = .5 * rt / _e
                  , nt = ue4Position2Xverse(e.position);
                const ot = ue4Position2Xverse(d)
                  , at = ue4Position2Xverse(e.position)
                  , st = j == null ? void 0 : j.onBeforeRenderObservable.add(()=>{
                    (!i || !e.position || !i.position) && (st && j.onBeforeRenderObservable.remove(st),
                    b("Invalid receiver when shoot gift!")),
                    o.loaded || (st && j.onBeforeRenderObservable.remove(st),
                    _());
                    const ut = ue4Position2Xverse(i.position)
                      , ct = new Vector3((ut.x - at.x) * _e,it,(ut.z - at.z) * _e);
                    it = it - rt,
                    $ < 1 ? (nt = nt.add(ct),
                    o.setPositionVector(nt.add(ot)),
                    $ += et) : (_(),
                    st && j.onBeforeRenderObservable.remove(st))
                }
                )
            }
        }
        )
    }
    roll(e, i, o, s) {
        var c, d;
        this._observer && ((c = this._scene) == null || c.onBeforeRenderObservable.remove(this._observer)),
        i && (o = o != null ? o : 1,
        s = s != null ? s : 1,
        this._observer = (d = this._scene) == null ? void 0 : d.onBeforeRenderObservable.add(()=>{
            e.rootNode.rotation.y += o * .1 * s,
            e.rootNode.rotation.y %= Math.PI * 2
        }
        ))
    }
    disposeObsever() {
        this._movingObserver && this._scene.onBeforeRenderObservable.remove(this._movingObserver)
    }
}
class PoolObject {
    constructor(e, i, o, s=!0) {
        this.data = e,
        this.nextFree = i,
        this.previousFree = o,
        this.free = s
    }
    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, i, o, s, ...c) {
        this._pool = [],
        this.objCreator = e,
        this.objReseter = i;
        for (let d = 0; d < s; d++)
            this.addNewObject(this.newPoolObject(...c));
        this.capacity = o
    }
    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 i = this.nextFree ? this.nextFree : this.addNewObject(this.newPoolObject(...e));
        return i.free = !1,
        this.nextFree = i.nextFree,
        this.nextFree || (this.lastFree = null),
        i
    }
    newPoolObject(...e) {
        const i = this.objCreator(...e);
        return new PoolObject(i,this.nextFree,this.lastFree)
    }
    releaseAll() {
        this._pool.forEach(e=>this.release(e))
    }
    clean(e=0, ...i) {
        let o = this.nextFree;
        if (!o)
            return;
        let s = 0;
        for (; o; )
            s += 1,
            o = o.nextFree;
        let c = !1;
        if (s > e && this._pool.length > this.capacity && (c = !0),
        c)
            for (o = this.nextFree; o; ) {
                o.free = !1,
                this.nextFree = o.nextFree;
                const d = this._pool.indexOf(o);
                this._pool.splice(d, 1),
                this.nextFree || (this.lastFree = null),
                o == null || o.dispose(),
                o = this.nextFree
            }
    }
}
const texRootDir = "https://app-asset-1258211750.file.myqcloud.com/1/textures/"
  , _XBillboardManager = class {
    constructor(a) {
        this.billboardMap = new Map,
        this.userBackGroundBlob = new Array,
        this.npcBackGroundBlob = new Array,
        this._updateLoopObserver = void 0,
        this.sceneManager = a,
        this.billboardPool = new Pool(this.createBillboardAsset,this.resetBillboardAsset,0,60,this.sceneManager.Scene,!1),
        this.tickInterval = 250;
        let e = 0;
        this.tickObserver = this.sceneManager.Scene.onAfterRenderObservable.add(()=>{
            e += 1,
            e == this.tickInterval && (this.tick(),
            e = 0)
        }
        ),
        this.launchBillboardStatusLoop()
    }
    tick() {
        this.billboardPool.clean(0, this.sceneManager.Scene, !1)
    }
    createBillboardAsset(a, e=!1) {
        const i = MeshBuilder.CreatePlane("billboard-", {
            height: .001,
            width: .001,
            sideOrientation: Mesh.DOUBLESIDE
        }, a);
        i.isPickable = !0,
        i.setEnabled(!1);
        const o = new DynamicTexture("billboard-tex-",{
            width: .001 + 1,
            height: .001 + 1
        },a,e,Texture.BILINEAR_SAMPLINGMODE);
        o.hasAlpha = !0;
        const s = new StandardMaterial("billboard-mat-",a);
        return s.diffuseTexture = o,
        s.emissiveColor = new Color3(.95,.95,.95),
        s.useAlphaFromDiffuseTexture = !0,
        i.material = s,
        i.billboardMode = Mesh.BILLBOARDMODE_Y,
        i.position.y = 0,
        i
    }
    resetBillboardAsset(a) {
        const e = a.data;
        return e.setEnabled(!1),
        e.isPickable = !1,
        a
    }
    async loadBackGroundTexToIDB() {
        _XBillboardManager.userBubbleUrls.forEach(i=>{
            this.sceneManager.urlTransformer(i).then(o=>{
                this.userBackGroundBlob.push(o)
            }
            )
        }
        ),
        _XBillboardManager.npcBubbleUrls.forEach(i=>{
            this.sceneManager.urlTransformer(i).then(o=>{
                this.npcBackGroundBlob.push(o)
            }
            )
        }
        )
    }
    addBillboardToMap(a, e) {
        this.billboardMap.set(a, e)
    }
    addBillboard(a, e, i) {
        let o = this.getBillboard(a);
        return o || (o = new XBillboard(this,e,i),
        this.addBillboardToMap(a, o)),
        o
    }
    generateStaticBillboard(a, {id: e="billboard", isUser: i, background: o, font: s="Arial", fontsize: c=40, fontcolor: d="#ffffff", fontstyle: _="600", linesize: b=16, linelimit: k, scale: j=1, width: $=.01, height: _e=.01, position: et={
        x: 0,
        y: 0,
        z: 0
    }}) {
        const tt = this.addBillboard(e, !1, !0);
        tt.getMesh() == null && tt.init(e, $, _e);
        let rt;
        i != null && (rt = i ? _XBillboardManager.userBubbleUrls : _XBillboardManager.npcBubbleUrls),
        tt && tt.getMesh() && (tt.DEFAULT_CONFIGS = {
            id: e,
            isUser: i,
            background: o,
            font: s,
            fontsize: c,
            fontcolor: d,
            fontstyle: _,
            linesize: b,
            linelimit: k,
            scale: j,
            width: $,
            height: _e,
            position: et
        },
        tt.drawBillboard({
            imageList: o || rt
        }, {
            texts: a,
            font: s,
            fontsize: c,
            fontcolor: d,
            fontstyle: _,
            linesize: b,
            linelimit: k
        }, {
            position: et,
            scale: j
        }),
        e && tt.setId(e),
        tt.setStatus(BillboardStatus.SHOW))
    }
    getBillboard(a) {
        return this.billboardMap.get(a)
    }
    toggle(a, e) {
        var i;
        (i = this.getBillboard(a)) == null || i.setStatus(e ? BillboardStatus.SHOW : BillboardStatus.HIDE)
    }
    removeBillboard(a) {
        const e = this.getBillboard(a);
        e && (e.setStatus(BillboardStatus.DISPOSE),
        this.billboardMap.delete(a))
    }
    launchBillboardStatusLoop() {
        this._updateLoopObserver = this.sceneManager.Scene.onBeforeRenderObservable.add(()=>{
            this.billboardMap.size <= 0 || this.billboardMap.forEach(a=>{
                a.stageChanged && (a.status == BillboardStatus.SHOW ? a.show() : a.status == BillboardStatus.HIDE ? a.hide() : (a.hide(),
                a.dispose()),
                a.stageChanged = !1)
            }
            )
        }
        )
    }
}
;
let XBillboardManager = _XBillboardManager;
XBillboardManager.alphaWidthMap = new Map;
XBillboardManager.userBubbleUrls = [texRootDir + "bubble01.png", texRootDir + "bubble02.png", texRootDir + "bubble03.png"];
XBillboardManager.npcBubbleUrls = [texRootDir + "bubble01_npc.png", texRootDir + "bubble02_npc.png", texRootDir + "bubble03_npc.png"];
const log$G = new Logger$1("XAvatarBillboardComponent");
class XAvatarBillboardComponent {
    constructor(e) {
        this._nickName = "",
        this._words = "",
        this._isNameVisible = !0,
        this._isBubbleVisible = !0,
        this._isGiftButtonsVisible = !1,
        this.withinVisualRange = !1,
        this._bubble = void 0,
        this._nameBoard = void 0,
        this._giftButtons = new Map,
        this._buttonTex = new Map,
        this._nameLinesLimit = 2,
        this._nameLengthPerLine = 16,
        this._pickBbox = null,
        this.bbox = void 0,
        this._height = .26,
        this._attachmentObservers = new Map,
        this.attachToAvatar = (i,o,s=!1,c={
            x: 0,
            y: 0,
            z: 0
        },d=!1,_)=>{
            const b = i.rootNode;
            if (this.bbox || i.getBbox(),
            o && b) {
                let k = this._attachmentObservers.get(o);
                if (k)
                    if (d)
                        this._scene.onBeforeRenderObservable.remove(k),
                        this._attachmentObservers.delete(o);
                    else
                        return;
                const j = ue4Position2Xverse(c);
                s ? (o.setParent(b),
                o.position = j) : (k = this._scene.onBeforeRenderObservable.add(()=>{
                    let$ = 0;
                    _ ? ($ = i.rootNode.rotation.y / Math.PI * 180 + 90,
                    i.rootNode.rotation.y && (o.rotation.y = i.rootNode.rotation.y)) : $ = i.avatarManager.sceneManager.cameraComponent.getCameraPose().rotation.yaw,
                    $ || ($ = 0);
                    const _e = new Vector3(0,this._height,0);
                    i.controller && i.controller.activeAnimation() && i.controller.activeAnimation().animatables[0] && (this._height = _e.y = (i.controller.activeAnimation().animatables[0].target.position.y * .01 - .66) * i.scale),
                    _e.y < .07 * i.scale && (_e.y = 0),
                    o.position.x = b.position.x + j.x * Math.sin($ * Math.PI / 180) + j.z * Math.cos($ * Math.PI / 180),
                    o.position.z = b.position.z + j.x * Math.cos($ * Math.PI / 180) - j.z * Math.sin($ * Math.PI / 180),
                    o.position.y = b.position.y + this.bbox.maximum.y + j.y + _e.y
                }
                ),
                this._attachmentObservers.set(o, k))
            } else
                log$G.error("avatar or attachment not found!")
        }
        ,
        this.detachFromAvatar = (i,o,s=!1)=>{
            const c = this._attachmentObservers.get(o);
            c && this._scene.onBeforeRenderObservable.remove(c),
            i.rootNode ? (o.setEnabled(!1),
            o.parent = null,
            s && o.dispose()) : log$G.error("avatar not found!")
        }
        ,
        this.getBbox = (i,o={})=>{
            const {isConst: s=!1, changeWithAvatar: c=!1} = o;
            let {localCenter: d={
                x: 0,
                y: 0,
                z: 75
            }, width: _=1.32, height: b=1.5, depth: k=.44} = o;
            if (c) {
                const j = i.scale;
                d = {
                    x: d.x * j,
                    y: d.y * j,
                    z: d.z * j
                },
                _ *= j,
                b *= j,
                k *= j
            }
            if (i.rootNode) {
                let j = new Vector3(0,0,0)
                  , $ = new Vector3(0,0,0);
                if (s) {
                    const et = ue4Position2Xverse(d);
                    j = j.add(et.add(new Vector3(-_ / 2,-b / 2,-k / 2))),
                    $ = $.add(et.add(new Vector3(_ / 2,b / 2,k / 2)))
                } else if (j = j.add(new Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)),
                $ = $.add(new Vector3(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY)),
                i.isRender) {
                    i.rootNode.getChildMeshes().forEach(rt=>{
                        const it = rt.getBoundingInfo().boundingBox.minimum
                          , nt = rt.getBoundingInfo().boundingBox.maximum;
                        j.x = Math.min(j.x, it.x),
                        $.x = Math.max($.x, nt.x),
                        j.y = Math.min(j.y, it.y),
                        $.y = Math.max($.y, nt.y),
                        j.z = Math.min(j.z, it.z),
                        $.z = Math.max($.z, nt.z)
                    }
                    );
                    const et = $.x - j.x
                      , tt = $.z - j.z;
                    j.x -= i.scale * et / 2,
                    $.x += i.scale * et / 2,
                    $.y *= i.scale,
                    j.z -= i.scale * tt / 2,
                    $.z += i.scale * tt / 2
                } else {
                    const et = i.avatarManager.getMainAvatar();
                    et && et.bbComponent.bbox && (j.x = et.bbComponent.bbox.minimum.x,
                    $.x = et.bbComponent.bbox.maximum.x,
                    j.y = et.bbComponent.bbox.minimum.y,
                    $.y = et.bbComponent.bbox.maximum.y,
                    j.z = et.bbComponent.bbox.minimum.z,
                    $.z = et.bbComponent.bbox.maximum.z)
                }
                const _e = i.rootNode.computeWorldMatrix(!0);
                this.bbox ? this.bbox.reConstruct(j, $, _e) : this.bbox = new BoundingBox(j,$,_e),
                this._pickBbox == null
            } else
                log$G.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) {
        var i;
        if (this.nameBoard && this.nameBoard.setStatus(e),
        e == BillboardStatus.DISPOSE) {
            const o = (i = this.nameBoard) == null ? void 0 : i.getMesh();
            if (o) {
                const s = this._attachmentObservers.get(o);
                s && (this._scene.onBeforeRenderObservable.remove(s),
                this._attachmentObservers.delete(o))
            }
        }
    }
    setBubbleStatus(e) {
        var i;
        if (this.bubble && this.bubble.setStatus(e),
        e == BillboardStatus.DISPOSE) {
            const o = (i = this.bubble) == null ? void 0 : i.getMesh();
            if (o) {
                const s = this._attachmentObservers.get(o);
                s && (this._scene.onBeforeRenderObservable.remove(s),
                this._attachmentObservers.delete(o))
            }
        }
    }
    setButtonsStatus(e) {
        this.giftButtons && this.giftButtons.size != 0 && this.giftButtons.forEach(i=>{
            if (i.setStatus(e),
            e == BillboardStatus.DISPOSE && i.getMesh()) {
                const o = i.getMesh();
                if (o) {
                    const s = this._attachmentObservers.get(o);
                    s && (this._scene.onBeforeRenderObservable.remove(s),
                    this._attachmentObservers.delete(o))
                }
            }
        }
        )
    }
    setGiftButtonsVisible(e) {
        this.setButtonsStatus(e ? BillboardStatus.SHOW : BillboardStatus.DISPOSE)
    }
    dispose(e) {
        this._attachmentObservers.forEach(i=>{
            this._scene.onBeforeRenderObservable.remove(i)
        }
        ),
        this._attachmentObservers.clear(),
        this.updateBillboardStatus(e, BillboardStatus.DISPOSE),
        this._buttonTex.clear(),
        this._pickBbox && (e.avatarManager.bboxMeshPool.release(this._pickBbox),
        this._pickBbox = null)
    }
    updateBillboardStatus(e, i) {
        this.bbox || e.getBbox(),
        e.isRender ? (e.setBubbleStatus(i),
        e.setButtonsStatus(i),
        e.setNicknameStatus(i)) : (e.setBubbleStatus(BillboardStatus.DISPOSE),
        e.setButtonsStatus(BillboardStatus.DISPOSE),
        e.enableNickname ? e.setNicknameStatus(i) : e.setNicknameStatus(BillboardStatus.DISPOSE))
    }
    disposeBillBoard(e) {
        this._attachmentObservers.forEach(i=>{
            this._scene.onBeforeRenderObservable.remove(i)
        }
        ),
        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, i) {
        e.rootNode && e.rootNode.getChildMeshes().forEach(o=>{
            o.isPickable = i
        }
        ),
        this._pickBbox && this._pickBbox.data && (this._pickBbox.data.isPickable = i)
    }
    initNameboard(e, i=1) {
        this._nameBoard == null && (this._nameBoard = e.avatarManager.sceneManager.billboardComponent.addBillboard("name-" + e.id, !1, !0)),
        this._nameBoard.init("nickname", i / 300, i / 300)
    }
    initBubble(e, i=1) {
        this._bubble == null && (this._bubble = e.avatarManager.sceneManager.billboardComponent.addBillboard("bubble-" + e.id, !1, !0)),
        e.isRender && this._bubble.init("bubble", i / 250, i / 250)
    }
    say(e, i=this._words, {id: o, isUser: s, background: c, font: d="Arial", fontsize: _=38, fontcolor: b="#ffffff", fontstyle: k="bold", linesize: j=22, linelimit: $, offsets: _e={
        x: 0,
        y: 0,
        z: 40
    }, scale: et, compensationZ: tt=11.2, reregistAnyway: rt=!0}) {
        (!this.bubble || this.bubble.getMesh() == null) && e.initBubble(),
        this._words = i;
        let it;
        s != null && (it = s ? XBillboardManager.userBubbleUrls : XBillboardManager.npcBubbleUrls),
        this._bubble && (this._bubble.DEFAULT_CONFIGS = {
            id: o,
            isUser: s,
            background: c || it,
            font: d,
            fontsize: _,
            fontcolor: b,
            fontstyle: k,
            linesize: j,
            linelimit: $,
            offsets: _e,
            scale: et,
            compensationZ: tt,
            reregistAnyway: rt
        },
        this._bubble.getMesh() && (e.avatarManager.enableBubble ? (this._bubble.drawBillboard({
            imageList: c || it
        }, {
            texts: this._words,
            font: d,
            fontsize: _,
            fontcolor: b,
            fontstyle: k,
            linesize: j
        }, {
            offsets: _e,
            scale: et,
            compensationZ: tt
        }),
        this.attachToAvatar(e, this._bubble.getMesh(), !1, this._bubble.offsets, rt)) : this.setBubbleStatus(BillboardStatus.DISPOSE),
        o && this._bubble.setId(o))),
        this.setButtonsStatus(BillboardStatus.DISPOSE)
    }
    silent() {
        this.setBubbleStatus(BillboardStatus.DISPOSE),
        this._words = ""
    }
    setNickName(e, i, {id: o, isUser: s, background: c, font: d="Arial", fontsize: _=40, fontcolor: b="#ffffff", fontstyle: k="bold", linesize: j=22, linelimit: $, offsets: _e={
        x: 0,
        y: 0,
        z: 15
    }, scale: et, compensationZ: tt=0, reregistAnyway: rt=!1}) {
        this._nickName = i,
        (!this.nameBoard || this.nameBoard.getMesh() == null) && this.initNameboard(e),
        this._nameBoard && this._nameBoard.getMesh() && (this._nameBoard.DEFAULT_CONFIGS = {
            id: o,
            isUser: s,
            background: c,
            font: d,
            fontsize: _,
            fontcolor: b,
            fontstyle: k,
            linesize: j,
            linelimit: $,
            offsets: _e,
            scale: et,
            compensationZ: tt,
            reregistAnyway: rt
        },
        e.avatarManager.enableNickname ? (this._nameBoard.drawBillboard({}, {
            texts: this._nickName,
            font: d,
            fontsize: _,
            fontcolor: b,
            fontstyle: k,
            linesize: j,
            linelimit: $
        }, {
            offsets: _e,
            scale: et,
            compensationZ: 0
        }),
        this.attachToAvatar(e, this._nameBoard.getMesh(), !1, this._nameBoard.offsets, rt)) : this.setNicknameStatus(BillboardStatus.DISPOSE),
        o && this._nameBoard.setId(o))
    }
    generateButtons(e, i=null, o, s=85) {
        if (i && (this._buttonTex = i,
        this.clearButtons()),
        this._buttonTex.size == 0)
            return;
        let c = (this._buttonTex.size - 1) / 2;
        this._buttonTex.forEach((d,_)=>{
            let b = this._giftButtons.get(_);
            b || (b = e.avatarManager.sceneManager.billboardComponent.addBillboard("button-" + _ + e.id, !0, !1),
            b.init(_, o / 240, o / 240));
            const k = {
                x: o * c * 70,
                y: 0,
                z: o * (s - 20 * (c * c))
            };
            b.drawBillboard({
                imageList: [d]
            }, {}, {
                offsets: k,
                scale: o
            }),
            this.attachToAvatar(e, b.getMesh(), !1, b.offsets, !0),
            this._giftButtons.set(_, b),
            c -= 1
        }
        ),
        this.setBubbleStatus(BillboardStatus.DISPOSE)
    }
    clearButtons() {
        this._giftButtons.forEach(e=>{
            e.dispose()
        }
        ),
        this._giftButtons.clear()
    }
    createPickBoundingbox(e, i) {
        const o = i.extendSize.x * 2
          , s = i.extendSize.y * 2
          , c = i.extendSize.z * 2
          , d = this._scene
          , _ = Math.max(o, c)
          , b = e.avatarManager.bboxMeshPool.getFree(d, _, s, _)
          , k = b.data;
        return k && (k.position = i.centerWorld,
        k.setEnabled(!1),
        k.isPickable = !0,
        k.xtype = EMeshType.XAvatar,
        k.xid = e.id),
        b
    }
}
const log$F = new Logger$1("Avatar")
  , castRayOffsetY = .01
  , castRayTeleportationOffset = 10;
class XAvatar {
    constructor({id: e, avatarType: i, priority: o, avatarManager: s, assets: c, status: d}) {
        this.id = "-1",
        this.priority = 0,
        this.isRender = !1,
        this.distLevel = 0,
        this.isInLoadingList = !1,
        this.isHide = !1,
        this.clothesList = [],
        this.isSelected = !1,
        this.pendingLod = !1,
        this._previousReceivedPosition = new Vector3(0,1e4,0),
        this.rootNode = void 0,
        this.distToCam = 1e11,
        this.enableNickname = !0,
        this.distance = 1e11,
        this.isCulling = !1,
        this.reslevel = 0,
        this.isInLoadingQueue = !1,
        this._scene = void 0,
        this._transparent = 0,
        this.hide = ()=>(this.isHide = !0,
        this._hide(),
        !this.isRender),
        this._show = ()=>{
            var _;
            this.isHide || (this.setIsPickable(!0),
            this.bbComponent._attachmentObservers.forEach((b,k)=>{
                k.setEnabled(!0)
            }
            ),
            this.priority == 0 && (this.rootNode.setEnabled(!0),
            this.isRender = !0,
            this.avatarManager._updateBillboardStatus(this, BillboardStatus.SHOW),
            this.component.accessories.forEach(b=>{
                b.rootComponent.setEnabled(!0)
            }
            ),
            (_ = this.controller) == null || _.playAnimation(this.controller.onPlay, this.controller.loop)),
            this.component.accessories.forEach(b=>{
                b.rootComponent.setEnabled(!0)
            }
            ))
        }
        ,
        this.show = ()=>(this.isHide = !1,
        this._show(),
        !!this.isRender),
        this.setAnimations = _=>{
            this.controller.animations = _
        }
        ,
        this.attachToAvatar = (_,b=!1,k={
            x: 0,
            y: 0,
            z: 0
        },j=!1,$,_e)=>this.bbComponent.attachToAvatar(this, _, b, k, j, _e),
        this.detachFromAvatar = (_,b=!1)=>this.bbComponent.detachFromAvatar(this, _, b),
        this.getBbox = (_={})=>this.bbComponent.getBbox(this, _),
        this.id = e,
        this._avatarManager = s,
        this._scene = this.avatarManager.scene,
        this.clothesList = c,
        this._avatarType = i,
        this.priority = o || 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 = d.avatarScale == null ? 1 : d.avatarScale,
        this._avatarRotation = d.avatarRotation == null ? {
            pitch: 0,
            yaw: 0,
            roll: 0
        } : d.avatarRotation,
        this._avatarPosition = d.avatarPosition == null ? {
            x: 0,
            y: 0,
            z: 0
        } : d.avatarPosition,
        this._isRayCastEnable = avatarSetting.isRayCastEnable,
        this.setPosition(this._avatarPosition, !0),
        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(i=>{
            this.distToCam < 50 ? i.visibility = 0 : i.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.bbComponent._attachmentObservers.forEach((e,i)=>{
            i.setEnabled(!1)
        }
        ),
        this.priority == 0 ? (this.rootNode.setEnabled(!1),
        this.isRender = !1,
        this.bbComponent.updateBillboardStatus(this, BillboardStatus.HIDE),
        this.component.accessories.forEach(e=>{
            e.rootComponent.setEnabled(!1)
        }
        )) : this.isRender && (this.avatarManager.currentLODUsers[this.distLevel]--,
        this.removeAvatarFromScene()),
        this.component.accessories.forEach(e=>{
            e.rootComponent.setEnabled(!1)
        }
        ))
    }
    rotate(e, i, o) {
        return this.stateMachine.roll(this, e, i, o)
    }
    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, i=!1) {
        if (this._avatarPosition = e,
        this.rootNode) {
            const o = ue4Position2Xverse(this._avatarPosition);
            let s = !1;
            this.avatarManager.getMainAvatar() && (this.id != this.avatarManager.getMainAvatar().id || (Math.abs(o.y - this._previousReceivedPosition.y) > castRayOffsetY && (s = !0),
            o.subtract(this._previousReceivedPosition).length() > castRayTeleportationOffset && (s = !0))),
            this._isRayCastEnable ? s || i ? this._castRay(e).then(c=>{
                this.rootNode.position = o,
                this.rootNode.position.y -= c
            }
            ).catch(c=>{
                Promise.reject(c)
            }
            ) : (this.rootNode.position.x = o.x,
            this.rootNode.position.z = o.z) : this.rootNode.position = o,
            this._previousReceivedPosition = o.clone()
        }
        return Promise.resolve(e)
    }
    setRotation(e) {
        if (this._avatarRotation = e,
        this.rootNode) {
            const i = {
                pitch: e.pitch,
                yaw: e.yaw + 180,
                roll: e.roll
            }
              , o = ue4Rotation2Xverse(i);
            this.rootNode.rotation = o
        }
    }
    setAvatarVisible(e) {
        this.rootNode && (this.rootNode.setEnabled(e),
        this.rootNode.getChildMeshes().forEach(i=>{
            i.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, i;
        this.isRender = !1,
        (e = this.controller) == null || e.detachAnimation(),
        this.component.dispose(this),
        (i = this.avatarManager.sceneManager) == null || i.lightComponent.removeShadow(this),
        this.component.accessories.forEach(o=>{
            o.rootComponent.setEnabled(!1)
        }
        )
    }
    removeAvatarFromScene() {
        this._removeAvatarFromScene(),
        this._disposeBillBoard()
    }
    _disposeBillBoard() {
        this.bbComponent.disposeBillBoard(this)
    }
    addComponent(e, i, o, s) {
        return i === "pendant" ? this.component.attachPendant(this, e) : this.component.changeClothesComp(this, e, i, o, s)
    }
    removeComponent(e, i) {
        if (e === "pendant")
            i ? this.component.detachPendant(i) : this.component.accessories.forEach((o,s)=>{
                this.component.detachPendant(s)
            }
            );
        else {
            const o = this.component.resourceIdList.find(s=>s.type == e);
            o && (this.detachDecoration(o),
            this.clothesList = this.clothesList.filter(s=>s.type != e))
        }
    }
    getComponentByType(e, i) {
        if (e === "pendant")
            if (i) {
                const o = this.component.accessories.get(i);
                return o || []
            } else
                return Array.from(this.component.accessories).map(o=>o[1]);
        else
            return this.component.resourceIdList.find(o=>o.type == e)
    }
    _castRay(e) {
        return new Promise((i,o)=>{
            var et;
            const s = ue4Position2Xverse(e)
              , c = new Vector3(0,-1,0)
              , d = 1.5 * this.scale
              , _ = 100 * d
              , b = d
              , k = new Vector3(s.x,s.y + b,+s.z)
              , j = new Ray(k,c,_)
              , $ = (et = this.avatarManager.sceneManager) == null ? void 0 : et.getGround(e);
            if (!$ || $.length <= 0)
                return log$F.warn(`\u89D2\u8272 id= ${this.id} \u627E\u4E0D\u5230\u5730\u9762\uFF0C\u5F53\u524D\u9AD8\u5EA6\u4E3A\u4E0B\u53D1\u9AD8\u5EA6`),
                i(0);
            let _e = j.intersectsMeshes($);
            if (_e.length > 0)
                return i(_e[0].distance - b);
            if (c.y = 1,
            _e = j.intersectsMeshes($),
            _e.length > 0)
                return i(-(_e[0].distance - b))
        }
        )
    }
    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, i, o) {
        return this.stateMachine.rotateTo(this, e, i, o)
    }
    faceTo(e, i) {
        return this.stateMachine.lookAt(this, e, i)
    }
    removeObserver() {
        this.stateMachine.disposeObsever()
    }
    moveHermite(e, i, o, s, c, d) {
        return this.stateMachine.moveToHermite(this, e, i, o, s, c, d)
    }
    moveCardinal(e, i, o, s, c, d, _=!1) {
        return this.stateMachine.moveToCardinal(this, e, i, o, s, c, d, _)
    }
    move(e, i, o, s, c, d=!1) {
        return this.stateMachine.moveTo(this, e, i, o, s, c, d)
    }
    initNameboard(e=1) {
        return this.bbComponent.initNameboard(this, e)
    }
    initBubble(e=1) {
        return this.bbComponent.initBubble(this, e)
    }
    say(e, {id: i, isUser: o, background: s, font: c="Arial", fontsize: d=38, fontcolor: _="#ffffff", fontstyle: b="bold", linesize: k=22, linelimit: j, offsets: $={
        x: 0,
        y: 0,
        z: 40
    }, scale: _e=this._avatarScale, compensationZ: et=11.2, reregistAnyway: tt=!0}) {
        return this.bbComponent.say(this, e, {
            id: i,
            isUser: o,
            background: s,
            font: c,
            fontsize: d,
            fontcolor: _,
            fontstyle: b,
            linesize: k,
            linelimit: j,
            offsets: $,
            scale: _e,
            compensationZ: et,
            reregistAnyway: tt
        })
    }
    silent() {
        return this.bbComponent.silent()
    }
    setNickName(e, {id: i, isUser: o, background: s, font: c="Arial", fontsize: d=40, fontcolor: _="#ffffff", fontstyle: b="bold", linesize: k=22, linelimit: j, offsets: $={
        x: 0,
        y: 0,
        z: 15
    }, scale: _e=this._avatarScale, compensationZ: et=0, reregistAnyway: tt=!1}) {
        return this.bbComponent.setNickName(this, e, {
            id: i,
            isUser: o,
            background: s,
            font: c,
            fontsize: d,
            fontcolor: _,
            fontstyle: b,
            linesize: k,
            linelimit: j,
            offsets: $,
            scale: _e,
            compensationZ: et,
            reregistAnyway: tt
        })
    }
    generateButtons(e=null, i=this._avatarScale, o=85) {
        return this.bbComponent.generateButtons(this, e, i, o)
    }
    clearButtons() {
        return this.bbComponent.clearButtons()
    }
    attachExtraProp(e, i, o, s) {
        return this.component.addDecoComp(this, e, i, o, s)
    }
    showExtra(e) {
        return this.component.showExtra(e)
    }
    hideExtra(e) {
        return this.component.hideExtra(e)
    }
    disposeExtra() {
        return this.component.disposeExtra()
    }
    getSkeletonPositionByName(e) {
        var i;
        if (this.skeleton) {
            const o = this.skeleton.bones.find(s=>s.name.replace("Clone of ", "") == e);
            if (o && o.getTransformNode() && ((i = o.getTransformNode()) == null ? void 0 : i.position)) {
                const s = o.getTransformNode().position;
                return xversePosition2Ue4({
                    x: s.x,
                    y: s.y,
                    z: s.z
                })
            }
        }
    }
    shootTo(e, i, o=2, s=10, c={
        x: 0,
        y: 0,
        z: 150
    }) {
        return this.stateMachine.sendObjectTo(this, e, i, o, s, c)
    }
}
const log$E = new Logger$1("AvatarManager");
var EAvatarRelationRank = (a=>(a[a.Self = 0] = "Self",
a[a.Npc = 1] = "Npc",
a[a.Friend = 2] = "Friend",
a[a.Stranger = 3] = "Stranger",
a[a.Robot = 4] = "Robot",
a[a.Unknown = 5] = "Unknown",
a))(EAvatarRelationRank || {});
class XAvatarManager {
    constructor(e) {
        this.characterMap = new Map,
        this.curAnimList = [],
        this.extraComps = new Map,
        this._mainUser = void 0,
        this._sceneManager = void 0,
        this.maxBillBoardDist = 0,
        this.maxAvatarNum = 0,
        this.currentLODUsers = [],
        this._distLevels = [],
        this._maxLODUsers = [],
        this._cullingDistance = 0,
        this._delayTime = 100,
        this._queueLength = -1,
        this._queue = [],
        this._processList = [],
        this._process = void 0,
        this._updateLoopObserver = void 0,
        this._enableNickname = !0,
        this._enableBubble = !0,
        this._defaultAnims = void 0,
        this._tickDispose = 0,
        this._disposeTime = 10,
        this.avatarLoader = avatarLoader,
        this.onThingsLoading = !1,
        this.compMap = new Map,
        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,0,this._sceneManager.Scene,0,0,0),
        this._tickInterval = 250;
        let i = 0;
        this._tickObserver = this._scene.onAfterRenderObservable.add(()=>{
            i += 1,
            i == this._tickInterval && (this.tick(),
            i = 0)
        }
        )
    }
    tick() {
        this.bboxMeshPool.clean(0)
    }
    createBboxAsset(e, i, o, s) {
        return MeshBuilder.CreateBox("avatarBbox", {
            width: i,
            height: o,
            depth: s
        }, e)
    }
    resetBboxAsset(e) {
        const i = e.data;
        return i.setEnabled(!1),
        i.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(i=>{
            e += i
        }
        ),
        e
    }
    curRenderNum() {
        let e = 0;
        return this.currentLODUsers.forEach(i=>{
            e += i
        }
        ),
        e
    }
    setLoDLevels(e) {
        this._distLevels = e
    }
    set cullingDistance(e) {
        this._cullingDistance = e
    }
    get cullingDistance() {
        return this._cullingDistance
    }
    getLoDLevels() {
        return this._distLevels
    }
    setLodUserLimits(e, i) {
        this._maxLODUsers.length > e && (this._maxLODUsers[e] = i)
    }
    setLodDist(e, i) {
        this._distLevels[e] = i
    }
    setMaxDistRange(e) {
        this._maxDistRange = e,
        this._distLevels[this._distLevels.length - 1] = e
    }
    get scene() {
        return this._scene
    }
    setMainAvatar(e) {
        var i;
        this._mainUser = (i = this.characterMap.get(0)) == null ? void 0 : i.get(e)
    }
    getMainAvatar() {
        return this._mainUser
    }
    get enableNickname() {
        return this._enableNickname
    }
    get enableBubble() {
        return this._enableBubble
    }
    enableAllNickname(e) {
        this._enableNickname = e,
        this.characterMap.forEach(i=>{
            i.forEach(o=>{
                e ? o.nameBoard && o.nickName.length > 0 && o.isRender && o.setNickName(o.nickName, o.nameBoard.DEFAULT_CONFIGS) : o.setNicknameStatus(BillboardStatus.DISPOSE)
            }
            )
        }
        )
    }
    enableAllBubbles(e) {
        this._enableBubble = e,
        this.characterMap.forEach(i=>{
            i.forEach(o=>{
                e ? o.bubble && o.words.length > 0 && o.isRender && o.say(o.words, o.bubble.DEFAULT_CONFIGS) : o.setBubbleStatus(BillboardStatus.DISPOSE)
            }
            )
        }
        )
    }
    getAvatarById(e) {
        let i;
        return this.characterMap.forEach((o,s)=>{
            o.get(e) && (i = o.get(e))
        }
        ),
        i
    }
    getAvatarNums() {
        let e = 0;
        return this.characterMap.forEach((i,o)=>{
            e += i.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: i, priority: o, avatarManager: s, assets: c, status: d}) {
        return new Promise((_,b)=>{
            if (this.getAvatarById(e))
                return b(new DuplicateAvatarIDError(`[Engine] cannot init avatar with the same id = ${e}`));
            if (this.getAvatarNums() > this.maxAvatarNum)
                return b(new ExceedMaxAvatarNumError(`[Engine] \u8D85\u51FA\u6700\u5927\u89D2\u8272\u9650\u5236 ${this.maxAvatarNum}`));
            const k = new XAvatar({
                id: e,
                avatarType: i,
                priority: o,
                avatarManager: s,
                assets: c,
                status: d
            });
            if (this.registerAvatar(k),
            o == 0)
                this.setMainAvatar(k.id),
                this.addAvatarToScene(k, 0).then(j=>(log$E.debug(`[Engine] avatar ${k.id} has been added to scene`),
                j ? (this._updateBillboardStatus(j, BillboardStatus.SHOW),
                setTimeout(()=>{
                    this.launchProcessLoadingLoop()
                }
                , this._delayTime),
                _(j)) : (k.removeAvatarFromScene(),
                b(new AvatarAssetLoadingError)))).catch(j=>(k.removeAvatarFromScene(),
                b(new AvatarAssetLoadingError(j))));
            else
                return _(k)
        }
        )
    }
    deleteAvatar(e) {
        return e.isRender ? (e.removeAvatarFromScene(),
        this.currentLODUsers[e.distLevel]--) : e.bbComponent.disposeBillBoard(e),
        this._processList = this._processList.filter(i=>i.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 i = 1; i < this._distLevels.length; ++i)
            if (e >= this._distLevels[i - 1] && e < this._distLevels[i])
                return i;
        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)),
        this._queueLength = 0,
        this._clear(this.compMap),
        this._process && (this._process.isInLoadingList = !1,
        this._process.removeAvatarFromScene(),
        this._process = void 0),
        this._processList.forEach(i=>{
            i.isInLoadingList = !1
        }
        ),
        this._processList = []
    }
    _distToMain(e) {
        var c;
        const i = (c = this._mainUser) == null ? void 0 : c.position
          , o = e.position
          , s = this.sceneManager.cameraComponent.MainCamera.position;
        if (o && s) {
            const d = this.sceneManager.cameraComponent.MainCamera.getFrontPosition(1).subtract(s)
              , _ = e.rootNode.position.subtract(s)
              , b = new Vector3(d.x,0,d.z).normalize()
              , k = new Vector3(_.x,0,_.z).normalize();
            let j = 1;
            if (b && k) {
                const $ = b.multiply(k);
                j = Math.acos($.x + $.y + $.z) < this.sceneManager.cameraComponent.getCameraHorizonFov() * .6 ? 1 : 1e11
            }
            return calcDistance3D(i || s, o) * j
        } else
            return log$E.warn("user position or camera position is not correct!"),
            1e11
    }
    _distToCamera(e) {
        var s;
        const i = (s = this._sceneManager) == null ? void 0 : s.cameraComponent.getCameraPose().position
          , o = e.position;
        return o && i ? calcDistance3D(i, o) : (log$E.warn("user position or camera position is not correct!"),
        1e11)
    }
    showAll(e) {
        this.characterMap.forEach((i,o)=>{
            e && o == 0 && i.forEach((s,c)=>{
                s.show()
            }
            ),
            o != 0 && i.forEach((s,c)=>{
                s.show()
            }
            )
        }
        )
    }
    hideAll(e) {
        this.characterMap.forEach((i,o)=>{
            e && o == 0 && i.forEach((s,c)=>{
                s.hide()
            }
            ),
            o != 0 && i.forEach((s,c)=>{
                s.hide()
            }
            )
        }
        )
    }
    _assemblyAvatar(e, i) {
        var s, c;
        const o = e.get(avatarSetting.body);
        if (o && !i.attachBody(o)) {
            i.isInLoadingList = !1,
            this._clear(e);
            return
        }
        for (const d of e)
            if (d[0] != avatarSetting.body && d[0] != avatarSetting.animations && !i.attachDecoration(d[1])) {
                i.isInLoadingList = !1,
                i.removeAvatarFromScene(),
                this._clear(e);
                return
            }
        i.isRender = !0,
        (s = i.controller) == null || s.playAnimation(i.controller.onPlay, i.controller.loop),
        (c = i.controller) == null || c.onPlayObservable.addOnce(()=>{
            var d, _;
            if (!this.getAvatarById(i.id)) {
                i.isInLoadingList = !1,
                i.removeAvatarFromScene(),
                this.currentLODUsers[i.distLevel]--;
                return
            }
            if (this.getAvatarById(i.id).rootNode.getChildMeshes().length < e.size) {
                log$E.error(`this avatar does not have complete components, render failed. current list ${(d = this.getAvatarById(i.id)) == null ? void 0 : d.clothesList},avatar: ${i.id},${i.nickName}`),
                i.isInLoadingList = !1,
                i.removeAvatarFromScene(),
                this.currentLODUsers[i.distLevel]--;
                return
            }
            i.setIsPickable(!0),
            i.isInLoadingList = !1,
            i.setAvatarVisible(!0),
            (_ = this._sceneManager) == null || _.lightComponent.setShadow(i),
            i.getBbox(),
            i.nameBoard && i.nickName.length > 0 && this._enableNickname && i.setNickName(i.nickName, i.nameBoard.DEFAULT_CONFIGS),
            i.component.accessories.forEach(b=>{
                b.rootComponent.setEnabled(!0)
            }
            ),
            i.bubble && i.words.length > 0 && i.say(i.words, i.bubble.DEFAULT_CONFIGS),
            log$E.debug(`[Engine] avatar ${i.id} has been added to scene, current number of users : ${this.currentLODUsers}`)
        }
        )
    }
    _disposeUnusedAssets() {
        this._tickDispose++,
        (this._tickDispose > this._disposeTime || avatarLoader.containers.size > 100) && (avatarLoader.disposeContainer(),
        this._tickDispose = 0)
    }
    _addResourcesToList(e, i) {
        return e.clothesList.forEach(o=>{
            o.lod = i,
            this._queue.push(o)
        }
        ),
        this._queue.push({
            type: avatarSetting.animations,
            id: this._defaultAnims
        }),
        this._queue.push({
            type: avatarSetting.body,
            id: e.avatarType,
            lod: i
        }),
        !0
    }
    _updateBillboardStatus(e, i) {
        e.bbComponent.updateBillboardStatus(e, i)
    }
    _processLayer(e) {
        const i = this.characterMap.get(e)
          , o = [];
        for (i == null || i.forEach(s=>{
            s.distToCam = this._distToCamera(s);
            const c = s.distToCam < this._cullingDistance;
            if (s.isRender && (!s.isHide && c ? s._hide_culling() : s._show_culling()),
            s.priority != 0) {
                s.distance = this._distToMain(s);
                let d = BillboardStatus.SHOW;
                s.distance < this._maxDistRange && (c ? d = BillboardStatus.HIDE : s._show_culling(),
                this._updateBillboardStatus(s, d)),
                s.isHide || (s.isInLoadingList ? this.currentLODUsers[s.distLevel]++ : o.push(s))
            }
        }
        ),
        o.sort((s,c)=>c.distance - s.distance); o.length > 0 && this.curRenderNum() < this.maxRenderNum(); ) {
            const s = o.pop();
            let c = this._checkLODLevel(s.distance)
              , d = !1;
            for (let _ = 0; _ < this._maxLODUsers.length; ++_)
                if (this.currentLODUsers[_] < this._maxLODUsers[_]) {
                    c = _,
                    d = !0;
                    break
                }
            if (!d || s.distance > this._maxDistRange) {
                if (s.isRender) {
                    s._removeAvatarFromScene();
                    let _ = BillboardStatus.HIDE;
                    s.distance < this._maxDistRange && (_ = BillboardStatus.SHOW),
                    this._updateBillboardStatus(s, _)
                }
                break
            }
            c != s.distLevel ? (s.isRender && (s.pendingLod = !0),
            s.distLevel = c,
            this._processList.push(s),
            s.isInLoadingList = !0) : s.isRender || (this._processList.push(s),
            s.isInLoadingList = !0),
            this.currentLODUsers[c]++
        }
        return this.curRenderNum() >= this.maxRenderNum() && o.forEach(s=>{
            if (s.isRender) {
                s._removeAvatarFromScene();
                let c = BillboardStatus.HIDE;
                s.distance < this._maxDistRange && (c = BillboardStatus.SHOW),
                this._updateBillboardStatus(s, c)
            }
        }
        ),
        this.curRenderNum() < this.maxRenderNum()
    }
    _updateAvatar() {
        this.currentLODUsers = [0, 0, 0];
        const e = [5, 4, 3, 2, 1, 0];
        for (; e.length > 0; ) {
            const i = e.pop();
            if (!this._processLayer(i)) {
                e.forEach(s=>{
                    var c;
                    (c = this.characterMap.get(s)) == null || c.forEach(d=>{
                        d.distance = this._distToMain(d);
                        let _ = BillboardStatus.HIDE;
                        d.distToCam < this._maxDistRange && (_ = BillboardStatus.SHOW,
                        d.isRender && d._removeAvatarFromScene()),
                        this._updateBillboardStatus(d, _)
                    }
                    )
                }
                );
                break
            }
        }
    }
    _updateAvatarStatus() {
        this._updateLoopObserver = this.scene.onBeforeRenderObservable.add(()=>{
            var e;
            if (!(this.getAvatarNums() <= 0)) {
                if (!this._process && this._processList.length == 0 && this._updateAvatar(),
                !this._process && this._processList.length > 0) {
                    const i = this._processList.shift();
                    i != this._process && !i.isCulling ? this._addResourcesToList(i, i.distLevel) ? (this._process = i,
                    this._queueLength = this._queue.length) : (this._process = void 0,
                    this._queue = [],
                    i.isInLoadingList = !1) : i.isInLoadingList = !1
                }
                if (this.compMap.size === this._queueLength && this._process) {
                    this._process.pendingLod && (this._process.pendingLod = !1,
                    this._process._removeAvatarFromScene());
                    const i = Date.now();
                    this._assemblyAvatar(this.compMap, this._process),
                    (e = this._sceneManager) == null || e.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - i),
                    this._updateBillboardStatus(this._process, BillboardStatus.SHOW),
                    this.compMap.clear(),
                    this._queue = [],
                    this._process.isInLoadingList = !1,
                    this._process = void 0
                }
                this._disposeUnusedAssets(),
                this._loadResByList(this.compMap)
            }
        }
        )
    }
    _clear(e) {
        e.forEach((i,o)=>{
            o == avatarSetting.body && (i.root._parentContainer ? i.root._parentContainer.xReferenceCount-- : i.root.getChildMeshes().forEach(s=>{
                s.dispose()
            }
            )),
            (o == avatarSetting.clothes || o == avatarSetting.hair || o == avatarSetting.head || o == avatarSetting.pants || o == avatarSetting.head || o == avatarSetting.suit) && (i.root._parentContainer ? i.root._parentContainer.xReferenceCount-- : i.root.dispose())
        }
        )
    }
    _loadResByList(e) {
        let i = 0;
        const o = 5;
        if (!this._process) {
            e.clear();
            return
        }
        for (; !this.onThingsLoading && i < o && this._queue.length > 0; ) {
            const s = Date.now()
              , c = this._queue.pop();
            setTimeout(()=>{
                c ? c.type === avatarSetting.body ? (this.onThingsLoading = !0,
                this.loadBody(c.type, c.id, c.lod).then(d=>{
                    d && e.set(avatarSetting.body, d),
                    i += Date.now() - s,
                    this.onThingsLoading = !1
                }
                ).catch(d=>{
                    this._process && (this._process.isHide = !0,
                    this.currentLODUsers[this._process.distLevel]--,
                    this._clear(e),
                    this._queue = [],
                    this._process.isInLoadingList = !1,
                    this._process = void 0,
                    i += 100,
                    this.onThingsLoading = !1),
                    log$E.warn(`[Engine] body ${c.id} uri error, type ${c.type}, avatar has been hided` + d)
                }
                )) : c.type === avatarSetting.animations ? this.loadAnimation(this._process.avatarType, c.id).then(d=>{
                    d && e.set(avatarSetting.animations, d),
                    i += Date.now() - s,
                    this.onThingsLoading = !1
                }
                ).catch(d=>{
                    this._process && (this._process.isHide = !0,
                    this.currentLODUsers[this._process.distLevel]--,
                    this._clear(e),
                    this._queue = [],
                    this._process.isInLoadingList = !1,
                    this._process = void 0,
                    i += 100,
                    this.onThingsLoading = !1),
                    log$E.warn(`animation  ${c.id} uri error, type ${c.type}, avatar has been hided` + d)
                }
                ) : this.loadDecoration(c.type, c.id, c.lod).then(d=>{
                    d && e.set(d.type, d),
                    i += Date.now() - s,
                    this.onThingsLoading = !1
                }
                ).catch(d=>{
                    this._process && (this._process.isHide = !0,
                    this.currentLODUsers[this._process.distLevel]--,
                    this._clear(e),
                    this._queue = [],
                    this._process.isInLoadingList = !1,
                    this._process = void 0,
                    i += 100,
                    this.onThingsLoading = !1),
                    log$E.warn(`component ${c.id} uri error, type ${c.type}, avatar has been hided` + d)
                }
                ) : i += 100
            }
            , 0)
        }
    }
    _validateContainer(e) {
        return !e.meshes || e.meshes.length <= 1 ? (log$E.warn("import container has no valid meshes"),
        !1) : !e.skeletons || e.skeletons.length == 0 ? (log$E.warn("import container has no valid skeletons"),
        !1) : !0
    }
    _getAssetContainer(e, i) {
        return new Promise((o,s)=>{
            const c = this._getSourceKey(e, i || 0)
              , d = avatarLoader.containers.get(c);
            if (d)
                return o(d);
            avatarLoader.load(this.sceneManager, e, i).then(_=>_ ? this._validateContainer(_) ? (avatarLoader.containers.set(c, _),
            o(_)) : s(new ContainerLoadingFailedError(`[Engine] :: cannot load body type ${e}.`)) : s(new ContainerLoadingFailedError(`[Engine] container load failed cannot load body type ${e}.`))).catch(_=>s(new ContainerLoadingFailedError(`[Engine] ${_} :: cannot load body type ${e}.`)))
        }
        )
    }
    _clipContainerRes(e) {
        e.transformNodes = [],
        e.skeletons.forEach(i=>{
            i.dispose()
        }
        ),
        e.skeletons = []
    }
    loadBody(e, i, o) {
        return avatarLoader.load(this.sceneManager, i, o).then(s=>{
            if (s) {
                const c = s.instantiateModelsToScene();
                s.xReferenceCount++;
                const d = {
                    isRender: !1,
                    uId: Math.random(),
                    root: c.rootNodes[0],
                    skeletonType: e,
                    name: i,
                    animations: c.animationGroups,
                    skeleton: c.skeletons[0],
                    lod: o
                };
                return c.rootNodes[0]._parentContainer = s,
                c.rootNodes[0].setEnabled(!1),
                d
            } else
                return Promise.reject(new ContainerLoadingFailedError("[Engine] container failed instanciates failed"))
        }
        ).catch(()=>Promise.reject(new ContainerLoadingFailedError(`[Engine] body type ${e} instanciates failed`)))
    }
    updateAnimationLists(e, i) {
        return new Promise((o,s)=>(avatarLoader.avaliableAnimation.set(i, e),
        o()))
    }
    loadAnimation(e, i) {
        return avatarLoader.loadAnimRes(this.sceneManager, i, e).then(o=>{
            if (o) {
                let s;
                const c = this.avatarLoader.animations;
                return o.animationGroups.forEach(d=>{
                    d.stop(),
                    d.name === i && (s = d,
                    s.pContainer = o),
                    c.set(getAnimationKey(d.name, e), d)
                }
                ),
                this._clipContainerRes(o),
                o.xReferenceCount++,
                s
            } else
                return Promise.reject(new ContainerLoadingFailedError("[Engine] container failed instanciates failed"))
        }
        )
    }
    loadDecoration(e, i, o) {
        return avatarLoader.load(this.sceneManager, i, o).then(s=>{
            if (s) {
                if (s.meshes.length <= 1)
                    return console.error("\u3010\u5F02\u5E38\uFF0Ccontainer\u4E0D\u542Bmesh\u3011"),
                    Promise.reject(`\u3010\u5F02\u5E38\uFF0Ccontainer\u4E0D\u542Bmesh\u3011 ${i}`);
                const c = s.meshes[1].clone(s.meshes[1].name, null);
                if (!c)
                    return log$E.warn("[Engine] decoration does not exist!"),
                    null;
                const d = {
                    isRender: !1,
                    uId: Math.random(),
                    root: c,
                    type: e,
                    name: i,
                    isSelected: !1,
                    lod: o
                };
                if (s.xReferenceCount++,
                c._parentContainer = s,
                s.meshes.length > 1)
                    for (let _ = 2; _ < s.meshes.length; _++)
                        c.addChild(s.meshes[_].clone(s.meshes[_].name, null));
                return c.setEnabled(!1),
                d.isSelected = !0,
                d
            } else
                return Promise.reject(new ContainerLoadingFailedError("[Engine] container failed, instanciates failed."))
        }
        )
    }
    _getSourceKey(e, i) {
        return i && avatarSetting.lod[i] ? e + avatarSetting.lod[i].fileName.split(".")[0] : e
    }
    addAvatarToScene(e, i) {
        const o = Date.now();
        return this.loadBody(e.avatarType, e.avatarType, i).then(s=>{
            var c;
            return s ? (e.attachBody(s),
            s.animations.length > 0 ? (s.animations.forEach(d=>{
                d.stop()
            }
            ),
            e.setAnimations(s.animations),
            (c = e.controller) == null || c.playAnimation(e.controller.onPlay, !0),
            e.isRender = !0,
            e.isInLoadingList = !1,
            e.setAvatarVisible(!0),
            e) : this.loadAnimation(e.avatarType, this._defaultAnims).then(d=>{
                if (!d)
                    return e.removeAvatarFromScene(),
                    e.isInLoadingList = !1,
                    Promise.reject(new AvatarAnimationError);
                const _ = [];
                return e.clothesList.length > 0 && e.clothesList.forEach(b=>{
                    _.push(this.loadDecoration(b.type, b.id, i))
                }
                ),
                Promise.all(_).then(b=>{
                    var $, _e, et, tt;
                    b.forEach(rt=>{
                        if (rt && !rt.isRender)
                            e.attachDecoration(rt);
                        else {
                            e.isInLoadingList = !1,
                            e.removeAvatarFromScene(),
                            Promise.reject(new AvatarAssetLoadingError);
                            return
                        }
                    }
                    ),
                    e.isRender = !0,
                    ($ = e.controller) == null || $.playAnimation(e.controller.onPlay, e.controller.loop),
                    e.setAvatarVisible(!0),
                    (_e = this._sceneManager) == null || _e.lightComponent.setShadow(e);
                    const k = avatarLoader.mshPath.get("meshes/ygb.glb")
                      , j = avatarLoader.matPath.get(avatarResources.ygb.mesh);
                    if (k && j)
                        this.loadExtra(j, k).then(rt=>{
                            var it;
                            return e.isRender = !0,
                            e.isInLoadingList = !1,
                            e.distLevel = i,
                            (it = this._sceneManager) == null || it.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - o),
                            e
                        }
                        );
                    else
                        return e.isRender = !0,
                        e.isInLoadingList = !1,
                        e.distLevel = i,
                        (et = this._sceneManager) == null || et.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - o),
                        e;
                    return e.isInLoadingList = !1,
                    e.distLevel = i,
                    (tt = this._sceneManager) == null || tt.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - o),
                    e
                }
                ).catch(()=>Promise.reject(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))
            }
            ).catch(()=>Promise.reject(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))) : (e.isInLoadingList = !1,
            Promise.reject(new ContainerLoadingFailedError(`[Engine] avatar ${e.id} instanciates failed`)))
        }
        ).catch(()=>Promise.reject(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))
    }
    loadExtra(e, i) {
        const o = avatarResources.ygb.name;
        return new Promise((s,c)=>{
            var d;
            (d = this.sceneManager) == null || d.urlTransformer(e).then(_=>{
                SceneLoader.LoadAssetContainerAsync("", _, this.scene, null, avatarSetting.fileType).then(b=>{
                    var j;
                    this.extraComps.set(o, b.meshes[0]);
                    const k = new NodeMaterial(`material_${o}`,this._scene,{
                        emitComments: !1
                    });
                    (j = this.sceneManager) == null || j.urlTransformer(i).then($=>{
                        k.loadAsync($).then(()=>{
                            b.meshes[2].material.dispose(!0, !0),
                            k.build(!1),
                            b.meshes[2].material = k,
                            s(b.meshes[2])
                        }
                        )
                    }
                    )
                }
                )
            }
            )
        }
        )
    }
    getAvatarList() {
        const e = [];
        return this.characterMap.forEach((i,o)=>{
            i.forEach((s,c)=>{
                e.push(s)
            }
            )
        }
        ),
        e
    }
    _debug_avatar() {
        var i, o;
        console.error("===>currentLODUsers", this.currentLODUsers),
        console.error("===>maxLODUsers", this._maxLODUsers),
        console.error("===>Loddist", this.getLoDLevels()),
        console.error("===> main character loc", (o = (i = this._mainUser) == null ? void 0 : i.rootNode) == null ? void 0 : o.position);
        let e = 0;
        this.getAvatarList().forEach(s=>{
            s.isRender && (console.error(`avatar id : ${s.id},lod ${s.distLevel},is Hide ${s.isHide}, distance ${s.distance}, is pending ${s.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$D = new Logger$1("XLightManager");
class XLightManager {
    constructor(e) {
        this.sceneManager = e,
        this._scene = this.sceneManager.Scene,
        this._envTexture = null,
        this.shadowLean = .1;
        const i = new Vector3(this.shadowLean,-1,0)
          , o = 1024;
        this._shadowLight = new DirectionalLight("AvatarLight",i,this._scene),
        this._shadowLight.shadowMaxZ = 5e3,
        this._shadowLight.intensity = 0,
        this.attachLightToCamera(this._shadowLight),
        this._shadowGenerator = new ShadowGenerator(o,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((i,o)=>{
            this.sceneManager.urlTransformer(e).then(s=>{
                var c;
                if (s == ((c = this._envTexture) == null ? void 0 : c.url))
                    return i("env set success");
                this._envTexture != null && this.disposeIBL(),
                this._envTexture = CubeTexture.CreateFromPrefilteredData(s, this._scene, ".env"),
                this._scene.environmentTexture = this._envTexture,
                this._envTexture.onLoadObservable.addOnce(()=>{
                    i("env set success"),
                    log$D.info("env set success")
                }
                )
            }
            ).catch(()=>{
                o("env set fail")
            }
            )
        }
        )
    }
    disposeIBL() {
        this._envTexture == null ? log$D.info("env not exist") : (this._envTexture.dispose(),
        this._envTexture = null,
        this._scene.environmentTexture = null,
        log$D.info("env dispose success"))
    }
    removeShadow(e) {
        var i;
        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 o = e.rootNode;
            o && ((i = this._shadowGenerator) == null || i.removeShadowCaster(o))
        } else
            return
    }
    setShadow(e) {
        if (this._avatarShadowMeshMap.has(e))
            return;
        e.rootNode && this._avatarShadowMeshMap.set(e, e.rootNode.getChildMeshes());
        const i = 20
          , o = 10
          , s = this.cullingShadow(i, o, e);
        this._cullingShadowObservers.set(e, s)
    }
    cullingShadow(e, i, o) {
        let s = 0;
        const c = ()=>{
            var _;
            if (s == i) {
                const b = this._avatarShadowMeshMap.get(o)
                  , k = (_ = o.rootNode) == null ? void 0 : _.getChildMeshes()
                  , j = this._scene.activeCamera;
                b == null || b.forEach($=>{
                    var _e;
                    (_e = this._shadowGenerator) == null || _e.removeShadowCaster($, !1)
                }
                ),
                k == null || k.forEach($=>{
                    var _e;
                    (_e = this._shadowGenerator) == null || _e.addShadowCaster($, !1)
                }
                ),
                j && o.rootNode.position.subtract(j.position).length() > e && (k == null || k.forEach($=>{
                    var _e;
                    (_e = this._shadowGenerator) == null || _e.removeShadowCaster($, !1)
                }
                )),
                k && this._avatarShadowMeshMap.set(o, k),
                s = 0
            } else
                s += 1
        }
        ;
        return this._scene.onBeforeRenderObservable.add(c)
    }
    attachLightToCamera(e) {
        const i = e
          , o = 15
          , s = ()=>{
            const c = this._scene.activeCamera;
            if (c) {
                const d = i.direction
                  , _ = new Vector3(o * d.x,o * d.y,o * d.z)
                  , b = c.position;
                i.position = b.subtract(_)
            }
        }
        ;
        return i && this._scene.registerBeforeRender(s),
        s
    }
}
ParticleSystemSet.prototype.systems = new Array;
const _XParticleManager = class {
    constructor(a) {
        if (this.load = (e,i,o)=>new Promise(s=>{
            ParticleSystemSet.BaseAssetsUrl = e;
            const c = new XMLHttpRequest;
            c.open("get", e + "/" + i),
            c.send(null),
            c.onload = ()=>{
                if (c.status == 200) {
                    const d = JSON.parse(c.responseText);
                    let _ = null;
                    if (Object.keys(d).find(b=>b == "systems") == null) {
                        const b = ParticleSystem.Parse(d, this._scene, e);
                        _ = new ParticleSystemSet,
                        _.systems.push(b)
                    } else
                        _ = ParticleSystemSet.Parse(d, this._scene, !1);
                    s(_)
                }
            }
        }
        ),
        this.get = e=>this._particles.get(e),
        this.start = e=>{
            const i = this._particles.get(e);
            i && i.start()
        }
        ,
        this.stop = e=>{
            var o;
            const i = ((o = this._particles.get(e)) == null ? void 0 : o.systems) || [];
            for (let s = 0; s < i.length; s++)
                i[s].stop()
        }
        ,
        this.remove = e=>{
            const i = this._particles.get(e);
            i && i.dispose()
        }
        ,
        this.setParticlePosition = (e,i)=>{
            const o = this._particles.get(e);
            o && (o.emitterNode = i)
        }
        ,
        this.setParticleScalingInPlace = (e,i)=>{
            const o = this._particles.get(e);
            o == null || o.systems.forEach(s=>{
                _XParticleManager.scalingInPlace(s, i)
            }
            )
        }
        ,
        this._scene = a,
        this._particles = new Map,
        this._light = null,
        this._scene.getLightByName("fireworkLight"))
            this._light = this._scene.getLightByName("fireworkLight");
        else {
            const e = new PointLight("fireworkLight",new Vector3(0,0,0),a);
            e.intensity = 0,
            this._light = e
        }
    }
    _flashBang(a=200) {
        const e = this._scene.getLightByName("fireworkLight");
        e.intensity = 1,
        setTimeout(()=>{
            e.intensity = 0
        }
        , a)
    }
}
;
let XParticleManager = _XParticleManager;
XParticleManager.disposeParticleSysSet = a=>{
    !a.systems || (a.systems.forEach(e=>{
        _XParticleManager.disposeParticleSystem(e)
    }
    ),
    a.dispose())
}
;
XParticleManager.disposeParticleSystem = a=>{
    a.particleSystem && (a = a.particleSystem),
    a.subEmitters && a.subEmitters.forEach(e=>{
        e instanceof Array ? e.forEach(i=>{
            _XParticleManager.disposeParticleSystem(i)
        }
        ) : _XParticleManager.disposeParticleSystem(e)
    }
    ),
    a.dispose()
}
;
XParticleManager.scalingInPlace = (a,e)=>{
    a.getClassName() === "ParticleSystem" && (a.minSize *= e,
    a.maxSize *= e,
    a.subEmitters != null && a.subEmitters.forEach(i=>{
        i instanceof SubEmitter && _XParticleManager.scalingInPlace(i.particleSystem, e),
        i instanceof ParticleSystem && _XParticleManager.scalingInPlace(i, e),
        i instanceof Array && i.forEach(o=>{
            _XParticleManager.scalingInPlace(o.particleSystem, e)
        }
        )
    }
    ))
}
;
const DefaultUrlTransformer$1 = async a=>a
  , log$C = new Logger$1("subSequence")
  , DEFAULT_FRAME_RATE = 30
  , ROOT_MESH_ANIM_PROPERTY = ["scaling", "position", "rotation"]
  , MESH_TAG = "XSubSequence";
class XSpriteManager extends SpriteManager {
    constructor(e, i, o, s, c) {
        super(e, i, o, s, c),
        this.originalPositions = new Array,
        this.sprites.forEach(d=>{
            this.originalPositions.push(d.position)
        }
        )
    }
    static Parse(e, i, o) {
        const s = new XSpriteManager(e.name,"",e.capacity,{
            width: e.cellWidth,
            height: e.cellHeight
        },i);
        e.texture ? s.texture = Texture.Parse(e.texture, i, o) : e.textureName && (s.texture = new Texture(o + e.textureUrl,i,!0,e.invertY !== void 0 ? e.invertY : !0));
        for (const c of e.sprites) {
            const d = Sprite.Parse(c, s);
            s.originalPositions.push(d.position)
        }
        return s
    }
}
class XSubSequence {
    constructor(e, i, o=DefaultUrlTransformer$1) {
        this._pickable = !1,
        this.onLoadedObserverable = new Observable,
        this.onSubSequenceTransformationChangeObservable = new Observable,
        this.onIntersectionObservable = new Observable,
        this._isDisposing = !1,
        this.init = ()=>new Promise((s,c)=>{
            this.urlTransformer(this._abosoluteUrl).then(d=>{
                const _ = new XMLHttpRequest;
                _.open("get", d),
                _.send(null),
                _.onload = ()=>{
                    if (_.status == 200) {
                        const b = JSON.parse(_.responseText);
                        this.load(b).then(()=>{
                            this.onLoadedObserverable.notifyObservers(this),
                            this._loaded = !0,
                            s()
                        }
                        , ()=>{
                            c(),
                            log$C.error("subSequence: Load ${jsonBlob} json fail")
                        }
                        )
                    }
                }
                ,
                _.onerror = ()=>{
                    log$C.error("http: Get ${jsonBlob} json fail"),
                    c()
                }
            }
            )
        }
        ),
        this.play = async(s=!0)=>new Promise(c=>{
            if (this._animGroup.isPlaying && this._animGroup.stop(),
            this._particleGroups.forEach(d=>{
                var _;
                ((_ = d.emitterNode) == null ? void 0 : _.getClassName()) == "Mesh" && d.emitterNode instanceof Mesh ? d.emitterNode.isEnabled() && d.start() : d.start()
            }
            ),
            this._animGroup.targetedAnimations.length == 0) {
                this.show();
                let d = 0;
                this._spriteGroups.forEach(_=>{
                    _.sprites.forEach(b=>{
                        b.toIndex > d && (d = b.toIndex)
                    }
                    )
                }
                ),
                this._spriteGroups.forEach(_=>{
                    _.sprites.forEach(b=>{
                        b.playAnimation(b.fromIndex, b.toIndex, s, b.delay, ()=>{
                            b.toIndex == d && (this._isPaused = !0,
                            this.hide(),
                            c())
                        }
                        )
                    }
                    )
                }
                )
            } else
                this._animGroup.play(s),
                this._spriteGroups.forEach(d=>{
                    d.sprites.forEach(_=>{
                        _.playAnimation(_.fromIndex, _.toIndex, s, _.delay)
                    }
                    )
                }
                ),
                s ? this._animGroup.onAnimationGroupLoopObservable.addOnce(()=>{
                    c()
                }
                ) : this._animGroup.onAnimationGroupEndObservable.addOnce(()=>{
                    this._spriteGroups.forEach(d=>{
                        d.sprites.forEach(_=>{
                            _.isVisible = !1,
                            _.isPickable = !1,
                            _.stopAnimation()
                        }
                        )
                    }
                    ),
                    c()
                }
                );
            this._isStarted = !0,
            this._isPaused = !1
        }
        ),
        this.stop = ()=>{
            this._animGroup.stop(),
            this._particleGroups.forEach(s=>{
                s.systems.forEach(c=>{
                    c.stop()
                }
                )
            }
            ),
            this._spriteGroups.forEach(s=>{
                s.sprites.forEach(c=>{
                    c.stopAnimation()
                }
                )
            }
            ),
            this._isStarted = !1
        }
        ,
        this.clone = (s="Clone")=>{
            const c = new XSubSequence(this._scene,this._abosoluteUrl);
            return c._centerNode.name = s + "_" + this._centerNode.name,
            c._animGroup.name = s + "_" + this._animGroup.name,
            this._meshGroups.forEach(d=>{
                const _ = d.clone(s + "_", c._centerNode)
                  , b = _.getChildren(void 0, !1);
                if (b.forEach(k=>{
                    k.setEnabled(!0)
                }
                ),
                b.push(_),
                _) {
                    const k = d.getChildren(void 0, !1);
                    k.push(d),
                    this.animGroup.targetedAnimations.forEach(j=>{
                        if (j.target instanceof Node$2) {
                            const $ = k.indexOf(j.target);
                            $ != -1 && c._animGroup.addTargetedAnimation(j.animation, b[$])
                        }
                    }
                    )
                }
            }
            ),
            c._loaded = !0,
            c
        }
        ,
        this.goToFrame = s=>{
            this._animGroup.start(!0, 1, s, s)
        }
        ,
        this.pause = ()=>{
            this._isPaused = !0,
            this._animGroup.pause()
        }
        ,
        this.reset = ()=>{
            this._animGroup.reset()
        }
        ,
        this.loadTrackToAnim = s=>{
            const c = Array();
            let d = !0;
            s.keyFrame.forEach(b=>{
                if (b.frame > this._endFrame && (this._endFrame = b.frame),
                b.value instanceof Array) {
                    const k = {
                        frame: b.frame,
                        value: new Vector3(0,0,0)
                    }
                      , j = new Vector3(b.value[0],b.value[1],b.value[2]);
                    k.value = j,
                    c.push(k)
                } else
                    c.push(b),
                    d = !1
            }
            ),
            s.loop == null && (s.loop = !1),
            s.index == null && (s.index = 0);
            let _ = null;
            if ("blockName"in s) {
                const b = {
                    keyFrame: c,
                    blockName: s.blockName,
                    property: s.property,
                    targetName: s.targetName,
                    index: s.index,
                    loop: s.loop
                };
                _ = this.transferTrackToAnim(b, d)
            } else {
                const b = {
                    keyFrame: c,
                    property: s.property,
                    targetName: s.targetName,
                    index: s.index,
                    loop: s.loop
                };
                _ = this.transferTrackToAnim(b, d)
            }
            return _
        }
        ,
        this.transferTrackToAnim = (s,c)=>{
            let d = null;
            c ? (d = new Animation(s.targetName + "_" + s.property,s.property,DEFAULT_FRAME_RATE,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CYCLE),
            d.setKeys(s.keyFrame)) : (d = new Animation(s.targetName + "_" + s.property,s.property,DEFAULT_FRAME_RATE,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE),
            d.setKeys(s.keyFrame));
            let _ = null;
            return "blockName"in s ? _ = {
                animation: d,
                blockName: s.blockName,
                targetName: s.targetName,
                nodeIndex: s.index,
                loop: s.loop
            } : _ = {
                animation: d,
                targetName: s.targetName,
                nodeIndex: s.index,
                loop: s.loop
            },
            _
        }
        ,
        i.indexOf("./") == 0 && (i = i.slice(2)),
        this._abosoluteUrl = i,
        this._name = i.split("/").slice(-1)[0].split(".")[0].split("_")[1],
        this._rootDir = i.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 = o,
        this._centerNode.onAfterWorldMatrixUpdateObservable.add(()=>{
            this.onSubSequenceTransformationChangeObservable.notifyObservers(this)
        }
        ),
        this._animGroup.onAnimationGroupPlayObservable.add(()=>{
            this._particleGroups.forEach(s=>{
                s.systems.forEach(c=>{
                    c.isStarted() || c.start()
                }
                )
            }
            ),
            this.show()
        }
        ),
        this._animGroup.onAnimationGroupLoopObservable.add(()=>{
            this._particleGroups.forEach(s=>{
                s.systems.forEach(c=>{
                    c.isStarted() || c.start()
                }
                )
            }
            )
        }
        ),
        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(i=>{
                var o, s;
                (i.getClassName() === "AbstractMesh" || i.getClassName() === "Mesh") && ((o = i.skeleton) == null || o.dispose(),
                (s = i.material) == null || s.dispose(!0, !0)),
                i.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(i=>{
            i.getChildMeshes().forEach(o=>{
                o.isPickable = e
            }
            )
        }
        ),
        this._spriteGroups.forEach(i=>{
            i.isPickable = e,
            i.sprites.forEach(o=>{
                o.isPickable = e
            }
            )
        }
        ),
        this._pickable = e
    }
    addAnimation(e) {
        this._animGroup.addTargetedAnimation(e, this._centerNode),
        this._spriteGroups.forEach(i=>{
            i.sprites.forEach(o=>{
                this._animGroup.addTargetedAnimation(e, o)
            }
            )
        }
        )
    }
    setStartFrame(e) {
        this._animGroup.stop(),
        this._animGroup.targetedAnimations.forEach(i=>{
            const o = i.animation.getKeys();
            o.forEach(s=>{
                e + o[0].frame > 0 ? s.frame += e : s.frame -= o[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(i=>{
            i.emitterNode == null || i.emitterNode instanceof Vector3 ? i.emitterNode = e : this._scene.getMeshByName(i.emitterNode.name) || (i.emitterNode = e)
        }
        ),
        this._spriteGroups.forEach(i=>{
            i.sprites.forEach((o,s)=>{
                o.position = e
            }
            )
        }
        )
    }
    setScaling(e) {
        this.setScalingVector(ue4Scaling2Xverse(e))
    }
    setScalingVector(e) {
        var i;
        this._centerNode.scaling = e,
        (i = this._particleGroups) == null || i.forEach(o=>{
            o.systems.forEach(s=>{
                XParticleManager.scalingInPlace(s, e.x)
            }
            )
        }
        ),
        this._spriteGroups.forEach(o=>{
            o.sprites.forEach(s=>{
                s.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(i=>{
                i.isStarted() && i.stop()
            }
            )
        }
        ),
        this._spriteGroups.forEach(e=>{
            e.sprites.forEach(i=>{
                i.isVisible = !1
            }
            )
        }
        )
    }
    show() {
        this._centerNode.setEnabled(!0),
        this._centerNode.getChildren().forEach(e=>{
            e.setEnabled(!0),
            e.getChildMeshes().forEach(i=>{
                i.setEnabled(!0)
            }
            )
        }
        ),
        this._particleGroups.forEach(e=>{
            e.systems.forEach(i=>{
                i.start()
            }
            )
        }
        ),
        this._spriteGroups.forEach(e=>{
            e.sprites.forEach(i=>{
                i.isVisible = !0
            }
            )
        }
        )
    }
    get totalFrame() {
        return this._endFrame
    }
    load(e) {
        return new Promise((i,o)=>{
            const s = e.Mesh
              , c = e.Sprite
              , d = e.Material
              , _ = e.Glow
              , b = e.HighLight
              , k = e.Particle
              , j = e.MeshTrack
              , $ = e.ParticleTrack
              , _e = e.MaterialTrack;
            this._animGroup.name += e.Type;
            const et = Date.now();
            this._centerNode.name += e.Type;
            const tt = new Array
              , rt = new Array;
            s != null && s.forEach(it=>{
                tt.push(this.loadMesh(it))
            }
            ),
            c != null && c.forEach(it=>{
                rt.push(this.loadSprite(it))
            }
            ),
            Promise.all(tt).then(()=>{
                d != null && d.forEach(it=>{
                    rt.push(this.loadMaterial(it))
                }
                ),
                k != null && k.forEach(it=>{
                    rt.push(this.loadParticle(it))
                }
                ),
                Promise.all(rt).then(()=>{
                    if (this._isDisposing) {
                        const nt = Date.now() - et;
                        log$C.info(`subSequence: Load ${e.Type} takes ${nt} ms`),
                        i(this);
                        return
                    }
                    if (_ != null)
                        for (const nt of _)
                            this.loadGlow(nt);
                    if (b != null)
                        for (const nt of b)
                            this.loadHighLight(nt);
                    j != null && j.forEach(nt=>{
                        const ot = this._meshGroups.get(nt.targetName);
                        if (ot != null) {
                            const at = this.loadTrackToAnim(nt);
                            ROOT_MESH_ANIM_PROPERTY.indexOf(at.animation.targetProperty) == -1 ? ot.getChildMeshes().forEach(st=>{
                                at.animation.targetProperty in st && this._animGroup.addTargetedAnimation(at.animation, st)
                            }
                            ) : this._animGroup.addTargetedAnimation(at.animation, ot)
                        }
                    }
                    ),
                    $ != null && $.forEach(nt=>{
                        var ut;
                        const ot = nt.index
                          , at = nt.targetName
                          , st = (ut = this._particleGroups.get(at)) == null ? void 0 : ut.systems[ot];
                        if (st != null) {
                            const ct = this.loadTrackToAnim(nt);
                            this._animGroup.addTargetedAnimation(ct.animation, st)
                        }
                    }
                    ),
                    _e != null && _e.forEach(nt=>{
                        const ot = this._materialGroups.get(nt.targetName);
                        if (ot) {
                            const at = ot[0];
                            if (at != null)
                                if (at.getBlockByName(nt.blockName) != null) {
                                    const st = this.loadTrackToAnim(nt);
                                    ot == null || ot.forEach(ut=>{
                                        this._animGroup.addTargetedAnimation(st.animation, ut.getBlockByName(nt.blockName))
                                    }
                                    )
                                } else
                                    console.error("property " + nt.property + "is not in " + at.name)
                        }
                    }
                    );
                    const it = Date.now() - et;
                    log$C.info(`subSequence: Load ${e.Type} takes ${it} ms`),
                    i(this)
                }
                , ()=>{
                    log$C.error(`subSequence: Load ${e.Type} fail`),
                    o()
                }
                )
            }
            , ()=>{
                o()
            }
            )
        }
        )
    }
    loadMesh(e) {
        return new Promise((i,o)=>{
            const s = this._rootDir + e.uri;
            this.urlTransformer(s).then(c=>{
                if (this._isDisposing) {
                    i();
                    return
                }
                SceneLoader.LoadAssetContainer("", c, this._scene, d=>{
                    if (this._isDisposing) {
                        d.removeAllFromScene(),
                        i();
                        return
                    }
                    d.animationGroups.forEach(b=>{
                        b.stop()
                    }
                    ),
                    d.animationGroups.length != 0 && (d.animationGroups.forEach(b=>{
                        b.targetedAnimations.forEach(k=>{
                            this._animGroup.addTargetedAnimation(k.animation, k.target)
                        }
                        ),
                        b.dispose()
                    }
                    ),
                    d.animationGroups = [],
                    d.animations = [],
                    d.materials = []);
                    const _ = new TransformNode("__root__" + e.name,this._scene);
                    if (e.uri.split(".")[1] == "glb")
                        d.meshes[0].parent = _;
                    else if (e.uri.split(".")[1] == "obj") {
                        const b = new TransformNode("__root__",this._scene);
                        d.meshes.forEach(k=>{
                            k.parent = b,
                            k.Type = MESH_TAG
                        }
                        ),
                        b.parent = _
                    }
                    _.getChildMeshes().forEach(b=>{
                        e.isPickable != null ? b.isPickable = e.isPickable : b.isPickable = !1,
                        b.xtype = "XSubSequence"
                    }
                    ),
                    this._meshGroups.set(e.name, _),
                    _.parent = this._centerNode,
                    d.addAllToScene(),
                    i()
                }
                , ()=>{}
                , ()=>{
                    log$C.error("subSequence:Load effect mesh fail"),
                    log$C.error(`Effect Mesh ${e.name} load error`),
                    o()
                }
                , ".glb")
            }
            , ()=>{
                log$C.error("http:Get effect mesh fail"),
                log$C.error(`Effect Mesh ${e.name} load error`),
                o()
            }
            )
        }
        )
    }
    loadSprite(e) {
        return new Promise((i,o)=>{
            if (this._isDisposing) {
                i();
                return
            }
            const s = this._rootDir + e.uri;
            if (e.uri !== "") {
                e.name;
                const c = new XMLHttpRequest;
                c.open("get", s),
                c.send(null),
                c.onload = ()=>{
                    if (c.status == 200) {
                        const d = JSON.parse(c.responseText)
                          , _ = XSpriteManager.Parse(d, this._scene, this._rootDir);
                        _.sprites.forEach(b=>{
                            b.stopAnimation()
                        }
                        ),
                        this._spriteGroups.set(e.name, _),
                        i()
                    } else
                        log$C.error("subSequence:Load effect sprite fail"),
                        log$C.error(`Effect Sprite ${e.name} load error`),
                        o()
                }
            }
        }
        )
    }
    loadMaterial(e) {
        return new Promise((i,o)=>{
            if (this._isDisposing) {
                i();
                return
            }
            const s = this._rootDir + e.uri;
            if (e.uri !== "") {
                const c = e.name
                  , d = new NodeMaterial(`material_${c}`,this._scene,{
                    emitComments: !1
                });
                d.backFaceCulling = !1,
                this.urlTransformer(s).then(_=>{
                    if (this._isDisposing) {
                        d.dispose(!1, !0, !1),
                        i();
                        return
                    }
                    d.loadAsync(_).then(()=>{
                        if (this._isDisposing) {
                            d.dispose(!0, !0, !1),
                            i();
                            return
                        }
                        d.build(!1);
                        const b = new Array;
                        let k = !1;
                        for (let j = 0; j < e.meshName.length; j++)
                            this._meshGroups.forEach($=>{
                                $.getChildMeshes().forEach(_e=>{
                                    var et;
                                    if (_e.name === e.meshName[j]) {
                                        k = !0,
                                        (et = _e.material) == null || et.dispose(!0, !0);
                                        const tt = _e;
                                        if (tt.skeleton == null) {
                                            const rt = d;
                                            tt.material = rt,
                                            b.push(rt)
                                        } else if (tt.numBoneInfluencers = 4,
                                        tt.computeBonesUsingShaders = !0,
                                        j == 0) {
                                            const rt = d;
                                            tt.material = rt,
                                            b.push(rt)
                                        } else {
                                            const rt = d.clone(`material_${c}` + String(j), !1);
                                            tt.material = rt,
                                            b.push(rt)
                                        }
                                    }
                                }
                                )
                            }
                            );
                        k ? this._materialGroups.set(e.name, b) : d.dispose(!0, !0),
                        i()
                    }
                    , ()=>{
                        log$C.error("http:Get effect Material fail"),
                        log$C.error(`Effect NodeMaterial ${c} load error`),
                        o()
                    }
                    )
                }
                )
            }
        }
        )
    }
    async loadGlow(e) {
        const i = new GlowLayer(e.name,this._scene,{
            blurKernelSize: e.blurKernelSize
        });
        i.intensity = e.intensity,
        e.meshName.forEach(o=>{
            const s = this._scene.getMeshByName(o);
            s != null && i.addIncludedOnlyMesh(s)
        }
        ),
        this._glowGroups.set(e.name, i)
    }
    loadHighLight(e) {
        const i = new HighlightLayer(e.name,this._scene);
        e.meshName.forEach(o=>{
            const s = this._scene.getMeshByName(o);
            if (s != null) {
                const c = new Color3(e.color[0],e.color[1],e.color[2]);
                i.addMesh(s, c)
            }
        }
        ),
        this._highLightGroups.set(e.name, i)
    }
    loadParticle(e) {
        return new Promise((i,o)=>{
            const s = this._rootDir + e.rootDir
              , c = new XParticleManager(this._scene);
            this.urlTransformer(s + e.uri).then(d=>{
                if (this._isDisposing) {
                    i();
                    return
                }
                c.load(s, e.uri, e.name).then(_=>{
                    if (this._isDisposing) {
                        o();
                        return
                    }
                    this._particleGroups.set(e.name, _),
                    i()
                }
                , ()=>{
                    log$C.error(`SubSequence: ${e.name} particle load fail`),
                    o()
                }
                )
            }
            , ()=>{
                log$C.error(`http: ${s + e.uri} load fail`),
                o()
            }
            )
        }
        )
    }
}
const DefaultUrlTransformer = async a=>a;
class XSequence {
    constructor(e, i, o="test", s=DefaultUrlTransformer) {
        this.init = async()=>new Promise(c=>{
            this.urlTransformer(this._abosoluteUrl).then(d=>{
                const _ = new XMLHttpRequest;
                _.open("get", d),
                _.send(null),
                _.onload = ()=>{
                    if (_.status == 200) {
                        const b = JSON.parse(_.responseText);
                        this.load(b).then(()=>{
                            c()
                        }
                        )
                    }
                }
            }
            )
        }
        ),
        this.getRootOfSubSeqs = ()=>{
            const c = new Array;
            return this._subSeqs.forEach(d=>{
                c.push(d.root)
            }
            ),
            c
        }
        ,
        this.play = async(c=!0)=>new Promise(d=>{
            this._animGroup.play(c),
            c ? this._animGroup.onAnimationGroupLoopObservable.addOnce(()=>{
                d()
            }
            ) : this._animGroup.onAnimationGroupEndObservable.addOnce(()=>{
                d()
            }
            )
        }
        ),
        this.goToFrame = c=>{
            this._animGroup.goToFrame(c)
        }
        ,
        this.hide = ()=>{
            this._subSeqs.forEach(c=>{
                c.hide()
            }
            )
        }
        ,
        this.show = ()=>{
            this._subSeqs.forEach(c=>{
                c.show()
            }
            )
        }
        ,
        this.pause = ()=>{
            this._animGroup.pause()
        }
        ,
        this.reset = ()=>{
            this._animGroup.reset()
        }
        ,
        this._scene = e,
        this._abosoluteUrl = i,
        this._rootDir = i.split("/").slice(0, -1).join("/") + "/",
        this._name = o,
        this._subSeqs = new Map,
        this._animGroup = new AnimationGroup("Seq_" + o,e),
        this._targetSubSeqs = new Map,
        this._animGroup.onAnimationGroupPlayObservable.add(()=>{
            this._subSeqs.forEach(c=>{
                c.show()
            }
            )
        }
        ),
        this._animGroup.onAnimationGroupEndObservable.add(()=>{
            this._subSeqs.forEach(c=>{
                c.hide()
            }
            )
        }
        ),
        this.urlTransformer = s
    }
    get animGroup() {
        return this._animGroup
    }
    serialize() {
        const e = {};
        return e.SubSequence = new Array,
        e.TimeLine = new Array,
        this._subSeqs.forEach(i=>{
            const o = {
                name: i.name,
                uri: i.path
            };
            e.SubSequence.push(o);
            const s = this._targetSubSeqs.get(i);
            s && e.TimeLine.push({
                frame: s == null ? void 0 : s.frame,
                position: s.position,
                rotation: s.rotation,
                scaling: s.scaling,
                name: i.name
            })
        }
        ),
        e
    }
    get isPlaying() {
        return this._animGroup.isPlaying
    }
    get isStarted() {
        return this._animGroup.isStarted
    }
    get loaded() {
        let e = !0;
        return this._subSeqs.forEach(i=>{
            e = e && i.loaded
        }
        ),
        e
    }
    dispose() {
        this._subSeqs.forEach(e=>{
            e.dispose()
        }
        ),
        this.animGroup.dispose()
    }
    setFrame(e, i) {
        const o = this._subSeqs.get(e);
        if (o) {
            const s = this._targetSubSeqs.get(o);
            s && (s.frame = i),
            s && this.update(o, s)
        }
    }
    get name() {
        return this._name
    }
    update(e, i) {
        if (i) {
            const o = {
                frame: i.frame,
                scaling: new Vector3(i.scaling[0],i.scaling[1],i.scaling[2]),
                position: new Vector3(i.position[0],i.position[1],i.position[2]),
                rotation: new Vector3(i.rotation[0] / 180 * Math.PI,i.rotation[1] / 180 * Math.PI,i.rotation[2] / 180 * Math.PI),
                name: i.name
            }
              , s = this._subSeqs.get(o.name);
            s && (s.setPositionVector(o.position),
            s.setRotationVector(o.rotation),
            s.setScalingVector(o.scaling),
            s.setStartFrame(o.frame),
            this._targetSubSeqs.set(s, i),
            s.onSubSequenceTransformationChangeObservable.add(()=>{
                const c = this._targetSubSeqs.get(s);
                c && (c.position = [s.pos.x, s.pos.y, s.pos.z]),
                c && (c.rotation = [s.rot.x, s.rot.y, s.rot.z]),
                c && (c.scaling = [s.scal.x, s.scal.y, s.scal.z])
            }
            ))
        }
    }
    load(e) {
        return new Promise((i,o)=>{
            const s = new Array
              , c = e.SubSequence
              , d = e.TimeLine;
            for (const _ of c) {
                _.uri.indexOf("./") == 0 && (_.uri = _.uri.slice(2));
                const b = new XSubSequence(this._scene,this._rootDir + _.uri,this.urlTransformer);
                this._subSeqs.set(_.name, b),
                s.push(b.init())
            }
            Promise.all(s).then(()=>{
                d.forEach(_=>{
                    const b = this._subSeqs.get(_.name);
                    b && this.update(b, _)
                }
                ),
                this._subSeqs.forEach(_=>{
                    _.animGroup.targetedAnimations.forEach(b=>{
                        this._animGroup.addTargetedAnimation(b.animation, b.target)
                    }
                    )
                }
                ),
                i()
            }
            , ()=>{
                o()
            }
            )
        }
        )
    }
}
const log$B = new Logger$1("XStaticMesh");
class XStaticMesh {
    constructor({id: e, mesh: i, group: o="default", lod: s=0, xtype: c=EMeshType.XStaticMesh, skinInfo: d="default", url: _=""}) {
        this._mesh = void 0,
        this._id = "-1",
        this._isMoving = !1,
        this._isRotating = !1,
        this._isVisible = !0,
        this.setVisibility = (b,k)=>{
            Array.isArray(b) ? b.forEach(j=>{
                this.setVisibility(j, k)
            }
            ) : b.isAnInstance || (b.visibility = k)
        }
        ,
        this.setPickable = (b,k)=>{
            Array.isArray(b) ? b.forEach(j=>{
                this.setPickable(j, k)
            }
            ) : ("isPickable"in b && (b.isPickable = k),
            b.setEnabled(k))
        }
        ,
        this.hide = ()=>{
            var b;
            this._isVisible = !1,
            this.mesh && this.setVisibility(this.mesh, 0),
            this.mesh && this.setPickable(this.mesh, !1),
            (b = this.mesh) == null || b.getChildMeshes().forEach(k=>{
                this.setVisibility(k, 0),
                this.setPickable(k, !1)
            }
            )
        }
        ,
        this.show = ()=>{
            var b;
            this._isVisible = !0,
            this.mesh && this.setVisibility(this.mesh, 1),
            this.mesh && this.setPickable(this.mesh, !0),
            (b = this.mesh) == null || b.getChildMeshes().forEach(k=>{
                this.setVisibility(k, 1),
                this.setPickable(k, !0)
            }
            )
        }
        ,
        this.attachToAvatar = (b,k={
            x: 0,
            y: .5,
            z: 0
        },j={
            yaw: 0,
            pitch: 0,
            roll: 0
        },$={
            x: .35,
            y: .35,
            z: .35
        })=>{
            const _e = ue4Scaling2Xverse($)
              , et = ue4Rotation2Xverse(j)
              , tt = ue4Position2Xverse(k)
              , rt = this._mesh;
            b && rt ? (b.setParent(rt),
            b.position = tt,
            b.rotation = et,
            b.scaling = _e) : log$B.error("[Engine] avatar or attachment not found!")
        }
        ,
        this.detachFromAvatar = (b,k=!1)=>{
            this._mesh && b ? this._mesh.removeChild(b) : log$B.error("[Engine] avatar not found!")
        }
        ,
        this._id = e,
        this._mesh = i,
        this._group = o,
        this._lod = s,
        this._skinInfo = d,
        this.unallowMove(),
        this._mesh.xtype = c,
        this._mesh.xid = e,
        this._mesh.xgroup = this._group,
        this._mesh.xlod = this._lod,
        this._mesh.xskinInfo = this._skinInfo,
        this._mesh.xurl = _
    }
    get mesh() {
        return this._mesh
    }
    get position() {
        var c;
        if (!this._mesh)
            return null;
        const {x: e, y: i, z: o} = (c = this._mesh) == null ? void 0 : c.position;
        return xversePosition2Ue4({
            x: e,
            y: i,
            z: o
        })
    }
    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 i = ue4Position2Xverse(e);
            this._mesh.position = i
        } else
            log$B.error("[Engine] no root for positioning")
    }
    setRotation(e) {
        const i = ue4Rotation2Xverse_mesh(e);
        this._mesh ? this._mesh.rotation = i : log$B.error("[Engine] no root for rotating")
    }
    setScale(e) {
        this._mesh ? this._mesh.scaling = new Vector3(e,e,-e) : log$B.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 i;
        (i = this.mesh) == null || i.getChildMeshes().forEach(o=>{
            "instances"in o && "isPickable"in o && (o.isPickable = e)
        }
        ),
        this.mesh != null && "isPickable"in this.mesh && (this.mesh.isPickable = e)
    }
    setMaterial(e) {
        var i;
        (i = this.mesh) == null || i.getChildMeshes().forEach(o=>{
            "instances"in o && "material"in o && (o.material = e)
        }
        ),
        this.mesh != null && "material"in this.mesh && (this.mesh.material = e)
    }
    dispose(e=!1, i=!1) {
        !this.mesh.isDisposed() && this.mesh.dispose(e, i)
    }
}
class Timeout$1 {
    constructor(e, i, o=!0) {
        this._fn = e,
        this._delay = i,
        o && 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) {
        if (this._streamPlayTimer = null,
        this.play = ()=>new Promise((i,o)=>{
            this._streamPlayTimer = new Timeout$1(()=>{
                o("Stream play timeout")
            }
            ,5e3),
            this.el && this.el.play().then(()=>{
                var s;
                i(),
                (s = this._streamPlayTimer) == null || s.clear()
            }
            ).catch(s=>{
                var c;
                o("Media Failed to autoplay"),
                (c = this._streamPlayTimer) == null || c.clear()
            }
            )
        }
        ),
        !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$A = new Logger$1("XTelevision");
var EFitMode = (a=>(a.fill = "fill",
a.contain = "contain",
a.cover = "cover",
a))(EFitMode || {});
class XTelevision {
    constructor(e, i, o, s) {
        if (this.tvMeshs = [],
        this.scene = e,
        this.meshPath = i,
        this._scenemanager = o,
        s != null) {
            const {vAng: c=0, widthHeightScale: d=-1, fitMode: _="fill"} = s;
            this.vAng = c,
            this.widthHeightScale = d,
            this.fitMode = _
        }
    }
    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, i=!1) {
        const s = new Stream$1().el;
        return s.loop = i,
        s.autoplay = !0,
        s.src = e,
        s
    }
    async setUrl(e) {
        const {url: i, isLive: o=!1, poster: s=null, bLoop: c=!1, bMuted: d=!0} = e || {};
        if (typeof i != "string")
            return log$A.error("[Engine] Tv setUrl Error, url must be string: ", i),
            Promise.reject(new XTvMediaUrlError("[Engine] url must be string"));
        if (this.videoElement) {
            this.videoElement.src = i,
            s != null && s.length > 0 && (this.videoElement.poster = s);
            const b = this.play();
            return "bMuted"in e && b !== void 0 && b.then(()=>{
                this.videoElement.muted = d
            }
            ),
            this.videoElement.addEventListener("loadedmetadata", k=>{
                this.videoElement.videoWidth > 0 ? this.videoMat.setFloat("mvWidthHeightScale", this.videoElement.videoWidth / this.videoElement.videoHeight) : this.videoMat.setFloat("mvWidthHeightScale", 16 / 9)
            }
            ),
            Promise.resolve(this)
        }
        const _ = this.createElement(i, c);
        return s != null && s.length > 0 && (_.poster = s),
        this.setVideo(_, o).then(()=>{
            var k;
            const b = (k = this.videoElement) == null ? void 0 : k.play();
            "bMuted"in e && b !== void 0 && b.then(()=>{
                this.videoElement.muted = d
            }
            )
        }
        ).catch(b=>{
            const k = new XTvMediaUrlError("[Engine] setUrl  error! " + b);
            return log$A.error(k),
            Promise.reject(k)
        }
        )
    }
    setCurrentTime(e) {
        if (!this.videoElement) {
            log$A.warn("[Engine] The television is not been initialize succesfully");
            return
        }
        const {currentTime: i} = e;
        if (typeof i != "number") {
            log$A.warn("[Engine] video currentTime must be number");
            return
        }
        this.videoElement.currentTime = i / 1e3
    }
    getCurrentTime() {
        return this.videoElement ? this.videoElement.currentTime * 1e3 : -1
    }
    play() {
        return log$A.info("[Engine] Play television"),
        this.toggle(!0),
        this.videoElement ? this.videoElement.play() : Promise.resolve()
    }
    pause() {
        var e;
        return log$A.info("[Engine] Pause television"),
        (e = this.videoElement) == null ? void 0 : e.pause()
    }
    stop() {
        log$A.info("[Engine] Stop television"),
        this.pause(),
        setTimeout(()=>{
            this.setCurrentTime({
                currentTime: 0
            })
        }
        ),
        this.toggle(!1)
    }
    toggle(e) {
        log$A.info(`[Engine] Set Tv visibility = ${e}`);
        for (let i = 0; i < this.tvMeshs.length; ++i)
            e == !0 ? this.tvMeshs[i].show() : this.tvMeshs[i].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, i=!1, o=!0) {
        return this.tvMeshs.length != 0 ? (log$A.warn(`[Engine] Set Video. length!=0, mesh: ${this.meshPath}, src: ${e.src}`),
        new Promise((s,c)=>{
            if (!(e instanceof HTMLVideoElement))
                return log$A.error("[Engine] Error, param of setVideo must be a HTMLVideoElement"),
                c(new XTvVideoElementError("[Engine] param of setVideo must be a HTMLVideoElement"));
            this.videoElement = e,
            o == !1 && (i == !1 || checkOS().isIOS) && e.crossOrigin !== "anonymous" && (e.crossOrigin = "anonymous",
            e.load()),
            this.videoElement.addEventListener("loadedmetadata", d=>{
                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),
            s(this)
        }
        )) : (log$A.warn(`[Engine] Set Video. length==0, mesh: ${this.meshPath}, src: ${e.src}`),
        this.meshPath == "" ? (log$A.error("[Engine] Error, television meshPath is empty."),
        Promise.reject(new XTvVideoElementError("[Engine] Error, television meshPath is empty."))) : this._scenemanager.urlTransformer(this.meshPath).then(s=>new Promise((c,d)=>e instanceof HTMLVideoElement ? (this.videoElement = e,
        o == !1 && (i == !1 || checkOS().isIOS) && e.crossOrigin !== "anonymous" && (e.crossOrigin = "anonymous",
        e.load()),
        SceneLoader.LoadAssetContainerAsync("", s, this.scene, null, ".glb").then(_=>{
            for (let k = _.materials.length - 1; k >= 0; --k)
                _.materials[k].dispose();
            const b = [];
            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", k=>{
                this.videoElement.videoWidth > 0 ? this.videoMat.setFloat("mvWidthHeightScale", this.videoElement.videoWidth / this.videoElement.videoHeight) : this.videoMat.setFloat("mvWidthHeightScale", 16 / 9)
            }
            );
            for (let k = 0; k < _.meshes.length; ++k)
                _.meshes[k].visibility = 1,
                _.meshes[k].isPickable = !0,
                _.meshes[k].checkCollisions = !1,
                _.meshes[k].material = this.videoMat,
                "hasVertexAlpha"in _.meshes[k] && (_.meshes[k].hasVertexAlpha = !1),
                this.scene.addMesh(_.meshes[k]),
                b.push(new XStaticMesh({
                    id: _.meshes[k].id,
                    mesh: _.meshes[k],
                    xtype: EMeshType.Tv
                }));
            this.changeTvFitMode(),
            this.tvMeshs = b,
            this.toggle(!0),
            c(this)
        }
        ).catch(_=>{
            log$A.error("[Engine] setVideo: create Tv by input mesh error! " + _),
            d(new XTvModelError("[Engine] setVideo: create Tv by input mesh error! " + _))
        }
        )) : d(new XTvVideoElementError("[Engine] param of setVideo must be a HTMLVideoElement")))))
    }
    async setSameVideo(e, i="") {
        return e == null || e == null ? (log$A.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 && i == "" ? (log$A.warn(`[Engine] Set mirror video. length!=0, mesh: ${this.meshPath}`),
        new Promise((o,s)=>{
            try {
                this.videoMat = e,
                this.tvMeshs.forEach(c=>{
                    c.setMaterial(e)
                }
                ),
                this.changeTvFitMode(),
                o(this)
            } catch (c) {
                log$A.error("[Engine] setSameVideo: create Tv by input mesh error! " + c),
                s(new XTvModelError("[Engine] create Tv by input mesh error! " + c))
            }
        }
        )) : (i != "" && (this.meshPath = i,
        this.widthHeightScale = -1),
        this.meshPath == "" ? (log$A.error("[Engine] Error, setSameVideo television meshPath is empty."),
        Promise.reject(new XTvVideoElementError("[Engine] Error, setSameVideo television meshPath is empty."))) : (log$A.warn(`[Engine] Set mirror video. length==0, mesh: ${this.meshPath}`),
        this._scenemanager.urlTransformer(this.meshPath).then(o=>new Promise((s,c)=>(this.videoMat = e,
        e != null && e.getActiveTextures()[0] && (this.videoElement = e == null ? void 0 : e.getActiveTextures()[0].video),
        SceneLoader.LoadAssetContainerAsync("", o, this.scene, null, ".glb").then(d=>{
            for (let b = d.materials.length - 1; b >= 0; --b)
                d.materials[b].dispose();
            const _ = [];
            for (let b = 0; b < d.meshes.length; ++b)
                d.meshes[b].visibility = 0,
                d.meshes[b].isPickable = !0,
                d.meshes[b].checkCollisions = !1,
                d.meshes[b].material = this.videoMat,
                "hasVertexAlpha"in d.meshes[b] && (d.meshes[b].hasVertexAlpha = !1),
                this.scene.addMesh(d.meshes[b]),
                _.push(new XStaticMesh({
                    id: d.meshes[b].id,
                    mesh: d.meshes[b],
                    xtype: EMeshType.Tv
                }));
            i != "" && this.cleanTv(!1, !1),
            this.tvMeshs = _,
            this.changeTvFitMode(),
            s(this)
        }
        ).catch(d=>{
            log$A.error("[Engine] setSameVideo: create Tv by input mesh error! " + d),
            c(new XTvModelError("[Engine] create Tv by input mesh error! " + d))
        }
        ))))))
    }
    async changeTvModel(e="") {
        return e != "" && (this.meshPath = e,
        this.widthHeightScale = -1),
        this.meshPath == "" ? (log$A.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$A.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(i=>new Promise((o,s)=>SceneLoader.LoadAssetContainerAsync("", i, this.scene, null, ".glb").then(c=>{
            for (let _ = c.materials.length - 1; _ >= 0; --_)
                c.materials[_].dispose();
            const d = [];
            for (let _ = 0; _ < c.meshes.length; ++_)
                c.meshes[_].visibility = 0,
                c.meshes[_].isPickable = !0,
                c.meshes[_].checkCollisions = !1,
                c.meshes[_].material = this.videoMat,
                "hasVertexAlpha"in c.meshes[_] && (c.meshes[_].hasVertexAlpha = !1),
                this.scene.addMesh(c.meshes[_]),
                d.push(new XStaticMesh({
                    id: c.meshes[_].id,
                    mesh: c.meshes[_],
                    xtype: EMeshType.Tv
                }));
            e != "" && this.cleanTv(!1, !1),
            this.tvMeshs = d,
            this.changeTvFitMode(),
            o(this)
        }
        ).catch(c=>{
            log$A.error("[Engine] changeTvModel: create Tv by input mesh error! " + c),
            s(new XTvModelError("[Engine] changeTvModel: create Tv by input mesh error! " + c))
        }
        )))
    }
    calWidthHeightScale() {
        const e = [1e5, 1e5, 1e5]
          , i = [-1e5, -1e5, -1e5];
        for (let d = 0; d < this.tvMeshs.length; ++d)
            if (this.tvMeshs[d].mesh.name != "__root__") {
                const _ = this.tvMeshs[d].mesh.getBoundingInfo().boundingBox.vectorsWorld;
                for (let b = 0; b < _.length; ++b)
                    e[0] > _[b].x && (e[0] = _[b].x),
                    e[1] > _[b].y && (e[1] = _[b].y),
                    e[2] > _[b].z && (e[2] = _[b].z),
                    i[0] < _[b].x && (i[0] = _[b].x),
                    i[1] < _[b].y && (i[1] = _[b].y),
                    i[2] < _[b].z && (i[2] = _[b].z);
                break
            }
        const o = i[0] - e[0]
          , s = i[1] - e[1]
          , c = i[2] - e[2];
        return Math.sqrt(o * o + c * c) / Math.abs(s)
    }
    cleanTv(e=!1, i=!0) {
        log$A.warn("[Engine] cleanTV");
        for (let o = 0; o < this.tvMeshs.length; ++o)
            this.tvMeshs[o].dispose(e, i);
        this.tvMeshs = [],
        this.meshPath = ""
    }
}
class XStats {
    constructor(e) {
        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()
          , i = this.getActiveMeshEvaluationTime()
          , o = this.getCameraRenderTime() - (i + e);
        return this.getRTT1Time() + o
    }
    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(i=>{
            e.has(i.xtype) ? e.set(i.xtype, e.get(i.xtype) + 1) : e.set(i.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
          , i = this.sceneInstrumentation.interFrameTimeCounter.lastSecAverage;
        return 1e3 / (e + i)
    }
    osVersion() {
        const e = window.navigator.userAgent;
        let i;
        return /iphone|ipad|ipod/gi.test(e) ? i = e.match(/OS (\d+)_(\d+)_?(\d+)?/) : /android/gi.test(e) && (i = e.match(/Android (\d+)/)),
        i != null && i.length > 0 ? i[0] : null
    }
}
class RunTimeArray {
    constructor() {
        this.circularData = []
    }
    add(e) {
        this.circularData.length > 1e3 && this.circularData.shift(),
        this.circularData.push(e)
    }
    getAvg() {
        let e = 0;
        for (let i = 0; i < this.circularData.length; i++)
            e += this.circularData[i];
        return {
            sum: e,
            avg: e / this.circularData.length || 0
        }
    }
    getMax() {
        let e = 0;
        for (let i = 0; i < this.circularData.length; i++)
            e < this.circularData[i] && (e = this.circularData[i]);
        return e || 0
    }
    clear() {
        this.circularData = []
    }
    getStat() {
        const e = this.getAvg()
          , i = {
            sum: e.sum,
            avg: e.avg,
            max: this.getMax()
        };
        return this.clear(),
        i
    }
}
class XEngineRunTimeStats {
    constructor() {
        this.timeArray_loadStaticMesh = new RunTimeArray,
        this.timeArray_updateStaticMesh = new RunTimeArray,
        this.timeArray_addAvatarToScene = new RunTimeArray
    }
}
const log$z = new Logger$1("XDecalManager");
class XDecalManager {
    get decals() {
        return Array.from(this._decal.values())
    }
    getMesh() {
        return this._decal
    }
    constructor(e) {
        this._decal = new Map,
        this._mat = new Map,
        this._sharedMat = new Map,
        this._scenemanager = e,
        this.scene = e.Scene
    }
    async addDecal(e) {
        const {id: i, meshPath: o, skinInfo: s="default"} = e;
        return this._decal.get(i) ? (log$z.warn(`[Engine] Cannot add decal with an existing id: [${i}], meshPath: ${o}, skinInfo:${s}`),
        Promise.resolve(!0)) : (log$z.info(`[Engine] addDecal wiht id:[${i}], meshPath: ${o}, skinInfo:${s}`),
        new Promise((c,d)=>this._scenemanager.urlTransformer(o).then(_=>new Promise((b,k)=>{
            if (this._decal.get(i))
                b(!0);
            else {
                const j = new XDecal({
                    id: i,
                    scene: this.scene,
                    meshPath: _,
                    skinInfo: s
                });
                this._decal.set(i, j),
                j.loadModel().then(()=>{
                    b(!0)
                }
                ).catch($=>{
                    log$z.error(`[Engine] addDecal Error! id: [${i}], meshpath:${o}, skin: ${s}. ${$}`),
                    k(new XDecalError(`[Engine] addDecal Error! id: [${i}], meshpath:${o}, skin: ${s}. ${$}`))
                }
                )
            }
        }
        )).then(_=>{
            _ == !0 ? c(!0) : d(!1)
        }
        ).catch(_=>{
            log$z.error(`[Engine] Add Decal error! id: [${i}], meshpath:${o}, skin:${s}. ${_}`),
            d(new XDecalError(`[Engine] addDecal  error! id: [${i}], meshpath:${o}, skin:${s}. ${_}`))
        }
        )))
    }
    setDecalTexture(e) {
        const {id: i, buffer: o, isDynamic: s=!1, width: c=1100, height: d=25, slots: _=1, visibleSlots: b=1} = e
          , k = !0;
        return log$z.info(`[Engine] setDecalTexture wiht id:[${i}]`),
        new Promise((j,$)=>{
            const _e = this._decal.get(i);
            if (_e != null)
                if (this._mat.get(i) != null)
                    this.changeDecalTexture({
                        id: i,
                        buffer: o,
                        isUrl: k,
                        isDynamic: s,
                        width: c,
                        height: d,
                        slots: _,
                        visibleSlots: b
                    }),
                    j(!0);
                else {
                    const et = new XDecalMaterial(i,this.scene);
                    et.setTexture(o, k, s, c, d, _, b).then(()=>{
                        _e.setMat(et.getMat()),
                        this._decal.set(i, _e),
                        this._mat.set(i, et),
                        j(!0)
                    }
                    ).catch(tt=>{
                        log$z.error("[Engine] setDecalTexture Error! " + tt),
                        $(new XDecalTextureError(`[Engine] decal set texture error! ${tt}`))
                    }
                    )
                }
            else
                log$z.error("[Engine] Error! decal id: [" + i + "] is not find!"),
                $(new XDecalTextureError(`[Engine] decal id: [${i}] is not find!`))
        }
        )
    }
    async shareDecal(e) {
        const {idTar: i, meshPath: o, idSrc: s, skinInfo: c="default"} = e;
        return this._decal.has(s) && !this._decal.has(i) && this._mat.has(s) && !this._mat.has(i) ? (log$z.info(`[Engine] shareDecal wiht idTar:[${i}], idSrc:[${s}], skinInfo: ${c}, meshPath: ${o}`),
        new Promise((d,_)=>this._scenemanager.urlTransformer(o).then(b=>{
            const k = new XDecal({
                id: i,
                scene: this.scene,
                meshPath: b,
                skinInfo: c
            })
              , j = this._mat.get(s);
            j != null && (k.setMat(j.getMat()),
            k.sourceMatId = s,
            this._decal.set(i, k),
            this.addSharedMatCount(s)),
            d(!0)
        }
        ).catch(b=>{
            _(new XDecalError(`[Engine] decal shareDecal error! ${b}`))
        }
        ))) : (log$z.error(`[Engine] shareDecal Error. idSrc: [${s}] not exist! or idTar: [${i}] exists!`),
        Promise.reject(`[Engine] shareDecal Error. idSrc: [${s}] not exist! or idTar: [${i}] exists!`))
    }
    changeDecalModel(e) {
        const {id: i, meshPath: o} = e
          , s = this._decal.get(i);
        return new Promise((c,d)=>s != null ? (log$z.info(`[Engine] changeDecalModel id:${i}`),
        s.changeModel(o).then(()=>{
            this._decal.set(i, s),
            c(!0)
        }
        )) : (log$z.warn(`[Engine] changeDecalModel id:${i} is not exist`),
        d(`[Engine] changeDecalModel id:${i} is not exist`)))
    }
    changeDecalTexture(e) {
        const {id: i, buffer: o, isUrl: s=!1, isDynamic: c=!1, width: d=1110, height: _=25, slots: b=1, visibleSlots: k=1} = e
          , j = this._mat.get(i);
        j != null && this._decal.has(i) ? (j.changeTexture(o, s, c, d, _, b, k),
        this._mat.set(i, j)) : log$z.error(`[Engine] changeDecalTexture Error. id:${i} is not exist`)
    }
    deleteDecal(e) {
        var i, o;
        if (this._decal.has(e)) {
            const s = this._decal.get(e);
            s != null && s.cleanMesh(),
            this._sharedMat.get(e) != null ? this.minusSharedMatCount(e) : this._mat.get(e) != null ? ((i = this._mat.get(e)) == null || i.cleanTexture(),
            this._mat.delete(e)) : ((o = s.sourceMatId) == null ? void 0 : o.length) > 0 && this.minusSharedMatCount(s.sourceMatId),
            this._decal.delete(e)
        }
    }
    deleteDecalBySkinInfo(e) {
        for (const [i,o] of this._decal.entries())
            o.skinInfo == e && this.deleteDecal(i)
    }
    addSharedMatCount(e) {
        const i = this._sharedMat.get(e);
        i != null ? this._sharedMat.set(e, i + 1) : this._sharedMat.set(e, 1)
    }
    minusSharedMatCount(e) {
        var o;
        const i = this._sharedMat.get(e);
        i != null && (this._sharedMat.set(e, i - 1),
        i == 0 && (this._sharedMat.delete(e),
        (o = this._mat.get(e)) == null || o.cleanTexture(),
        this._mat.delete(e)))
    }
    toggle(e, i) {
        const o = this._decal.get(e);
        o == null || o.toggle(i)
    }
    toggleDecalBySkinInfo(e, i) {
        for (const [o,s] of this._decal.entries())
            s.skinInfo == e && s.toggle(i)
    }
    updateTexAsWords(e, i, o={}) {
        const {clearArea: s=!0, w: c=480, h: d=480, y: _=d / 2, fontsize: b=70, slots: k=1, visibleSlots: j=1, font: $="black-body", color: _e="white", fontweight: et=100} = o;
        let {x: tt=c / 2} = o;
        const rt = this._mat.get(e);
        if (rt) {
            tt == -1 && (tt = (rt.getUOffset() + j / k) % 1 * c * k);
            const nt = rt.getMat().diffuseTexture
              , ot = nt.getContext();
            s && ot.clearRect(tt - c / 2, _ - d / 2, c, d),
            ot.textAlign = "center",
            ot.textBaseline = "middle",
            nt.drawText(i, tt, _, et + " " + b + "px " + $, _e, "transparent", !0),
            nt.hasAlpha = !0,
            nt.update()
        }
    }
    async updateTexAsImg(e, i, o={}) {
        const {clearArea: s=!0, w: c=480, h: d=480, x: _=c / 2, y: b=d / 2, clearW: k=c, clearH: j=d} = o;
        return i == null || i == null || i == "" ? (log$z.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(($,_e)=>this._scenemanager.urlTransformer(i).then(et=>new Promise((tt,rt)=>{
            const it = this._mat.get(e);
            if (it) {
                const ot = it.getMat().diffuseTexture;
                if (typeof i == "string") {
                    const at = new Image;
                    at.crossOrigin = "anonymous",
                    at.src = et,
                    at.onload = ()=>{
                        const st = ot.getContext();
                        s && st.clearRect(_ - k / 2, b - j / 2, k, j),
                        st.drawImage(at, _ - c / 2, b - d / 2, c, d),
                        ot.update(),
                        tt(!0)
                    }
                    ,
                    at.onerror = ()=>{
                        log$z.error(`[Engine] updateTexAsImg Error.newImg load error. id: [${e}], decalMat is Null or undefined!`),
                        rt(new XDecalError(`[Engine] updateTexAsImg Error. id: [${e}], decalMat is Null or undefined!`))
                    }
                } else
                    log$z.error(`[Engine] updateTexAsImg Error. id: [${e}], Buffer is not string!`),
                    rt(new XDecalError(`[Engine] updateTexAsImg Error. id: [${e}], Buffer is not string!`))
            } else
                log$z.error(`[Engine] updateTexAsImg Error. id: [${e}], decalMat is Null or undefined!`),
                rt(new XDecalError(`[Engine] updateTexAsImg Error. id: [${e}], decalMat is Null or undefined!`))
        }
        ).then(tt=>{
            tt == !0 ? $(!0) : (log$z.error(`[Engine] updateTexAsImg Error. id: [${e}] !`),
            _e(new XDecalError(`[Engine] updateTexAsImg error! id: [${e}]`)))
        }
        ).catch(tt=>{
            log$z.error(`[Engine] updateTexAsImg Error. id: [${e}]. ${tt}`)
        }
        )))
    }
    startAnime(e, i) {
        log$z.info(`[Engine] Decal Start Anime. [${e}]`);
        const {speed: o=.001, callback: s} = i
          , c = this._mat.get(e);
        c ? (c.do_animation(o),
        s && c.uOffsetObserverable.add(s)) : (log$z.error(`[Engine] startAnime Error. id: [${e}] is not exist!`),
        new XDecalError(`[Engine] startAnime Error. id: [${e}] is not exist!`))
    }
}
class XDecalMaterial {
    constructor(e, i) {
        this._speed = .001,
        this._slots = 1,
        this._visibleSlots = 1,
        this._animeObserver = null,
        this.reg_mat_update = ()=>{
            const o = this._mat.diffuseTexture;
            o != null && (o.uOffset = o.uOffset + this._speed,
            o.uOffset > 1 && (o.uOffset -= 1),
            Math.round(o.uOffset % (1 / this._slots) / this._speed) == 0 && this._uOffsetObserverable.notifyObservers(this))
        }
        ,
        this.setTexture = async(o,s=!0,c=!1,d=1,_=1,b=1,k=1)=>new Promise((j,$)=>{
            this._slots = b,
            this._visibleSlots = k;
            const _e = this._tex;
            c ? (this._tex = new DynamicTexture("dyTex",{
                width: d,
                height: _
            },this.scene,!0,Texture.BILINEAR_SAMPLINGMODE),
            this._tex.name = "decal_dy_" + this._id,
            this._tex.uScale = k / b,
            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,
            _e != null && _e.dispose(),
            j(!0)) : !c && s && typeof o == "string" ? this._tex = new Texture(o,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,
                _e != null && _e.dispose(),
                j(!0)
            }
            ,()=>{
                log$z.error("[Engine] decal create texture error!"),
                $(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,
                _e != null && _e.dispose(),
                j(!0)
            }
            ,()=>{
                log$z.error("[Engine] decal create texture error!"),
                $(new XDecalTextureError("[Engine] decal create texture error!"))
            }
            ,o,!0)
        }
        ),
        this._id = e,
        this.scene = i,
        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, i=!1, o=!1, s=1, c=1, d=1, _=1) {
        return this._mat == null || this._tex == null ? (log$z.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, i, o, s, c, d, _)
    }
    cleanTexture() {
        log$z.info("[Engine] Decal clean Texture"),
        this.scene.onBeforeRenderObservable.remove(this._animeObserver),
        this._uOffsetObserverable.clear(),
        this._tex.dispose(),
        this._mat.dispose()
    }
}
class XDecal {
    constructor(e) {
        this._low_model = [],
        this._mat = null,
        this.sourceMatId = "",
        this.loadModel = async()=>new Promise((d,_)=>{
            typeof this.meshPath == "string" ? SceneLoader.LoadAssetContainerAsync("", this.meshPath, this.scene, null, ".glb").then(b=>{
                for (let k = b.materials.length - 1; k >= 0; --k)
                    b.materials[k].dispose();
                for (let k = 0; k < b.meshes.length; ++k)
                    b.meshes[k].visibility = 1,
                    b.meshes[k].isPickable = !0,
                    b.meshes[k].checkCollisions = !1,
                    "hasVertexAlpha"in b.meshes[k] && (b.meshes[k].hasVertexAlpha = !1),
                    this.scene.addMesh(b.meshes[k]),
                    this._low_model.push(new XStaticMesh({
                        id: this._id,
                        mesh: b.meshes[k],
                        xtype: EMeshType.Decal,
                        skinInfo: this._skinInfo
                    })),
                    this.toggle(!1);
                d(!0)
            }
            ).catch(b=>{
                _(new XDecalError(`[Engine] decal load model error! ${b}`))
            }
            ) : _(new XDecalError("[Engine] decal inport mesh is not string!"))
        }
        ).catch(d=>{
            new XDecalError(`[Engine] decal loadModel ${d}`)
        }
        );
        const {id: i, scene: o, meshPath: s, skinInfo: c="default"} = e;
        this._id = i,
        this.scene = o,
        this.meshPath = s,
        this._skinInfo = c
    }
    get skinInfo() {
        return this._skinInfo
    }
    getMesh() {
        return this._low_model
    }
    getMat() {
        return this._mat
    }
    get id() {
        return this._id
    }
    toggle(e) {
        for (let i = 0; i < this._low_model.length; ++i)
            e == !0 ? this._low_model[i].show() : this._low_model[i].hide()
    }
    setMat(e) {
        this._mat = e;
        for (let i = 0; i < this._low_model.length; ++i)
            this._low_model[i].mesh.material = this._mat;
        this.toggle(!0)
    }
    changeModel(e="") {
        return e != "" && (this.meshPath = e),
        this.meshPath == "" ? (log$z.error("[Engine] changeModel Error! meshPath is empty"),
        Promise.reject(new XDecalTextureError("[Engine] changeModel Error! meshPath is empty"))) : new Promise((i,o)=>SceneLoader.LoadAssetContainerAsync("", this.meshPath, this.scene, null, ".glb").then(s=>{
            for (let d = s.materials.length - 1; d >= 0; --d)
                s.materials[d].dispose();
            const c = [];
            for (let d = 0; d < s.meshes.length; ++d)
                s.meshes[d].visibility = 0,
                s.meshes[d].isPickable = !0,
                s.meshes[d].checkCollisions = !1,
                "hasVertexAlpha"in s.meshes[d] && (s.meshes[d].hasVertexAlpha = !1),
                this._mat != null && (s.meshes[d].material = this._mat),
                this.scene.addMesh(s.meshes[d]),
                c.push(new XStaticMesh({
                    id: this._id,
                    mesh: s.meshes[d],
                    xtype: EMeshType.Decal,
                    skinInfo: this._skinInfo
                }));
            e != "" && this.cleanMesh(),
            this._low_model = c,
            this._mat != null && this.toggle(!0),
            i(this)
        }
        ).catch(s=>{
            log$z.error("[Engine] Create decal error! " + s),
            o(new XDecalError("[Engine] Create decal error! " + s))
        }
        ))
    }
    cleanMesh(e=!1, i=!1) {
        log$z.info("[Engine] Decal Model clean mesh");
        for (let o = 0; o < this._low_model.length; ++o)
            this._low_model[o].dispose(e, i)
    }
}
const log$y = new Logger$1("XBreathPointManager");
class XBreathPointManager {
    constructor(e) {
        this.materialMap = new Map,
        this.breathPoints = new Map,
        this._allIds = new Set,
        this._loopBPKeys = [],
        this.addBreathPoint = async i=>{
            const o = [{
                url: "https://static.xverse.cn/qqktv/texture.png"
            }];
            if (o.length <= 0) {
                log$y.warn("[Engine] BreathPoint get texture list error: textureList.length <= 0"),
                new XBreathPointError("[Engine] BreathPoint get texture list error!");
                return
            }
            const s = o[0]
              , {id: c, spriteSheet: d=s.url, spriteWidthNumber: _=20, spriteHeightNumber: b=1, position: k, rotation: j={
                pitch: -90,
                yaw: 270,
                roll: 0
            }, size: $=.6, width: _e=-1, height: et=-1, fps: tt=30, billboardMode: rt=!1, forceLeaveGround: it=!1, type: nt="default", lifeTime: ot=-1, backfaceculling: at=!0, maxVisibleRegion: st=-1, skinInfo: ut="default"} = i;
            if (this.breathPoints.get(c)) {
                log$y.warn("[Engine] Cannot add breathPoint with an existing id: [" + c + "]"),
                new XBreathPointError("[Engine] Cannot add breathPoint with an existing id: [" + c + "]");
                return
            }
            if (it) {
                const mt = this.castRay(new Vector3(k.x,k.y,k.z)) * scaleFromUE4toXverse;
                mt != 0 ? k.z = k.z - mt + 1 : k.z = k.z + 1
            }
            let ct;
            if (this.materialMap.get(nt)) {
                const mt = this.materialMap.get(nt);
                mt.count = mt.count + 1,
                ct = mt.mat
            } else {
                const mt = new Texture(d,this._scene,!0,!0,Texture.BILINEAR_SAMPLINGMODE,null,()=>{
                    log$y.error("[Engine] Breathpoint create texture error."),
                    new XBreathPointError("[Engine] Breathpoint create texture error.")
                }
                ,null,!0);
                mt.name = "TexBreathPoint_" + c,
                ct = new StandardMaterial(`MaterialBreathPoint_${c}`,this._scene),
                ct.alpha = 1,
                ct.emissiveTexture = mt,
                ct.backFaceCulling = at,
                ct.diffuseTexture = mt,
                ct.diffuseTexture.hasAlpha = !0,
                ct.useAlphaFromDiffuseTexture = !0,
                this.materialMap.set(nt, {
                    mat: ct,
                    count: 1,
                    lastRenderTime: Date.now(),
                    fps: tt,
                    spriteWidthNumber: _,
                    spriteHeightNumber: b,
                    spriteSheet: d,
                    texture: mt
                })
            }
            const lt = new Array(6);
            for (let mt = 0; mt < 6; mt++)
                lt[mt] = new Vector4(0,0,0,0);
            lt[0] = new Vector4(0,0,1 / _,1 / b),
            lt[1] = new Vector4(0,0,1 / _,1 / b);
            let ft = {};
            _e > 0 && et > 0 ? ft = {
                width: _e,
                height: et,
                depth: .01,
                faceUV: lt
            } : ft = {
                size: $,
                depth: .01,
                faceUV: lt
            };
            const ht = MeshBuilder.CreateBox(c, ft, this._scene);
            ht.material = ct;
            const pt = new XStaticMesh({
                id: c,
                mesh: ht,
                xtype: EMeshType.XBreathPoint,
                skinInfo: ut
            });
            let dt = j;
            rt && (ht.billboardMode = Mesh.BILLBOARDMODE_ALL,
            pt.allowMove(),
            dt = {
                pitch: 0,
                yaw: 270,
                roll: 0
            });
            const _t = new BreathPoint({
                type: nt,
                mesh: pt,
                id: c,
                position: k,
                rotation: dt,
                mat: ct,
                maxVisibleRegion: st,
                scene: this._scene,
                skinInfo: ut
            });
            this.breathPoints.set(c, _t),
            this._allIds.add(c),
            ot > 0 && setTimeout(()=>{
                this.clearBreathPoints(c)
            }
            , ot * 1e3)
        }
        ,
        this.reg_breathpoint_update = ()=>{
            const i = new Date().getTime();
            if (this.materialMap != null)
                for (const [o,s] of this.materialMap)
                    i - s.lastRenderTime > 1e3 / s.fps && (s.lastRenderTime = i,
                    Math.abs(s.mat.diffuseTexture.uOffset - (1 - 1 / s.spriteWidthNumber)) < 1e-6 ? (s.mat.diffuseTexture.uOffset = 0,
                    Math.abs(s.mat.diffuseTexture.vOffset - (1 - 1 / s.spriteHeightNumber)) < 1e-6 ? s.mat.diffuseTexture.vOffset = 0 : s.mat.diffuseTexture.vOffset += 1 / s.spriteHeightNumber) : s.mat.diffuseTexture.uOffset += 1 / s.spriteWidthNumber)
        }
        ,
        this.reg_breathpoint_autovisible = ()=>{
            if (this._scene.getFrameId() % 2 == 0)
                if (this._loopBPKeys.length == 0)
                    this._loopBPKeys = Array.from(this._allIds);
                else {
                    const i = this._getMainPlayerPosition();
                    for (let o = 0; o < 5 && this._loopBPKeys.length > 0; ++o) {
                        const s = this._loopBPKeys.pop();
                        if (s != null) {
                            const c = this.getBreathPoint(s);
                            if (c != null && c.maxvisibleregion >= 0 && c.mesh.visibility == 1) {
                                const d = c.mesh.position;
                                calcDistance3DVector(i, d) >= c.maxvisibleregion ? c == null || c.removeFromScene() : c == null || c.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 [i,o] of this.breathPoints.entries())
            o.toggleVisibility(e)
    }
    toggleBPVisibilityBySkinInfo(e, i) {
        for (const [o,s] of this.breathPoints.entries())
            s.skinInfo == e && s.toggleVisibility(i)
    }
    toggleBPVisibilityById(e, i) {
        const o = this.getBreathPoint(e);
        o != null && o.toggleVisibility(i)
    }
    getBreathPointBySkinInfo(e) {
        const i = [];
        for (const [o,s] of this.breathPoints.entries())
            s.skinInfo == e && i.push(s);
        return i
    }
    getAllBreathPoint() {
        return this.breathPoints
    }
    getBreathPoint(e) {
        return this.breathPoints.get(e)
    }
    delete(e) {
        const i = this.breathPoints.get(e);
        if (i != null) {
            i.dispose(),
            this._allIds.delete(e);
            const o = this.materialMap.get(i._type);
            o != null && (o.count = o.count - 1,
            o.count <= 0 && (o.count = 0,
            o.texture.dispose(),
            o.mat.dispose(!0, !0),
            this.materialMap.delete(i._type))),
            this.breathPoints.delete(e)
        }
    }
    castRay(e) {
        var _;
        e = ue4Position2Xverse({
            x: e.x,
            y: e.y,
            z: e.z
        });
        const i = new Vector3(0,-1,0)
          , o = new Ray(e,i,length)
          , s = []
          , c = (_ = this._sceneManager) == null ? void 0 : _.getGround({
            x: e.x,
            y: e.y,
            z: e.z
        });
        let d = o.intersectsMeshes(c);
        if (d.length > 0) {
            const b = d[0];
            if (b && b.pickedMesh) {
                const k = b.distance;
                i.y = 1;
                const j = o.intersectsMeshes(s);
                let$ = 1e8;
                if (j.length > 0) {
                    const _e = j[0];
                    return _e && _e.pickedMesh && ($ = -_e.distance),
                    $ == 1e8 ? k : Math.abs($) < Math.abs(k) ? $ : k
                }
            }
        } else if (i.y = 1,
        d = o.intersectsMeshes(s),
        d.length > 0) {
            const b = d[0];
            if (b && b.pickedMesh)
                return b.distance
        }
        return 0
    }
    changePickable(e) {
        for (const [i,o] of this.breathPoints.entries())
            o.changePickable(e)
    }
    clearBreathPoints(e) {
        log$y.info(`[Engine] clearBreathPoints: ${e}`);
        for (const [i,o] of this.breathPoints.entries())
            (o._type == e || o._id == e) && this.delete(o._id)
    }
    clearBreathPointsBySkinInfo(e) {
        log$y.info(`[Engine] clearBreathPointsBySkinInfo: ${e}`);
        for (const [i,o] of this.breathPoints.entries())
            o.skinInfo == e && this.delete(o._id)
    }
    clearAllBreathPoints() {
        log$y.info("[Engine] ClearAllBreathPoints");
        for (const [e,i] of this.breathPoints.entries())
            this.delete(i._id)
    }
    _getMainPlayerPosition() {
        var o;
        const e = this._sceneManager.cameraComponent.MainCamera.position
          , i = this._sceneManager.avatarComponent.getMainAvatar();
        if (i != null && i != null) {
            const s = (o = i == null ? void 0 : i.rootNode) == null ? void 0 : o.position;
            if (s != null)
                return s
        }
        return e
    }
    changeBreathPointPose(e, i, o) {
        const s = new Vector3(e.position.x,e.position.y,e.position.z);
        if (this.breathPoints.get(o) != null) {
            log$y.info(`[Engine] changeBreathPointPose, id:${o}`);
            const c = this.breathPoints.get(o)
              , d = c.mesh.position;
            let _ = d.subtract(s);
            _ = Vector3.Normalize(_);
            const b = Vector3.Distance(d, s)
              , k = new Ray(s,_,b)
              , j = this._scene.multiPickWithRay(k);
            if (j) {
                for (let$ = 0; $ < j.length; $++)
                    if (j[$].pickedMesh != null && i.mesh.name.indexOf(j[$].pickedMesh.name) >= 0) {
                        const _e = j[$].pickedPoint;
                        c.mesh.position = s.add(_e.subtract(s).scale(.99)),
                        this.breathPoints.set(o, c)
                    }
            }
        } else
            log$y.warn(`[Engine] changeBreathPointPose, id:${o} is not existing!`)
    }
}
class BreathPoint {
    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
    }
    constructor(e) {
        const {mesh: i, id: o, position: s, rotation: c, mat: d, type: _="default", maxVisibleRegion: b=-1, scene: k, skinInfo: j="default"} = e;
        this._id = o,
        i.mesh.position = ue4Position2Xverse(s),
        i.mesh.rotation = ue4Rotation2Xverse(c),
        this._staticmesh = i,
        this._mat = d,
        this._type = _,
        this._maxVisibleRegion = b,
        this._scene = k,
        this._skinInfo = j,
        this._isInScene = !0
    }
    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, i) {
        this.scene = e,
        this._videoRawYUVTexture = [],
        this.videosResOriArray = i,
        this._currentVideoId = -1;
        for (let o = 0; o < i.length; ++o)
            (s=>{
                const c = RawTexture.CreateLuminanceTexture(null, i[s].width, i[s].height * 1.5, this.scene, !1, !0);
                c.name = "videoTex_" + i[s].width + "_" + i[s].height,
                this._videoRawYUVTexture.push(c)
            }
            )(o)
    }
    inRange(e) {
        return e >= 0 && e < this._videoRawYUVTexture.length
    }
    getVideoYUVTex(e) {
        return this.inRange(e) ? this._videoRawYUVTexture[e] : null
    }
    findId(e, i) {
        let o = 0;
        for (let s = 0; s < this.videosResOriArray.length; ++s)
            if (this.videosResOriArray[s].width == e && this.videosResOriArray[s].height == i) {
                o = s;
                break
            }
        return o
    }
    getCurrentVideoTexId() {
        return this._currentVideoId
    }
    setCurrentVideoTexId(e) {
        this._currentVideoId = e
    }
}
const log$x = new Logger$1("XMaterial");
var EShaderMode = (a=>(a[a.default = 0] = "default",
a[a.video = 1] = "video",
a[a.videoAndPano = 2] = "videoAndPano",
a))(EShaderMode || {});
class XMaterialComponent {
    constructor(e, i) {
        this._inputYUV420 = !0,
        this._inputPanoYUV420 = !0,
        this._isUpdateYUV = !0,
        this.initMaterial = async()=>new Promise((o,s)=>{
            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,
            o(!0)
        }
        ),
        this._initPureVideoContent = o=>{
            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(o)
            }
            )) : (this._videoElement = o.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: o.fov
                })
            }
            ),
            this._lowModelShader.setTexture("texture_video", this._videoTexture),
            this._lowModelShader.setFloat("isYUV", 0))
        }
        ,
        this._changePureVideoLowModelShaderCanvasSize = o=>{
            var b;
            const s = o.fov || 50
              , c = o.width || 720
              , d = o.height || 1280
              , _ = c / (2 * Math.tan(Math.PI * s / 360));
            (b = this._lowModelShader) == null || b.setVector3("focal_width_height", new Vector3(_,c,d))
        }
        ,
        this.updateRawYUVData = (o,s,c,d=-1)=>{
            var _, b;
            if (d == -1 && (d = this.yuvInfo.fov),
            this._isUpdateYUV == !0) {
                const k = {
                    width: s,
                    height: c,
                    fov: d
                }
                  , j = this._videoRawYUVTexArray.findId(s, c)
                  , $ = this._videoRawYUVTexArray.getCurrentVideoTexId();
                ($ < 0 || j != $ || d != this.yuvInfo.fov) && (this.yuvInfo.width = s,
                this.yuvInfo.height = c,
                this.yuvInfo.fov = d,
                this._videoRawYUVTexArray.setCurrentVideoTexId(j),
                this._changeVideoRes(j),
                this.changeCameraFovWithShaderUpdate(k),
                this._scenemanager.yuvInfo = k),
                (_ = this._videoRawYUVTexArray.getVideoYUVTex(j)) == null || _.update(o),
                (b = this._videoRawYUVTexArray.getVideoYUVTex(j)) == null || b.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE)
            }
        }
        ,
        this._changeVideoRes = o=>{
            this._lowModelShader.setTexture("texture_video", this._videoRawYUVTexArray.getVideoYUVTex(o))
        }
        ,
        this.initDynamicData = (o,s,c)=>new Promise((d,_)=>{
            this.setDynamicSize(o).then(b=>{
                if (b) {
                    for (let k = 0; k < o; ++k)
                        (j=>{
                            this.initDynamicTexture(j, s, c),
                            this.initDynamicShaders(j).then(()=>{
                                this._updatePanoShaderInput(j)
                            }
                            )
                        }
                        )(k);
                    d(!0)
                } else
                    _(new XMaterialError(`[Engine] DynamicRoomSize (${o}) is too small`))
            }
            )
        }
        ).catch(d=>log$x.error(`[Engine] ${d}`)),
        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)
        }
        ,
        this._initPureVideoShader = ()=>{
            if (this._lowModelShader == null) {
                const o = new ShaderMaterial("PureVideoShader",this.scene,{
                    vertexSource: pureVideoVertex,
                    fragmentSource: pureVideoFragment
                },{
                    attributes: ["uv", "position", "world0", "world1", "world2", "world3"],
                    uniforms: ["view", "projection", "worldViewProjection", "world"],
                    defines: ["#define SHADOWFULLFLOAT"]
                });
                o.setTexture("shadowSampler", null),
                o.setMatrix("lightSpaceMatrix", null),
                o.setFloat("haveShadowLight", 0),
                o.setTexture("texture_video", null),
                o.setFloat("isYUV", this._inputYUV420 ? 1 : 0),
                o.setFloat("fireworkLight", 0),
                o.setVector3("fireworkLightPosition", new Vector3(0,0,0)),
                o.setVector3("focal_width_height", new Vector3(772.022491,720,1280)),
                o.backFaceCulling = !1,
                this._lowModelShader = o
            }
        }
        ,
        this.setDynamicSize = o=>new Promise((s,c)=>{
            o >= 1 && o <= 100 ? (this._dynamic_size = o,
            s(!0)) : (this._dynamic_size = 1,
            s(!1))
        }
        ),
        this._isInDynamicRange = o=>o < this._dynamic_size && o >= 0,
        this.initDynamicTexture = (o,s,c)=>{
            this._isInDynamicRange(o) && (this._dynamic_textures[o] != null && (this._dynamic_textures[o].dispose(),
            this._dynamic_textures[o] = null),
            this._dynamic_textures[o] = new RawTexture(null,s,c * 1.5,Engine.TEXTUREFORMAT_LUMINANCE,this.scene,!1,!0,Texture.NEAREST_SAMPLINGMODE,Engine.TEXTURETYPE_UNSIGNED_BYTE),
            this._dynamic_textures[o].name = "Pano_Dynamic_" + o + "_" + Date.now())
        }
        ,
        this.initDynamicShaders = o=>(log$x.info("[Engine] Material init dynamic shader."),
        new Promise((s,c)=>{
            this._dynamic_shaders[o] != null && this._dynamic_shaders[o].dispose();
            const d = new ShaderMaterial("Pano_Shader_" + o,this.scene,{
                vertexSource: panoVertex,
                fragmentSource: panoFragment
            },{
                attributes: ["uv", "position", "world0", "world1", "world2", "world3"],
                uniforms: ["view", "projection", "worldViewProjection", "world"],
                defines: ["#define SHADOWFULLFLOAT"]
            });
            d.setTexture("texture_pano", null),
            d.setVector3("centre_pose", new Vector3(0,0,0)),
            d.setFloat("isYUV", this._inputPanoYUV420 ? 1 : 0),
            d.setTexture("shadowSampler", null),
            d.setMatrix("lightSpaceMatrix", null),
            d.setFloat("haveShadowLight", 0),
            d.setFloat("fireworkLight", 0),
            d.setVector3("fireworkLightPosition", new Vector3(0,0,0)),
            d.backFaceCulling = !1,
            this._dynamic_shaders[o] = d,
            s(!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,i.videoResOriArray),
        this.shaderMode = i.shaderMode,
        i.yuvInfo != null && (this.yuvInfo = i.yuvInfo),
        i.panoInfo != null && this.setPanoInfo(i.panoInfo)
    }
    stopYUVUpdate() {
        this._isUpdateYUV = !1
    }
    allowYUVUpdate() {
        this._isUpdateYUV = !0
    }
    setPanoInfo(e) {
        this._panoInfo = e
    }
    _prepareRender(e) {
        e && (this._initPureVideoContent(e),
        this._updatePureVideoShaderInput())
    }
    changeCameraFovWithShaderUpdate(e) {
        this._changePureVideoLowModelShaderCanvasSize(e),
        this._scenemanager.cameraComponent.cameraFovChange(e)
    }
    getPureVideoShader() {
        return this._lowModelShader
    }
    getDefaultShader() {
        return this._defaultShader
    }
    updatePanoPartYUV(e, i, o) {
        const s = i.subarray(0, o.width * o.height)
          , c = i.subarray(o.width * o.height, o.width * o.height * 1.25)
          , d = i.subarray(o.width * o.height * 1.25)
          , _ = this._panoInfo.width
          , b = this._panoInfo.height;
        if (this._dynamic_textures[e] != null) {
            const k = this._dynamic_textures[e].getInternalTexture();
            if (k != null && k != null) {
                const j = this.engine._getTextureTarget(k);
                this.engine._bindTextureDirectly(j, k, !0),
                this.engine.updateTextureData(k, s, o.startX, b * 1.5 - o.startY - o.height, o.width, o.height),
                this.engine.updateTextureData(k, c, o.startX * .5, (b - o.startY - o.height) * .5, o.width * .5 - 1, o.height * .5 - 1),
                this.engine.updateTextureData(k, d, o.startX * .5 + _ * .5, (b - o.startY - o.height) * .5, o.width * .5, o.height * .5),
                this.engine._bindTextureDirectly(j, null)
            }
        }
    }
    changePanoImg(e, i) {
        if (log$x.info(`[Engine] changePanoImg, id=${e}, pose=${i.pose.position.x},${i.pose.position.y},${i.pose.position.z}`),
        !this._isInDynamicRange(e))
            return log$x.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 o = ue4Position2Xverse(i.pose.position);
        return o && (this._dynamic_babylonpose[e] = {
            position: o
        }),
        new Promise((s,c)=>{
            try {
                typeof i.data == "string" ? (this.setPanoYUV420(!1),
                this._dynamic_textures[e].updateURL(i.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(i.data),
                this._dynamic_textures[e].updateSamplingMode(Texture.NEAREST_SAMPLINGMODE)),
                s(this)
            } catch (d) {
                c(new XMaterialError(`[Engine] ChangePanoImg Error! ${d}`))
            }
        }
        ).then(s=>(i.fov != null && this._scenemanager.cameraComponent.changeCameraFov(i.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, i, o, s, c, d, _, b, k, j;
        if (this.scene.getLightByName("AvatarLight") ? ((e = this._lowModelShader) == null || e.setFloat("haveShadowLight", 1),
        (s = this._lowModelShader) == null || s.setTexture("shadowSampler", (o = (i = this.scene.getLightByName("AvatarLight")) == null ? void 0 : i.getShadowGenerator()) == null ? void 0 : o.getShadowMapForRendering()),
        (_ = this._lowModelShader) == null || _.setMatrix("lightSpaceMatrix", (d = (c = this.scene.getLightByName("AvatarLight")) == null ? void 0 : c.getShadowGenerator()) == null ? void 0 : d.getTransformMatrix())) : ((b = this._lowModelShader) == null || b.setTexture("shadowSampler", this._videoRawYUVTexArray.getVideoYUVTex(0)),
        (k = this._lowModelShader) == null || k.setMatrix("lightSpaceMatrix", new Matrix),
        (j = this._lowModelShader) == null || j.setFloat("haveShadowLight", 0)),
        this.scene.getLightByName("fireworkLight"))
            this.scene.registerBeforeRender(()=>{
                var $;
                this._lowModelShader.setFloat("fireworkLight", this.scene.getLightByName("fireworkLight").getScaledIntensity()),
                this._lowModelShader.setVector3("fireworkLightPosition", ($ = this.scene.getLightByName("fireworkLight")) == null ? void 0 : $.position)
            }
            );
        else {
            const $ = new PointLight("fireworkLight",new Vector3(0,0,0),this.scene);
            $.intensity = 0
        }
    }
    _updatePanoShaderInput(e) {
        var i, o, s, c, d, _, b, k, j, $;
        if (this._isInDynamicRange(e))
            if (this.scene.getLightByName("AvatarLight") ? ((i = this._dynamic_shaders[e]) == null || i.setFloat("haveShadowLight", 1),
            (c = this._dynamic_shaders[e]) == null || c.setTexture("shadowSampler", (s = (o = this.scene.getLightByName("AvatarLight")) == null ? void 0 : o.getShadowGenerator()) == null ? void 0 : s.getShadowMapForRendering()),
            (b = this._dynamic_shaders[e]) == null || b.setMatrix("lightSpaceMatrix", (_ = (d = this.scene.getLightByName("AvatarLight")) == null ? void 0 : d.getShadowGenerator()) == null ? void 0 : _.getTransformMatrix())) : ((k = this._lowModelShader) == null || k.setTexture("shadowSampler", this._videoRawYUVTexArray.getVideoYUVTex(0)),
            (j = this._lowModelShader) == null || j.setMatrix("lightSpaceMatrix", new Matrix),
            ($ = this._lowModelShader) == null || $.setFloat("haveShadowLight", 0)),
            this.scene.getLightByName("fireworkLight"))
                this.scene.registerBeforeRender(()=>{
                    var _e;
                    this._dynamic_shaders[e].setFloat("fireworkLight", this.scene.getLightByName("fireworkLight").getScaledIntensity()),
                    this._dynamic_shaders[e].setVector3("fireworkLightPosition", (_e = this.scene.getLightByName("fireworkLight")) == null ? void 0 : _e.position)
                }
                );
            else {
                const _e = new PointLight("fireworkLight",new Vector3(0,0,0),this.scene);
                _e.intensity = 0
            }
    }
}
class XCameraComponent {
    constructor(e, i, o) {
        this.maincameraRotLimitObserver = null,
        this.forceKeepVertical = !1,
        this.initCamera = s=>{
            const {maxZ: c=1e4, minZ: d=.1, angularSensibility: _=2e3} = s;
            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 = _,
            this.mainCamera.setTarget(new Vector3(0,1010,0)),
            this.mainCamera.minZ = d,
            this.mainCamera.fov = Math.PI * this.yuvInfo.fov / 180,
            this.mainCamera.maxZ = c,
            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 = c,
            this.cgCamera.minZ = d,
            this.cgCamera.fovMode = Camera$1.FOVMODE_HORIZONTAL_FIXED,
            this.cameraFovChange(this.yuvInfo)
        }
        ,
        this.cameraFovChange = s=>{
            this.yuvInfo = s;
            const c = s.width
              , d = s.height
              , _ = this.canvas.width
              , b = this.canvas.height
              , k = s.fov;
            if (this.forceKeepVertical == !0) {
                const j = c / (2 * Math.tan(Math.PI * k / 360))
                  , $ = 2 * Math.atan(d / (2 * j));
                this.mainCamera.fov = $,
                this.cgCamera.fov = $,
                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,
            _ / b < c / d && this.mainCamera.fov) {
                const j = b
                  , $ = _
                  , _e = j * c / d / (2 * Math.tan(k * Math.PI / 360))
                  , et = 2 * Math.atan($ / (2 * _e));
                this.mainCamera.fov = et,
                this.cgCamera.fov = et
            } else
                this.mainCamera.fov = Math.PI * k / 180,
                this.cgCamera.fov = Math.PI * k / 180
        }
        ,
        this.setCameraPose = s=>{
            var _;
            const c = ue4Position2Xverse(s.position);
            let d = null;
            s.rotation != null && (d = ue4Rotation2Xverse(s.rotation)),
            this._cameraPose = {
                position: c
            },
            d != null && (this._cameraPose.rotation = d),
            this.scene.activeCamera === this.mainCamera && !((_ = this.mainCamera) != null && _.isDisposed()) && this._setCamPositionRotation(this.mainCamera, this._cameraPose)
        }
        ,
        this._setCamPositionRotation = (s,c)=>{
            var d, _;
            c.position && (s.position = (d = c.position) == null ? void 0 : d.clone()),
            c.rotation && (s.rotation = (_ = c.rotation) == null ? void 0 : _.clone())
        }
        ,
        this.switchCamera = s=>{
            var c;
            (c = this.scene.activeCamera) == null || c.detachControl(this.canvas),
            this.scene.activeCamera = s
        }
        ,
        this.reCalXYZRot = (s,c)=>(s = s % (2 * Math.PI),
        Math.abs(c - s) >= Math.PI && (s = s - 2 * Math.PI),
        s),
        this._moveCam = (s,c,d,_,b,k,j,$)=>{
            const _e = (st,ut,ct)=>(st.x = this.reCalXYZRot(st.x, ut.x),
            st.y = this.reCalXYZRot(st.y, ut.y),
            st.z = this.reCalXYZRot(st.z, ut.z),
            new Vector3((ut.x - st.x) * ct + st.x,(ut.y - st.y) * ct + st.y,(ut.z - st.z) * ct + st.z))
              , et = function(st, ut, ct) {
                return new Vector3((ut.x - st.x) * ct + st.x,(ut.y - st.y) * ct + st.y,(ut.z - st.z) * ct + st.z)
            }
              , tt = new Animation("myAnimation1","position",j,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT);
            let rt = []
              , it = c
              , nt = d;
            for (let st = 0; st < k; ++st)
                rt.push({
                    frame: st,
                    value: et(it, nt, st / k)
                });
            rt.push({
                frame: rt.length,
                value: et(it, nt, 1)
            }),
            tt.setKeys(rt);
            const ot = new Animation("myAnimation2","rotation",j,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT);
            rt = [],
            it = _,
            nt = b;
            for (let st = 0; st < k; ++st)
                rt.push({
                    frame: st,
                    value: _e(it, nt, st / k)
                });
            rt.push({
                frame: rt.length,
                value: _e(it, nt, 1)
            }),
            ot.setKeys(rt),
            s.animations.push(ot),
            s.animations.push(tt);
            const at = this.scene.beginAnimation(s, 0, k, !1);
            at.onAnimationEnd = ()=>{
                $(),
                at.stop(),
                at.animationStarted = !1
            }
        }
        ,
        this.scene = i,
        this.canvas = e,
        this.yuvInfo = o.yuvInfo,
        o.forceKeepVertical != null && (this.forceKeepVertical = o.forceKeepVertical),
        this.initCamera(o.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: i=1e4, minZ: o=.1, angularSensibility: s=2e3} = e;
        this.mainCamera.maxZ = i,
        this.mainCamera.minZ = o,
        this.mainCamera.angularSensibility = s
    }
    getMainCameraInfo() {
        return {
            maxZ: this.mainCamera.maxZ,
            minZ: this.mainCamera.minZ,
            angularSensibility: this.mainCamera.angularSensibility
        }
    }
    _limitAngle(e, i) {
        return Math.abs(Math.abs(i[0] - i[1]) - 360) < 1e-6 || (e = (e % 360 + 360) % 360,
        i[0] = (i[0] % 360 + 360) % 360,
        i[1] = (i[1] % 360 + 360) % 360,
        i[0] > i[1] ? e > i[1] && e < i[0] && (Math.abs(e - i[0]) < Math.abs(e - i[1]) ? e = i[0] : e = i[1]) : e < i[0] ? e = i[0] : e > i[1] && (e = i[1])),
        e
    }
    setMainCameraRotationLimit(e, i) {
        this.maincameraRotLimitObserver != null && this.removeMainCameraRotationLimit();
        const o = this.mainCamera
          , {yaw: s, pitch: c, roll: d} = e
          , {yaw: _, pitch: b, roll: k} = i;
        if (_ < 0 || b < 0 || k < 0)
            throw new Error("\u76F8\u673A\u65CB\u8F6C\u9650\u5236\u53EA\u80FD\u8BBE\u7F6E\u4E3A\u5927\u4E8E0");
        const j = [c - b, c + b]
          , $ = [s - _, s + _]
          , _e = [d - k, d + k];
        this.maincameraRotLimitObserver = o.onAfterCheckInputsObservable.add(()=>{
            let {pitch: et, yaw: tt, roll: rt} = xverseRotation2Ue4(o.rotation);
            et = this._limitAngle(et, j),
            tt = this._limitAngle(tt, $),
            rt = this._limitAngle(rt, _e),
            o.rotation = ue4Rotation2Xverse({
                pitch: et,
                yaw: tt,
                roll: rt
            })
        }
        )
    }
    setMainCameraRotationLimitByAnchor(e, i, o) {
        this.maincameraRotLimitObserver != null && this.removeMainCameraRotationLimit();
        const s = this.mainCamera
          , c = ue4Rotation2Xverse_mesh(i)
          , d = ue4Rotation2Xverse_mesh(o);
        d != null && c != null && e.mesh != null && (this.maincameraRotLimitObserver = s.onAfterCheckInputsObservable.add(()=>{
            const _ = e.mesh.rotation;
            o.yaw > 0 && (s.rotation.y <= _.y - d.y + c.y ? s.rotation.y = _.y - d.y + c.y : s.rotation.y >= _.y + d.y + c.y && (s.rotation.y = _.y + d.y + c.y)),
            o.pitch > 0 && (s.rotation.x <= _.x - d.x + c.x ? s.rotation.x = _.x - d.x + c.x : s.rotation.x >= _.x + d.x + c.x && (s.rotation.x = _.x + d.x + c.x)),
            o.roll > 0 && (s.rotation.z <= _.z - d.z + c.z ? s.rotation.z = _.z - d.z + c.z : s.rotation.z >= _.z + d.z + c.z && (s.rotation.z = _.z + d.z + c.z))
        }
        ))
    }
    getCameraPose() {
        const e = xversePosition2Ue4({
            x: this.mainCamera.position.x,
            y: this.mainCamera.position.y,
            z: this.mainCamera.position.z
        })
          , i = xverseRotation2Ue4({
            x: this.mainCamera.rotation.x,
            y: this.mainCamera.rotation.y,
            z: this.mainCamera.rotation.z
        });
        return {
            position: e,
            rotation: i
        }
    }
    changeCameraFov(e, i) {
        this.mainCamera.fov = e,
        i != null && (this.mainCamera.fovMode = i == 0 ? Camera$1.FOVMODE_HORIZONTAL_FIXED : Camera$1.FOVMODE_VERTICAL_FIXED)
    }
    controlCameraRotation(e, i, o=.5, s=.5) {
        const c = {
            pitch: s * i * 180,
            yaw: o * e * 180,
            roll: 0
        };
        this.addRot(c)
    }
    addRot(e) {
        const i = this.mainCamera
          , o = ue4Rotation2Xverse_mesh(e);
        o != null && i.rotation.addInPlace(o)
    }
    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, i, o, s, c) {
        this._moveCam(this.mainCamera, this.mainCamera.position, e, this.mainCamera.rotation, i, o, s, c)
    }
}
function uuid$2() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, a=>{
        const e = Math.random() * 16 | 0;
        return (a === "x" ? e : e & 3 | 8).toString(16)
    }
    )
}
function hashCode(a) {
    let e = 0, i, o;
    if (a == null || a.length === 0)
        return e;
    for (i = 0; i < a.length; i++)
        o = a.charCodeAt(i),
        e = (e << 5) - e + o,
        e |= 0;
    return e
}
const log$w = new Logger$1("XStaticMeshComponent")
  , _XStaticMeshComponent = class {
    constructor(a) {
        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 i = !0;
                const o = Array.from(this._currentMeshUsedLod.keys());
                if (o.length > 0) {
                    for (let s = 0; s < o.length; ++s)
                        this._currentMeshUsedLod.get(o[s]) != this._forceLod && (i = !1);
                    i && (this._allowRegionForceLod = !1)
                }
            }
        }
        ,
        this.setMeshInfo = (e,i="")=>{
            this._abosoluteUrl != e && (this._abosoluteUrl.length > 0 && this.deleteLastRegionMesh(),
            this._partMeshSkinInfo = i,
            this._abosoluteUrl = e,
            this._rootDir = this._abosoluteUrl.slice(0, -4) + "/",
            this.parseJson(this._rootDir + "meshInfo.json").then(()=>{
                this.startMeshUpdate()
            }
            ))
        }
        ,
        this._meshUpdateFrame = ()=>{
            {
                let e = this._meshInfoKeys[this._currentUpdateRegionCount % this._meshInfoKeys.length];
                const i = !0;
                let o = 3;
                if (this._scenemanager != null && this._scenemanager.cameraComponent != null) {
                    const s = this._getMainPlayerPosition();
                    if (s != null) {
                        if (this._cameraInRegionId >= 0) {
                            const d = this.getRegionIdWhichIncludeCamera(s);
                            (this._cameraInRegionId != d || this.regionIdInCamera.length == 0) && (this._cameraInRegionId = d,
                            this.regionIdInCamera = this._getNeighborId(this._cameraInRegionId.toString()),
                            this.regionIdInCameraConst = this.regionIdInCamera.slice());
                            let _ = this.regionIdInCamera.pop();
                            for (; _ != null; )
                                if (this._notUsedRegionLists.indexOf(_) >= 0)
                                    _ = this.regionIdInCamera.pop();
                                else
                                    break;
                            _ != null && (e = _.toString())
                        } else
                            this._cameraInRegionId = this.getRegionIdWhichIncludeCamera(s);
                        if (this._currentMeshUsedLod.size == 0 || this._notUsedRegionLists.indexOf(parseInt(e)) >= 0) {
                            e = this._cameraInRegionId.toString();
                            const d = this._getNeighborId(e);
                            for (; d.length == 0 && (e = this.getNearestRegionIdWithCamera(s).toString()),
                            this._notUsedRegionLists.indexOf(parseInt(e)) >= 0; )
                                e = d.pop().toString()
                        }
                        const c = this._meshInfoJson[this._cameraInRegionId.toString()].lod;
                        o = 3,
                        this._cameraInRegionId.toString() == e ? o = this._regionLodRule[0] : c[0].indexOf(parseInt(e)) >= 0 ? o = this._regionLodRule[1] : c[1].indexOf(parseInt(e)) >= 0 ? o = this._regionLodRule[2] : c[2].indexOf(parseInt(e)) >= 0 ? o = this._regionLodRule[3] : o = this._regionLodRule[4]
                    }
                }
                this.setOneRegionLod(e, o, i),
                this.updateRegionNotInLocalNeighbor(),
                this.cleanRootNodes()
            }
        }
        ,
        this.updateRegionNotInLocalNeighbor = ()=>{
            Array.from(this._currentMeshUsedLod.keys()).forEach(i=>{
                this.regionIdInCameraConst.indexOf(parseInt(i)) < 0 && this.setOneRegionLod(i, -1)
            }
            )
        }
        ,
        this.cleanRootNodes = ()=>{
            if (this.scene.getFrameId() % 3 == 0) {
                const e = [];
                this.scene.rootNodes.forEach(i=>{
                    (i.getClassName() == "TransformNode" && i.getChildren().length == 0 || i.getClassName() == "Mesh" && i.name == "__root__" && i.getChildren().length == 0) && e.push(i)
                }
                ),
                e.forEach(i=>{
                    i.dispose()
                }
                )
            }
        }
        ,
        this.setOneRegionLod = (e,i,o=!0)=>{
            this._currentUpdateRegionCount++;
            const s = this._calHashCode(this._rootDir)
              , c = "region_" + s + "_" + e;
            if (i < 0) {
                this._currentMeshUsedLod.has(e) && (this._currentMeshUsedLod.delete(e),
                this._currentPartGroup.delete(c),
                this.deleteMeshesByCustomProperty("group", "region_" + s + "_" + e));
                return
            }
            const d = this._rootDir + e + "_lod" + i + "_xverse.glb"
              , _ = this._currentMeshUsedLod.get(e);
            this._currentPartGroup.add(c),
            _ != null ? _ != i && (this._currentMeshUsedLod.set(e, i),
            this._scenemanager.addNewLowPolyMesh({
                url: d,
                group: "region_" + s + "_" + e,
                pick: !0,
                lod: i,
                skinInfo: this._partMeshSkinInfo
            }, [{
                group: "region_" + s + "_" + e,
                mode: 0
            }])) : (this._currentMeshUsedLod.set(e, i),
            this._scenemanager.addNewLowPolyMesh({
                url: d,
                group: "region_" + s + "_" + e,
                pick: !0,
                lod: i,
                skinInfo: this._partMeshSkinInfo
            }))
        }
        ,
        this.checkPointInView = ({x: e, y: i, z: o})=>{
            const s = ue4Position2Xverse({
                x: e,
                y: i,
                z: o
            });
            if (!s)
                return !1;
            for (let c = 0; c < 6; c++)
                if (this.scene.frustumPlanes[c].dotCoordinate(s) < 0)
                    return !1;
            return !0
        }
        ,
        this.addNewLowPolyMesh = (e,i,o)=>{
            if (!e.url.endsWith("glb") && !e.url.startsWith("blob:"))
                return e.url.endsWith("zip") ? (this.setMeshInfo(e.url, e.skinInfo),
                Promise.resolve(!0)) : (log$w.error("[Engine] input model path is error! ", e.url),
                Promise.reject(new XLowpolyModelError("[Engine] input model path is error! " + e.url)));
            {
                const s = e.url;
                return new Promise((c,d)=>this._scenemanager.urlTransformer(e.url).then(_=>{
                    e.url = _;
                    const b = new XStaticMeshFromOneGltf(this.scene,e)
                      , k = Date.now();
                    return new Promise((j,$)=>{
                        b.loadMesh(o, !0).then(_e=>{
                            const et = Date.now();
                            if (this._scenemanager.engineRunTimeStats.timeArray_loadStaticMesh.add(et - k),
                            _e == !0) {
                                const tt = this.getLowModelType(e);
                                let rt = 0;
                                if (this._lowModel_group.has(tt) && (rt = this._lowModel_group.get(tt).length),
                                o != null && this._scenemanager.currentShader != null && this._scenemanager.currentShader.name != o.name && b.setMaterial(this._scenemanager.currentShader),
                                this._allowRegionUpdate == !1 && tt.startsWith("region_"))
                                    b.dispose();
                                else if (this._staticmeshes.push(b),
                                this.lowmodelGroupMapAddValue(tt, b),
                                i != null && i.length > 0) {
                                    const it = [];
                                    for (let nt = 0; nt < i.length; ++nt)
                                        it.push(i[nt].group),
                                        this.updateLowModelGroup(i[nt], tt, rt)
                                }
                                this._scenemanager.engineRunTimeStats.timeArray_updateStaticMesh.add(Date.now() - et),
                                j(!0)
                            } else
                                $(new XLowpolyModelError("[Engine] after lowmodel error!"))
                        }
                        ).catch(_e=>{
                            log$w.error("[Engine] load Mesh [" + s + "] error! " + _e),
                            $(new XLowpolyModelError(`[Engine] load Mesh [${s}] error! ${_e}`))
                        }
                        )
                    }
                    )
                }
                ).then(_=>{
                    _ == !0 ? (log$w.info(`[Engine] load Mesh [${s}] successfully.`),
                    c(!0)) : d(!1)
                }
                ).catch(_=>{
                    log$w.error("[Engine] addNewLowPolyMesh [" + s + "] error! " + _),
                    d(new XLowpolyModelError(`[Engine] addNewLowPolyMesh [${s}] error! ${_}`))
                }
                ))
            }
        }
        ,
        this.toggleLowModelVisibility = e=>{
            const {vis: i, groupName: o="", skinInfo: s=""} = e;
            this._meshVis = i,
            this._meshVisTypeName = {
                groupName: o,
                skinInfo: s
            },
            this._doMeshVisChangeNumber = 0,
            o == _XStaticMeshComponent.ALL_MESHES || this._currentPartGroup.has(o) == !0 || this._partMeshSkinInfo == s ? i == !1 ? (this._visCheckDurationFrameNumber = 100,
            this.stopMeshUpdate()) : (this._visCheckDurationFrameNumber = 1,
            this.startMeshUpdate()) : this._visCheckDurationFrameNumber = 1
        }
        ,
        this.reg_staticmesh_visibility = ()=>{
            if (this._doMeshVisChangeNumber >= 0)
                if (this._doMeshVisChangeNumber < this._visCheckDurationFrameNumber)
                    if (this._doMeshVisChangeNumber = this._doMeshVisChangeNumber + 1,
                    this._meshVisTypeName.groupName == _XStaticMeshComponent.ALL_MESHES)
                        this._lowModel_group.forEach((e,i)=>{
                            for (let o = 0, s = e.length; o < s; ++o)
                                e[o].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
        }
        ,
        this._getMeshesByCustomProperty = (e,i)=>{
            let o = [];
            return this._staticmeshes.forEach(s=>{
                s[e] != null && s[e] == i && (o = o.concat(s.meshes))
            }
            ),
            o
        }
        ,
        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 = a,
        this.scene = a.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(a) {
        return a.length != 5 ? !1 : (a.forEach(e=>{}
        ),
        this._regionLodRule = a,
        !0)
    }
    get lowModel_group() {
        return this._lowModel_group
    }
    _regionPartLoop() {
        this.scene.registerBeforeRender(this.reg_staticmesh_partupdate),
        this.scene.registerAfterRender(this.reg_staticmesh_visibility)
    }
    _globalSearchCameraInWhichRegion(a, e) {
        let i = -1;
        for (let o = 0; o < e.length; ++o) {
            const s = this._meshInfoJson[e[o].toString()].boundingbox
              , c = s[0]
              , d = s[1];
            if (a.x >= c[0] && a.x <= d[0] && a.y >= c[1] && a.y <= d[1] && a.z >= c[2] && a.z <= d[2] || a.x >= d[0] && a.x <= c[0] && a.y >= d[1] && a.y <= c[1] && a.z >= d[2] && a.z <= c[2]) {
                i = parseInt(e[o].toString());
                break
            }
        }
        return i
    }
    getRegionIdByPosition(a) {
        return this.getRegionIdWhichIncludeCamera(a)
    }
    getRegionIdWhichIncludeCamera(a) {
        let e = -1;
        if (this._allowRegionUpdate == !1)
            return e;
        if (this._cameraInRegionId == -1 ? e = this._globalSearchCameraInWhichRegion(a, this._meshInfoKeys) : (e = this._globalSearchCameraInWhichRegion(a, this.regionIdInCameraConst),
        e == -1 && (e = this._globalSearchCameraInWhichRegion(a, this._meshInfoKeys))),
        e == -1) {
            let i = 1e7;
            for (let o = 0; o < this._meshInfoKeys.length; ++o) {
                const s = this._meshInfoJson[this._meshInfoKeys[o]].center
                  , c = Math.abs(a.x - s[0]) + Math.abs(a.y - s[1]);
                i > c && (i = c,
                e = parseInt(this._meshInfoKeys[o]))
            }
        }
        return e
    }
    getNearestRegionIdWithCamera(a) {
        let e = 1
          , i = 1e7;
        for (let o = 0; o < this._meshInfoKeys.length; ++o) {
            if (this._notUsedRegionLists.indexOf(parseInt(this._meshInfoKeys[o])) >= 0)
                continue;
            const s = this._meshInfoJson[this._meshInfoKeys[o]].center
              , c = Math.abs(a.x - s[0]) + Math.abs(a.y - s[1]);
            i > c && (i = c,
            e = parseInt(this._meshInfoKeys[o]))
        }
        return e
    }
    _getNeighborId(a) {
        const e = this._meshInfoJson[a].lod;
        let i = [];
        const o = Object.keys(e);
        for (let s = o.length - 1; s >= 0; --s)
            i = i.concat(e[o[s]]);
        return i.push(parseInt(a)),
        i
    }
    _getMainPlayerPosition() {
        const a = this._scenemanager.cameraComponent.getCameraPose().position
          , e = this._scenemanager.avatarComponent.getMainAvatar();
        if (e != null && e != null) {
            const i = e.position;
            if (i != null)
                return i
        }
        return a
    }
    _calHashCode(a) {
        return hashCode(a) + "_" + this._partMeshSkinInfo
    }
    forceAllRegionLod(a=3) {
        a < 0 && (a = 0),
        a > 3 && (a = 3),
        this.stopMeshUpdate(),
        this._allowRegionForceLod = !0,
        this._forceLod = a
    }
    deleteLastRegionMesh() {
        if (this._rootDir != "") {
            const a = 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_" + a, !0)
        }
    }
    startMeshUpdate() {
        this._allowRegionUpdate == !1 && this._meshInfoJson != null && this._abosoluteUrl != "" && this._meshInfoKeys.length > 0 && (this._allowRegionUpdate = !0)
    }
    stopMeshUpdate() {
        this._allowRegionUpdate = !1
    }
    parseJson(a) {
        return new Promise((e,i)=>this._scenemanager.urlTransformer(a).then(o=>{
            const s = new XMLHttpRequest;
            s.open("get", o),
            s.send(null),
            s.onload = ()=>{
                if (s.status == 200) {
                    const c = JSON.parse(s.responseText);
                    this._orijson = c,
                    this._meshInfoJson = this._orijson.usedRegion,
                    this._notUsedRegionLists = this._orijson.notUsedRegion,
                    this._meshInfoKeys = Object.keys(this._meshInfoJson),
                    log$w.info("[Engine] parse zip mesh info successful"),
                    e()
                }
            }
            ,
            s.onerror = ()=>{
                log$w.error(`[Engine] load zip mesh info json error, (provided by blob): ${o}`),
                i(new XLowpolyJsonError(`[Engine] load zip mesh info json error, (provided by blob): ${o}`))
            }
        }
        ).catch(o=>{
            log$w.error(`[Engine] load zip mesh info json error: ${o}, link:${a}`),
            i(new XLowpolyJsonError(`[Engine] load zip mesh info json error: ${o}, link: ${a}`))
        }
        ))
    }
    initCgLowModel() {
        const a = MeshBuilder.CreatePlane("CgPlane", {
            size: 400
        });
        a.position = new Vector3(0,1010,0),
        a.rotation = new Vector3(3 * Math.PI / 2,0,0),
        this._CgPlane = new XStaticMesh({
            id: "CgPlane",
            mesh: a,
            xtype: EMeshType.Cgplane
        }),
        this._CgPlane.hide()
    }
    getLowModelType(a) {
        let e = "";
        return a.group != null ? e = a.group : e = "default",
        e
    }
    lowmodelGroupMapAddValue(a, e) {
        const i = this._lowModel_group.get(a);
        i != null ? (i.push(e),
        this._lowModel_group.set(a, i)) : this._lowModel_group.set(a, [e])
    }
    updateLowModelGroup(a, e, i) {
        let o = i;
        a.group == e || (o = -1),
        a.mode == 0 ? this.deleteLowModelGroup(a.group, o) : a.mode == 1 ? this.toggleVisibleLowModelGroup(!1, a.group, o) : a.mode == 2 && this.toggleVisibleLowModelGroup(!0, a.group, o)
    }
    toggleVisibleLowModelGroup(a, e, i=-1) {
        if (this._lowModel_group.has(e)) {
            const o = this._lowModel_group.get(e);
            let s = o.length;
            i >= 0 && s >= i && (s = i);
            for (let c = 0; c < s; ++c)
                o[c].toggleVisibility(a)
        }
    }
    deleteLowModelGroup(a, e=-1) {
        if (this._lowModel_group.has(a)) {
            const s = this._lowModel_group.get(a);
            let c = s.length;
            e >= 0 && c >= e && (c = e);
            for (let d = 0; d < c; ++d)
                s[d].dispose();
            e >= 0 ? this._lowModel_group.set(a, this._lowModel_group.get(a).slice(c)) : this._lowModel_group.delete(a)
        }
        const i = this._lowModel_group.get(a)
          , o = [];
        i != null && i.length > 0 ? this._staticmeshes.forEach(s=>{
            if (s.group != a)
                o.push(s);
            else
                for (let c = 0; c < i.length; ++c)
                    s.groupUuid == i[c].groupUuid && o.push(s)
        }
        ) : this._staticmeshes.forEach(s=>{
            s.group != a && o.push(s)
        }
        ),
        this._staticmeshes = o
    }
    deleteMeshesByGroup(a) {
        this.deleteLowModelGroup(a)
    }
    deleteMeshesById(a) {
        this.deleteMeshesByCustomProperty("id", a)
    }
    deleteMeshesByLoD(a) {
        this.deleteMeshesByCustomProperty("lod", a)
    }
    deleteMeshesBySkinInfo(a) {
        this.deleteMeshesByCustomProperty("skinInfo", a)
    }
    removeMeshesFromSceneByGroup(a) {
        this.removeMeshesFromSceneByCustomProperty("group", a)
    }
    removeMeshesFromSceneById(a) {
        this.removeMeshesFromSceneByCustomProperty("id", a)
    }
    addMeshesToSceneByGroup(a) {
        this.addMeshesToSceneByCustomProperty("group", a)
    }
    addMeshesToSceneById(a) {
        this.addMeshesToSceneByCustomProperty("id", a)
    }
    removeMeshesFromSceneByCustomProperty(a, e, i=!1) {
        this._staticmeshes.forEach(o=>{
            o.isinscene && o[a] != null && (i ? o[a].indexOf(e) < 0 || o.removeFromScene() : o[a] != e || o.removeFromScene())
        }
        )
    }
    addMeshesToSceneByCustomProperty(a, e, i=!1) {
        this._staticmeshes.forEach(o=>{
            o.isinscene == !1 && o[a] != null && (i ? o[a].indexOf(e) < 0 || o.addToScene() : o[a] != e || o.addToScene())
        }
        )
    }
    deleteMeshesByCustomProperty(a, e, i=!1) {
        const o = [];
        this._staticmeshes.forEach(c=>{
            c[a] != null && (i ? c[a].indexOf(e) < 0 ? o.push(c) : c.dispose() : c[a] != e ? o.push(c) : c.dispose())
        }
        ),
        this._staticmeshes = o;
        const s = Array.from(this._lowModel_group.keys());
        for (let c = 0; c < s.length; ++c) {
            const d = s[c]
              , _ = this._lowModel_group.get(d);
            if (_ != null) {
                const b = [];
                for (let k = 0; k < _.length; ++k)
                    _[k][a] != null && (i ? _[k][a].indexOf(e) < 0 && b.push(_[k]) : _[k][a] != e && b.push(_[k]));
                b.length > 0 ? this._lowModel_group.set(d, b) : this._lowModel_group.delete(d)
            }
        }
    }
    getMeshes() {
        let a = [];
        for (let e = 0; e < this._staticmeshes.length; ++e)
            a = a.concat(this._staticmeshes[e].meshes);
        return a
    }
    getCgMesh() {
        return this._CgPlane
    }
    getMeshesByGroup(a="default") {
        const e = this._lowModel_group.get(a);
        if (e != null) {
            let i = [];
            for (let o = 0; o < e.length; ++o)
                i = i.concat(e[o].meshes);
            return i
        } else
            return null
    }
    getMeshesByGroup2(a="default") {
        return this._getMeshesByCustomProperty("group", a)
    }
}
;
let XStaticMeshComponent = _XStaticMeshComponent;
XStaticMeshComponent.ALL_MESHES = "ALL_MESHES";
class XStaticMeshFromOneGltf {
    constructor(e, i) {
        this.loadMesh = (o,s)=>{
            const c = this._meshes.length
              , d = s ? 1 : 0
              , _ = this._url;
            return SceneLoader.LoadAssetContainerAsync("", _, this._scene, ()=>{
                this._scene.blockMaterialDirtyMechanism = !0
            }
            , ".glb").then(b=>{
                for (let k = b.materials.length - 1; k >= 0; --k)
                    b.materials[k].dispose();
                this._scene.blockMaterialDirtyMechanism = !0;
                for (let k = 0; k < b.meshes.length; ++k) {
                    const j = b.meshes[k];
                    if ("instances"in j) {
                        "visibility"in j && (j.visibility = 0),
                        "isPickable"in j && (j.isPickable = this._pickable),
                        o != null && (j.material = o),
                        "hasVertexAlpha"in j && (j.hasVertexAlpha = !1);
                        const $ = new XStaticMesh({
                            id: this._groupUuid + "-" + Math.random().toString(36).substr(2, 5),
                            mesh: j,
                            lod: this._lod,
                            group: this._group,
                            url: this._url,
                            xtype: EMeshType.XStaticMesh,
                            skinInfo: this._skinInfo
                        });
                        this._meshes.push($)
                    }
                    this._scene.addMesh(j)
                }
                return !0
            }
            ).then(()=>{
                this._isInScene = !0;
                for (let b = c; b < this._meshes.length; ++b)
                    this._meshes[b].mesh.visibility = d;
                return Promise.resolve(!0)
            }
            ).catch(b=>{
                log$w.error("[Engine] input gltf mesh uri error! " + b),
                Promise.reject(new XLowpolyModelError("[Engine] input gltf mesh uri error! " + b))
            }
            )
        }
        ,
        this._meshes = [],
        this._scene = e,
        this._url = i.url,
        i.group != null ? this._group = i.group : this._group = "default",
        i.pick != null ? this._pickable = i.pick : this._pickable = !1,
        i.id != null ? this._id = i.id : this._id = "default",
        i.lod != null ? this._lod = i.lod : this._lod = -1,
        i.skinInfo != null ? this._skinInfo = i.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, i = this._meshes.length; e < i; ++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, i = this._meshes.length; e < i; ++e)
                this._meshes[e].mesh != null && this._scene.addMesh(this._meshes[e].mesh)
        }
    }
    toggleVisibility(e) {
        const i = e ? 1 : 0;
        for (let o = 0, s = this._meshes.length; o < s; ++o)
            "visibility"in this._meshes[o].mesh && (this._meshes[o].mesh.visibility = i)
    }
    togglePickable(e) {
        for (let i = 0, o = this._meshes.length; i < o; ++i)
            "isPickable"in this._meshes[i].mesh && (this._meshes[i].mesh.isPickable = e)
    }
    setMaterial(e) {
        for (let i = 0, o = this._meshes.length; i < o; ++i)
            "material"in this._meshes[i].mesh && (this._meshes[i].mesh.material = e)
    }
    dispose() {
        for (let e = 0, i = this._meshes.length; e < i; ++e)
            this._meshes[e].mesh.dispose(!1, !1)
    }
}
const log$v = new Logger$1("XSceneManager");
var ECurrentShaderMode = (a=>(a[a.default = 0] = "default",
a[a.video = 1] = "video",
a[a.pano = 2] = "pano",
a))(ECurrentShaderMode || {})
  , EImageQuality = (a=>(a[a.low = 0] = "low",
a[a.mid = 1] = "mid",
a[a.high = 2] = "high",
a))(EImageQuality || {});
class XSceneManager {
    constructor(e, i, o, s, c) {
        this._forceKeepVertical = !1,
        this._renderStatusCheckCount = 0,
        this._renderStatusNotChecktCount = 0,
        this._nonlinearCanvasResize = !1,
        this._bChangeEngineSize = !0,
        this._mv = [],
        this.uploadHardwareSystemInfo = ()=>{
            const j = this.statisticComponent.getHardwareRenderInfo()
              , $ = this.statisticComponent.getSystemInfo()
              , _e = {
                driver: $.driver,
                vender: $.vender,
                webgl: $.version,
                os: $.os
            };
            log$v.warn(JSON.stringify(j)),
            log$v.warn(JSON.stringify(_e))
        }
        ,
        this.addNewLowPolyMesh = async(j,$)=>(this._currentShader == null && await this.initSceneManager(),
        this._lowpolyManager.addNewLowPolyMesh(j, $, this._currentShader)),
        this.initSceneManager = async()=>(await this._materialManager.initMaterial(),
        this.applyShader()),
        this.registerAfterRender = ()=>{
            var j;
            if (this._forceKeepVertical) {
                const $ = this.canvas.width
                  , _e = this.canvas.height;
                let et = 0
                  , tt = [[0, 0, 0, 0], [0, 0, 0, 0]];
                if (((j = this._cameraManager.MainCamera) == null ? void 0 : j.fovMode) === Camera$1.FOVMODE_HORIZONTAL_FIXED ? (et = Math.ceil((_e - this._yuvInfo.height * $ / this._yuvInfo.width) / 2),
                tt = [[0, 0, $, et], [0, _e - et, $, et]]) : (et = Math.ceil(($ - this._yuvInfo.width * _e / this._yuvInfo.height) / 2),
                tt = [[0, 0, et, _e], [$ - et, 0, et, _e]]),
                et > 0) {
                    this.gl.enable(this.gl.SCISSOR_TEST);
                    for (let rt = 0; rt < tt.length; ++rt)
                        this.gl.scissor(tt[rt][0], tt[rt][1], tt[rt][2], tt[rt][3]),
                        this.gl.clearColor(0, 0, 0, 1),
                        this.gl.clear(this.gl.COLOR_BUFFER_BIT);
                    this.gl.disable(this.gl.SCISSOR_TEST)
                }
            }
        }
        ,
        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 d = /iphone|ipad/gi.test(window.navigator.userAgent) || i.disableWebGL2;
        o || (o = new Engine(e,!0,{
            preserveDrawingBuffer: !0,
            stencil: !0,
            disableWebGL2Support: d
        },!0)),
        s || (s = new Scene(o)),
        this.scene = s,
        this.engine = o,
        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 = i.urlTransformer || (j=>Promise.resolve(j)),
        i.logger && Logger$1.setLogger(i.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,
        i.forceKeepVertical != null && (this._forceKeepVertical = i.forceKeepVertical),
        i.panoInfo != null && (this.panoInfo = i.panoInfo),
        i.shaderMode != null && (this.shaderMode = i.shaderMode),
        i.yuvInfo != null ? this._yuvInfo = i.yuvInfo : this._yuvInfo = {
            width: i.videoResOriArray[0].width,
            height: i.videoResOriArray[0].height,
            fov: 50
        },
        i.cameraParam != null && (this.cameraParam = i.cameraParam),
        i.nonlinearCanvasResize != null && (this._nonlinearCanvasResize = i.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: i.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();
        let _ = !1
          , b = !1;
        i.disableLight != null && (_ = i.disableLight),
        i.disablePostprocess != null && (b = i.disablePostprocess),
        _ || (this._lightManager = new XLightManager(this)),
        b || 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 * (c || 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.adaptRatio(this._initEngineScaleNumber, 1.8)),
        log$v.info("[Engine] change image quality to low")) : e == 1 ? (this.engine.setHardwareScalingLevel(this.adaptRatio(this._initEngineScaleNumber, 1.5)),
        log$v.info("[Engine] change image quality to mid")) : e == 2 && (this.engine.setHardwareScalingLevel(this.adaptRatio(this._initEngineScaleNumber, 1)),
        log$v.info("[Engine] change image quality to high"))
    }
    adaptRatio(e, i) {
        const o = Math.max(this.canvas.clientWidth, this.canvas.clientHeight);
        for (; o / (e * i) < 1e3; )
            if (i = i - .1,
            i < 1.1) {
                i = 1;
                break
            }
        const s = Math.min(this.canvas.clientWidth, this.canvas.clientHeight);
        for (; s / (e * i) > 1e3; )
            if (i = i + .1,
            i >= 2) {
                i = 2;
                break
            }
        return e * i
    }
    setNonlinearCanvasResize(e) {
        this._nonlinearCanvasResize = e,
        this._bChangeEngineSize = e,
        e || this.engine.resize()
    }
    changeCameraFovWithShaderUpdate(e) {
        this.materialComponent.changeCameraFovWithShaderUpdate(e)
    }
    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((i,o)=>{
            this.urlTransformer(e).then(s=>{
                this._backgroundImg == null ? this._backgroundImg = {
                    layer: new Layer("tex_background_" + Date.now(),s,this.Scene,!0),
                    url: e
                } : this._backgroundImg.url != e && this._backgroundImg.layer != null && this._backgroundImg.layer.texture != null && (this._backgroundImg.layer.texture.updateURL(s),
                this._backgroundImg.layer.name = "tex_background_" + Date.now(),
                this._backgroundImg.url = e),
                i(!0)
            }
            ).catch(s=>{
                log$v.error(`[Engine] set background image Error: ${s}`),
                o(`[Engine] set background image Error: ${s}`)
            }
            )
        }
        )
    }
    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, i) {
        const o = [];
        return this._avatarManager.getAvatarList().forEach(s=>{
            const c = e
              , d = s.position;
            d && c && calcDistance3D(c, d) < i && o.push(s.id)
        }
        ),
        o
    }
    setEngineSize(e) {
        const i = e.width
          , o = e.height
          , s = this.canvas.width;
        this.canvas.height,
        this.engine.setSize(Math.round(s), Math.round(s * (o / i)))
    }
    getCurrentShaderMode() {
        return this._currentShader === this._materialManager.getDefaultShader() ? 0 : this._currentShader === this._materialManager.getPureVideoShader() ? 1 : 2
    }
    addSkyTV(e, i) {
        return this._skytv = new XTelevision(this.scene,e,this,i),
        this._skytv
    }
    addMv(e, i) {
        this._mv.push(new XTelevision(this.scene,e,this,i))
    }
    addMeshInfo(e) {
        this._lowpolyManager.setMeshInfo(e)
    }
    applyShader() {
        return new Promise((e,i)=>{
            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$v.error(`[Engine] Render Error: ${e}`),
            e
        }
    }
    isReadyToRender(e) {
        const {checkMesh: i=!0, checkEffect: o=!1, checkPostProgress: s=!1, checkParticle: c=!1, checkAnimation: d=!1, materialNameWhiteLists: _=[]} = e;
        if (this.scene._isDisposed)
            return log$v.error("[Engine] this.scene._isDisposed== false "),
            !1;
        let b;
        const k = this.scene.getEngine();
        if (o && !k.areAllEffectsReady())
            return log$v.error("[Engine] engine.areAllEffectsReady == false"),
            !1;
        if (d && this.scene._pendingData.length > 0)
            return log$v.error("[Engine] scene._pendingData.length > 0 && animation error"),
            !1;
        if (i) {
            for (b = 0; b < this.scene.meshes.length; b++) {
                const j = this.scene.meshes[b];
                if (!j.isEnabled() || !j.subMeshes || j.subMeshes.length === 0 || j != null && j.material != null && !(j.material.name.startsWith("Pure") || j.material.name.startsWith("Pano")))
                    continue;
                if (!j.isReady(!0))
                    return log$v.error(`[Engine] scene. mesh isReady == false, mesh name:${j.name}, mesh xtype: ${j == null ? void 0 : j.xtype}, mesh xgroup: ${j == null ? void 0 : j.xgroup}, mesh xskinInfo: ${j == null ? void 0 : j.xskinInfo}`),
                    !1;
                const $ = j.hasThinInstances || j.getClassName() === "InstancedMesh" || j.getClassName() === "InstancedLinesMesh" || k.getCaps().instancedArrays && j.instances.length > 0;
                for (const _e of this.scene._isReadyForMeshStage)
                    if (!_e.action(j, $))
                        return log$v.error(`[Engine] scene._isReadyForMeshStage == false, mesh name:${j.name}, mesh xtype: ${j == null ? void 0 : j.xtype}, mesh xgroup: ${j == null ? void 0 : j.xgroup}, mesh xskinInfo: ${j == null ? void 0 : j.xskinInfo}`),
                        !1
            }
            for (b = 0; b < this.scene.geometries.length; b++)
                if (this.scene.geometries[b].delayLoadState === 2)
                    return log$v.error("[Engine] geometry.delayLoadState === 2"),
                    !1
        }
        if (s) {
            if (this.scene.activeCameras && this.scene.activeCameras.length > 0) {
                for (const j of this.scene.activeCameras)
                    if (!j.isReady(!0))
                        return log$v.error("[Engine] camera not ready === false, ", j.name),
                        !1
            } else if (this.scene.activeCamera && !this.scene.activeCamera.isReady(!0))
                return log$v.error("[Engine] activeCamera ready === false, ", this.scene.activeCamera.name),
                !1
        }
        if (c) {
            for (const j of this.scene.particleSystems)
                if (!j.isReady())
                    return log$v.error("[Engine] particleSystem ready === false, ", j.name),
                    !1
        }
        return !0
    }
    changePanoShaderForLowModel(e) {
        return log$v.info(`[Engine] changePanoShaderForLowModel: ${e}`),
        this._materialManager.allowYUVUpdate(),
        new Promise((i,o)=>{
            this._materialManager._isInDynamicRange(e) == !1 && o(!1),
            this._currentPanoId = e,
            this._currentShader = this._materialManager.getDynamicShader(e),
            this.changeShaderForLowModel().then(()=>{
                i(!0)
            }
            )
        }
        )
    }
    changeVideoShaderForLowModel() {
        return log$v.info("[Engine] changeVideoShaderForLowModel"),
        this._currentShader = this._materialManager.getPureVideoShader(),
        this._materialManager.allowYUVUpdate(),
        this.changeShaderForLowModel()
    }
    changeDefaultShaderForLowModel() {
        return log$v.info("[Engine] changeDefaultShaderForLowModel"),
        this._currentShader = this._materialManager.getDefaultShader(),
        this._materialManager.stopYUVUpdate(),
        this.changeShaderForLowModel()
    }
    changeShaderForLowModel() {
        return new Promise((e,i)=>{
            this._lowpolyManager.getMeshes().forEach(o=>{
                o.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 i = this._lowpolyManager.getMeshes()
          , o = [];
        return i.forEach(s=>{
            s.mesh.name.indexOf("SM_Stage") >= 0 && o.push(s.mesh)
        }
        ),
        this.Scene.meshes.forEach(s=>{
            s.name.split("_")[0] === "ground" && o.push(s)
        }
        ),
        o
    }
}
new Logger$1("XVolume");
class WorldStore {
    static get DefaultWorld() {
        return this.Instances.length === 0 ? null : this.Instances[this.Instances.length - 1]
    }
}
WorldStore.Instances = new Array;
class XLevel extends XObject {
    constructor() {
        var e;
        super(),
        this._OwningWorld = null,
        (e = XWorld.GetDefaultWorld()) == null || e.Levels.push(this),
        this.Actors = new Array,
        this.Components = new Array
    }
    get OwningWorld() {
        return this._OwningWorld
    }
    set OWningWorld(e) {
        this._OwningWorld = e
    }
    dispose() {
        var i;
        const e = XWorld.GetDefaultWorld().Levels.indexOf(this);
        (i = XWorld.GetDefaultWorld()) == null || i.Levels.splice(e, 1)
    }
}
class XWorld extends XObject {
    constructor() {
        super(),
        XWorld.Instances.push(this),
        this._persistentLevel = null,
        this.Levels = new Array,
        this.Components = new Array
    }
    static GetDefaultWorld() {
        return WorldStore.DefaultWorld
    }
    static get Instances() {
        return WorldStore.Instances
    }
    get persistentLevel() {
        return this._persistentLevel == null && (this._persistentLevel = new XLevel),
        this._persistentLevel
    }
    set persistentLevel(e) {
        this._persistentLevel = e
    }
    dispose() {
        const e = XWorld.Instances.indexOf(this);
        XWorld.Instances.splice(e, 1),
        this.Levels = [],
        this.Components = [],
        this._persistentLevel = null
    }
}
class XActorComponent extends XObject {
    constructor() {
        super(),
        this._ownerPrivate = null,
        this._worldPrivate = XWorld.GetDefaultWorld(),
        this._tickEnabled = !0
    }
    Tick() {}
    ReceiveTick() {
        this.tickEnabled && this.Tick()
    }
    get tickEnabled() {
        return this._tickEnabled
    }
    set tickEnabled(e) {
        this._tickEnabled = e
    }
    get owner() {
        return this._ownerPrivate
    }
    set owner(e) {
        e && (this._ownerPrivate = e,
        this._outer = e == null ? void 0 : e.outer)
    }
    set outer(e) {
        this._outer = e
    }
    get outer() {
        return this.owner && (this._outer = this.owner.outer),
        this._outer
    }
    RegisterComponentWithWorld(e) {}
}
var __defProp$2 = Object.defineProperty
  , __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor
  , __decorateClass$2 = (a,e,i,o)=>{
    for (var s = o > 1 ? void 0 : o ? __getOwnPropDesc$2(e, i) : e, c = a.length - 1, d; c >= 0; c--)
        (d = a[c]) && (s = (o ? d(e, i, s) : d(s)) || s);
    return o && s && __defProp$2(e, i, s),
    s
}
;
AssetContainer.prototype.clone = function(a, e=!0, i, o=!0) {
    const s = new AssetContainer(this.scene);
    a || (a = "");
    const c = $=>a + "_CloneOf_" + $
      , d = {}
      , _ = {}
      , b = []
      , k = [];
    i || (i = {
        doNotInstantiate: !0
    });
    const j = ($,_e)=>{
        if (d[$.uniqueId] = _e.uniqueId,
        _[_e.uniqueId] = _e,
        c && (_e.name = c($.name)),
        _e instanceof Mesh) {
            const et = _e;
            if (s.meshes.push(_e),
            _e.geometry && s.geometries.push(_e.geometry),
            et.morphTargetManager) {
                const tt = $.morphTargetManager;
                et.morphTargetManager = tt.clone(),
                s.morphTargetManagers.push(et.morphTargetManager);
                for (let rt = 0; rt < tt.numTargets; rt++) {
                    const it = tt.getTarget(rt)
                      , nt = et.morphTargetManager.getTarget(rt);
                    d[it.uniqueId] = nt.uniqueId,
                    _[nt.uniqueId] = nt
                }
            }
        } else
            _e instanceof TransformNode && s.transformNodes.push(_e)
    }
    ;
    return this.transformNodes.forEach($=>{
        if (!$.parent) {
            const _e = $.instantiateHierarchy(null, i, (et,tt)=>{
                j(et, tt)
            }
            );
            _e && s.rootNodes.push(_e)
        }
    }
    ),
    this.meshes.forEach($=>{
        if (!$.parent) {
            const _e = $.instantiateHierarchy(null, i, (et,tt)=>{
                if (j(et, tt),
                tt.material) {
                    const rt = tt;
                    if (rt.material)
                        if (e) {
                            const it = et.material;
                            if (k.indexOf(it) === -1) {
                                let nt = it.clone(c ? c(it.name) : "Clone of " + it.name);
                                if (s.materials.push(nt),
                                k.push(it),
                                d[it.uniqueId] = nt.uniqueId,
                                _[nt.uniqueId] = nt,
                                it.getClassName() === "MultiMaterial") {
                                    const ot = it;
                                    for (const at of ot.subMaterials)
                                        !at || (nt = at.clone(c ? c(at.name) : "Clone of " + at.name),
                                        k.push(at),
                                        d[at.uniqueId] = nt.uniqueId,
                                        _[nt.uniqueId] = nt);
                                    ot.subMaterials = ot.subMaterials.map(at=>at && _[d[at.uniqueId]]),
                                    s.multiMaterials.push(ot)
                                }
                            }
                            rt.getClassName() !== "InstancedMesh" && (rt.material = _[d[it.uniqueId]])
                        } else
                            rt.material.getClassName() === "MultiMaterial" ? (this.scene.multiMaterials.indexOf(rt.material) === -1 && this.scene.addMultiMaterial(rt.material),
                            s.multiMaterials.indexOf(rt.material) === -1 && s.multiMaterials.push(rt.material)) : (this.scene.materials.indexOf(rt.material) === -1 && this.scene.addMaterial(rt.material),
                            s.materials.indexOf(rt.material) === -1 && s.materials.push(rt.material))
                }
            }
            );
            _e && s.rootNodes.push(_e)
        }
    }
    ),
    this.skeletons.forEach($=>{
        const _e = $.clone(c ? c($.name) : "Clone of " + $.name);
        $.overrideMesh && (_e.overrideMesh = _[d[$.overrideMesh.uniqueId]]);
        for (const et of this.meshes)
            if (et.skeleton === $ && !et.isAnInstance) {
                const tt = _[d[et.uniqueId]];
                if (tt.isAnInstance || (tt.skeleton = _e,
                b.indexOf(_e) !== -1))
                    continue;
                b.push(_e);
                for (const rt of _e.bones)
                    rt._linkedTransformNode && (rt._linkedTransformNode = _[d[rt._linkedTransformNode.uniqueId]])
            }
        s.skeletons.push(_e)
    }
    ),
    this.animationGroups.forEach($=>{
        const _e = $.clone($.name, et=>_[d[et.uniqueId]] || et, o);
        s.animationGroups.push(_e)
    }
    ),
    this.textures.forEach($=>{
        const _e = $.clone();
        _e && s.textures.push(_e)
    }
    ),
    this.cameras.forEach($=>{
        s.cameras.push($.clone(c($.name)))
    }
    ),
    this.lights.forEach($=>{
        const _e = $.clone(c($.name));
        _e && s.lights.push(_e)
    }
    ),
    s
}
;
AssetContainer.prototype.GetName = function() {
    return this._name || (this._name = ""),
    this._name
}
;
AssetContainer.prototype.SetName = function(a) {
    this._name = a
}
;
AssetContainer.prototype.GetRootNode = function() {
    return this._rootNode || (this._rootNode = this.meshes[0]),
    this._rootNode
}
;
AssetContainer.prototype.CreateRootNodeByName = function(a) {
    const e = new Mesh("assetContainerRootMesh_" + a,this.scene);
    return this.meshes.forEach(i=>{
        i.parent || e.addChild(i)
    }
    ),
    this.meshes.unshift(e),
    e
}
;
AssetContainer.prototype.GetMeshesWithoutParent = function() {
    const a = new Array;
    return this.meshes.forEach(e=>{
        e.parent || a.push(e)
    }
    ),
    a
}
;
AssetContainer.prototype.GetOwner = function() {
    return this._owner
}
;
AssetContainer.prototype.SetOwner = function(a) {
    this._owner || (this._owner = new XObject),
    this._owner = a
}
;
AssetContainer.prototype.toJSON = function() {
    const a = this.GetOwner()
      , e = a == null ? void 0 : a.outer;
    return e ? e.SaveAsset(this) : ""
}
;
AssetContainer.prototype.getClassName = function() {
    return "AssetContainer"
}
;
new Logger$1("XSceneComponent");
class XSceneComponent extends XActorComponent {
    constructor() {
        super(),
        this._billboardMode = 0,
        this._castShadow = !0,
        this.getBbox = (i={})=>{
            const {isConst: o=!1, changeWithAvatar: s=!1} = i;
            let {localCenter: c={
                x: 0,
                y: 0,
                z: 75
            }, width: d=1.32, height: _=1.5, depth: b=.44} = i;
            if (s) {
                const k = this.scaling;
                c = {
                    x: c.x * k.x,
                    y: c.y * k.y,
                    z: c.z * k.z
                },
                d *= k.x,
                _ *= k.y,
                b *= k.z
            }
            if (this.rootNode) {
                let k = new Vector3(0,0,0)
                  , j = new Vector3(0,0,0);
                if (o) {
                    const _e = ue4Position2Xverse(c);
                    k = k.add(_e.add(new Vector3(-d / 2,-_ / 2,-b / 2))),
                    j = j.add(_e.add(new Vector3(d / 2,_ / 2,b / 2)))
                } else {
                    k = k.add(new Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)),
                    j = j.add(new Vector3(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY)),
                    this.rootNode.getChildMeshes().forEach(tt=>{
                        const rt = tt.getBoundingInfo().boundingBox.minimum
                          , it = tt.getBoundingInfo().boundingBox.maximum;
                        k.x = Math.min(k.x, rt.x),
                        j.x = Math.max(j.x, it.x),
                        k.y = Math.min(k.y, rt.y),
                        j.y = Math.max(j.y, it.y),
                        k.z = Math.min(k.z, rt.z),
                        j.z = Math.max(j.z, it.z)
                    }
                    );
                    const _e = j.x - k.x
                      , et = j.z - k.z;
                    k.x -= this.scaling.x * _e / 2,
                    j.x += this.scaling.x * _e / 2,
                    j.y *= this.scaling.y,
                    k.z -= this.scaling.z * et / 2,
                    j.z += this.scaling.z * et / 2
                }
                const $ = this.rootNode.computeWorldMatrix(!0);
                this.bbox ? this.bbox.reConstruct(k, j, $) : this.bbox = new BoundingBox(k,j,$)
            }
        }
        ;
        const e = EngineStore.LastCreatedScene;
        this._bbox = null,
        this._attachChildren = new Array,
        this._attachParent = null,
        this._asset = new AssetContainer(e),
        this._rootNode = this._asset.GetRootNode()
    }
    getClassName() {
        return "XSceneComponent"
    }
    set asset(e) {
        !e || (this._asset = e,
        this._asset.SetOwner(this),
        this._rootNode = this._asset.GetRootNode())
    }
    get asset() {
        return this._asset
    }
    set castShadow(e) {
        !this._rootNode || (this._rootNode.getChildMeshes().forEach(i=>{}
        ),
        this._castShadow = e)
    }
    get castShadow() {
        return this._castShadow
    }
    set position(e) {
        if (!this.rootNode || !e)
            return;
        const i = ue4Position2Xverse(e);
        i && (this.rootNode.position = i)
    }
    get position() {
        return this.rootNode ? xversePosition2Ue4(this.rootNode.position) : {
            x: 0,
            y: 0,
            z: 0
        }
    }
    set rotation(e) {
        if (!this.rootNode || !e)
            return;
        const i = ue4Rotation2Xverse(e);
        i && (this.rootNode.rotation = i)
    }
    get rotation() {
        return this.rootNode ? xverseRotation2Ue4(this.rootNode.rotation) : {
            pitch: 0,
            yaw: 0,
            roll: 0
        }
    }
    set scaling(e) {
        if (!this.rootNode || !e)
            return;
        const i = ue4Scaling2Xverse(e);
        i && (this.rootNode.scaling = i)
    }
    get scaling() {
        if (!this.rootNode)
            return {
                x: 0,
                y: 0,
                z: 0
            };
        const e = this.rootNode.scaling;
        return {
            x: e.x,
            y: -e.z,
            z: e.y
        }
    }
    setEnabled(e) {
        !this.rootNode || (this.rootNode.setEnabled(e),
        this._attachChildren.forEach(i=>{
            i.setEnabled(e)
        }
        ))
    }
    isEnabled() {
        return this.rootNode ? this.rootNode.isEnabled : null
    }
    get billboardMode() {
        return this._billboardMode
    }
    set bllboardMode(e) {
        this._billboardMode !== e && (!this.rootNode || this._rootNode.getChildMeshes().forEach(i=>{
            i.billboardMode = e
        }
        ))
    }
    set name(e) {
        !this.rootNode || (this.rootNode.name = e)
    }
    get name() {
        return this.rootNode ? this.rootNode.name : ""
    }
    get bbox() {
        return this._bbox
    }
    set bbox(e) {
        this._bbox = e
    }
    get rootNode() {
        return this._rootNode
    }
    postLoad() {
        var e;
        this._asset && (this.asset = this._asset,
        this._rootNode = (e = this._asset) == null ? void 0 : e.GetRootNode())
    }
    dispose() {
        var e, i;
        (e = this._asset) == null || e.dispose(),
        (i = this._bbox) == null || i.dispose(),
        this._attachChildren = [],
        this._attachParent = null
    }
    DetachFromComponent(e) {
        !this.rootNode || (this.rootNode.parent = null,
        e._attachChildren.splice(e._attachChildren.indexOf(this), 1),
        this._attachParent = null)
    }
    AttachToComponent(e, i={
        x: 0,
        y: 0,
        z: 0
    }) {
        if (!this.asset || !this.rootNode)
            return;
        const o = this.rootNode;
        this.asset.scene;
        const s = ue4Position2Xverse(i);
        o.setParent(e.rootNode),
        o.position = s,
        e._attachChildren.push(this),
        this._attachParent = e
    }
}
__decorateClass$2([xProperty("xAsset")], XSceneComponent.prototype, "_asset", 2);
RegisterXObjectClass("XSceneComponent", XSceneComponent);
var __defProp$1 = Object.defineProperty
  , __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor
  , __decorateClass$1 = (a,e,i,o)=>{
    for (var s = o > 1 ? void 0 : o ? __getOwnPropDesc$1(e, i) : e, c = a.length - 1, d; c >= 0; c--)
        (d = a[c]) && (s = (o ? d(e, i, s) : d(s)) || s);
    return o && s && __defProp$1(e, i, s),
    s
}
;
new Logger$1("XActor");
class XActor extends XObject {
    constructor() {
        super();
        const e = EngineStore.LastCreatedScene;
        this._children = new Array,
        this._ownedComponent = new Set,
        this._rootComponent = new XSceneComponent,
        this._rootComponent.owner = this,
        this._tickInterval = 1;
        let i = 0;
        this._tickObserver = e.onAfterRenderObservable.add(()=>{
            i += 1,
            i == this._tickInterval && (this._tick(),
            i = 0)
        }
        )
    }
    set outer(e) {
        this._outer = e,
        this._ownedComponent.forEach(i=>{
            i.outer = e
        }
        )
    }
    get outer() {
        return this._outer
    }
    get rootComponent() {
        return this._rootComponent
    }
    getClassName() {
        return "XActor"
    }
    _tick() {
        this._ownedComponent.forEach(e=>{
            e.ReceiveTick()
        }
        )
    }
    get tickInterval() {
        return this._tickInterval
    }
    set tickInterval(e) {
        this._tickInterval = e
    }
    AttachToActor(e) {
        e._children.push(this),
        this._rootComponent.AttachToComponent(e.rootComponent)
    }
    postLoad() {
        this._ownedComponent.add(this._rootComponent)
    }
    dispose() {
        this._children = [],
        this._ownedComponent.clear(),
        this._rootComponent.dispose(),
        this._tickObserver.unregisterOnNextCall = !0
    }
}
__decorateClass$1([xProperty("rootComponent")], XActor.prototype, "_rootComponent", 2);
RegisterXObjectClass("XActor", XActor);
var __defProp = Object.defineProperty
  , __getOwnPropDesc = Object.getOwnPropertyDescriptor
  , __decorateClass = (a,e,i,o)=>{
    for (var s = o > 1 ? void 0 : o ? __getOwnPropDesc(e, i) : e, c = a.length - 1, d; c >= 0; c--)
        (d = a[c]) && (s = (o ? d(e, i, s) : d(s)) || s);
    return o && s && __defProp(e, i, s),
    s
}
;
class XAccessory extends XActor {
    constructor() {
        super()
    }
    getClassName() {
        return "XAccessory"
    }
    set attachType(e) {
        this._attachType = e
    }
    get attachType() {
        return this._attachType
    }
    set attachBoneId(e) {
        this._attachBoneId = e
    }
    get attachBoneId() {
        return this._attachBoneId
    }
    set attachPointOffset(e) {
        this._attachPointOffset = e
    }
    get attachPointOffset() {
        return this._attachPointOffset
    }
    set attachPointRotation(e) {
        this._attachPointRotation = e
    }
    get attachPointScale() {
        return this._attachPointScale
    }
    set pointId(e) {
        this._pointId = e
    }
    get pointId() {
        return this._pointId
    }
    set attachPointOffsetVector3(e) {
        this._attachPointOffset = xversePosition2Ue4(e)
    }
    set attachPointScaleVector3(e) {
        this._attachPointScale = {
            x: e.x,
            y: -e.z,
            z: e.y
        }
    }
    set attachPointRotationVector3(e) {
        this._attachPointRotation = xverseRotation2Ue4_mesh(e)
    }
    setLocalRTS(e) {
        if (e) {
            const i = ue4Scaling2Xverse(this._attachPointScale);
            i && (e.scaling = i);
            const o = ue4Position2Xverse(this._attachPointOffset);
            o && (e.position = o);
            const s = ue4Rotation2Xverse_mesh(this._attachPointRotation);
            s && (e.rotation = s)
        }
    }
    setParentTo(e) {
        this.rootComponent && this.rootComponent.rootNode && (this.rootComponent.rootNode.parent = e,
        this.setLocalRTS(this.rootComponent.rootNode))
    }
    detachFrom(e=!0) {
        e ? this.dispose() : this.rootComponent && this.rootComponent.rootNode && (this.rootComponent.rootNode.parent = null,
        this.rootComponent.rootNode.detachFromBone(!1))
    }
    attachTo(e) {
        switch (this._attachType) {
        case 0:
            this.rootComponent && this.rootComponent.rootNode && e.component.body && (this.rootComponent.rootNode.parent = e.component.body.root,
            this.setLocalRTS(this.rootComponent.rootNode));
            break;
        case 1:
            {
                const i = e.skeleton.bones.find(o=>o.name === this._attachBoneId);
                i && this.rootComponent && this.rootComponent.rootNode && e.component.body && (this.rootComponent.rootNode.attachToBone(i, e.component.body.root),
                this.setLocalRTS(this.rootComponent.rootNode));
                break
            }
        }
    }
    async play() {
        this.rootComponent.asset && this.rootComponent.asset.animationGroups && this.rootComponent.asset.animationGroups.length > 0 && (this.rootComponent.asset.animationGroups[0].play(),
        this.rootComponent.asset.animationGroups[0].onAnimationGroupEndObservable.addOnce(()=>Promise.resolve(null)))
    }
    stop() {
        this.rootComponent.asset && this.rootComponent.asset.animationGroups && this.rootComponent.asset.animationGroups.length > 0 && this.rootComponent.asset.animationGroups[0].stop()
    }
}
__decorateClass([xProperty("_pointId")], XAccessory.prototype, "_pointId", 2);
__decorateClass([xProperty("_attachBoneId")], XAccessory.prototype, "_attachBoneId", 2);
__decorateClass([xProperty("_attachType")], XAccessory.prototype, "_attachType", 2);
__decorateClass([xProperty("_attachPointOffset")], XAccessory.prototype, "_attachPointOffset", 2);
__decorateClass([xProperty("_attachPointRotation")], XAccessory.prototype, "_attachPointRotation", 2);
__decorateClass([xProperty("_attachPointScale")], XAccessory.prototype, "_attachPointScale", 2);
RegisterXObjectClass("XAccessory", XAccessory);
const log$u = new Logger$1("ScreenShot");
function CreateScreenshot(a, e, i, o, s="image/png", c=!1) {
    const {height: d, width: _} = _getScreenshotSize(a, e, i);
    if (log$u.info("[Engine]CreateScreenshot!"),
    !(d && _)) {
        log$u.error("[Engine]CreateScreenshot Invalid 'size' parameter !");
        return
    }
    Tools._ScreenshotCanvas || (Tools._ScreenshotCanvas = document.createElement("canvas")),
    Tools._ScreenshotCanvas.width = _,
    Tools._ScreenshotCanvas.height = d;
    const b = Tools._ScreenshotCanvas.getContext("2d")
      , k = a.getRenderWidth() / a.getRenderHeight();
    let j = _
      , $ = j / k;
    $ > d && ($ = d,
    j = $ * k);
    const _e = Math.max(0, _ - j) / 2
      , et = Math.max(0, d - $) / 2;
    e.getScene().onAfterRenderObservable.addOnce(function() {
        const rt = a.getRenderingCanvas();
        b && rt ? b.drawImage(rt, _e, et, j, $) : log$u.error("[Engine]CreateScreenshot Invalid renderContext and renderingCanvas!"),
        c ? (Tools.EncodeScreenshotCanvasData(void 0, s),
        o && o("")) : Tools.EncodeScreenshotCanvasData(o, s)
    })
}
function CreateScreenshotAsync(a, e, i, o="image/png") {
    return new Promise((s,c)=>{
        CreateScreenshot(a, e, i, d=>{
            typeof d != "undefined" ? s(d) : c(new Error("Data is undefined"))
        }
        , o)
    }
    )
}
function CreateScreenshotUsingRenderTarget(a, e, i, o, s="image/png", c=1, d=!1, _, b=!1, k=!1) {
    const {height: j, width: $} = _getScreenshotSize(a, e, i)
      , _e = {
        width: $,
        height: j
    };
    if (!(j && $)) {
        log$u.error("Invalid 'size' parameter !");
        return
    }
    const et = e.getScene();
    let tt = null;
    const rt = et.activeCameras;
    et.activeCameras = null,
    et.activeCamera !== e && (tt = et.activeCamera,
    et.activeCamera = e),
    et.render();
    const it = new RenderTargetTexture("screenShot",_e,et,!1,!1,Constants.TEXTURETYPE_UNSIGNED_INT,!1,Texture.NEAREST_SAMPLINGMODE,void 0,k,void 0,void 0,void 0,c);
    it.renderList = null,
    it.samples = c,
    it.renderSprites = b,
    et.onAfterRenderTargetsRenderObservable.addOnce(function() {
        it.readPixels(void 0, void 0, void 0, !1).then(ot=>{
            Tools.DumpData($, j, ot, o, s, _, !0),
            it.dispose()
        }
        )
    });
    const nt = ()=>{
        et.incrementRenderId(),
        et.resetCachedMaterial(),
        it.render(!0),
        et.incrementRenderId(),
        et.resetCachedMaterial(),
        tt && (et.activeCamera = tt),
        et.activeCameras = rt,
        e.getProjectionMatrix(!0),
        et.render()
    }
    ;
    if (d) {
        const ot = new FxaaPostProcess("antialiasing",1,et.activeCamera);
        it.addPostProcess(ot),
        ot.getEffect().isReady() ? nt() : ot.getEffect().onCompiled = ()=>{
            nt()
        }
    } else
        nt()
}
function CreateScreenshotUsingRenderTargetAsync(a, e, i, o="image/png", s=1, c=!1, d, _=!1) {
    return new Promise((b,k)=>{
        CreateScreenshotUsingRenderTarget(a, e, i, j=>{
            typeof j != "undefined" ? b(j) : k(new Error("Data is undefined"))
        }
        , o, s, c, d, _)
    }
    )
}
function _getScreenshotSize(a, e, i) {
    let o = 0
      , s = 0;
    if (typeof i == "object") {
        const c = i.precision ? Math.abs(i.precision) : 1;
        i.width && i.height ? (o = i.height * c,
        s = i.width * c) : i.width && !i.height ? (s = i.width * c,
        o = Math.round(s / a.getAspectRatio(e))) : i.height && !i.width ? (o = i.height * c,
        s = Math.round(o * a.getAspectRatio(e))) : (s = Math.round(a.getRenderWidth() * c),
        o = Math.round(s / a.getAspectRatio(e)))
    } else
        isNaN(i) || (o = i,
        s = i);
    return s && (s = Math.floor(s)),
    o && (o = Math.floor(o)),
    {
        height: o | 0,
        width: s | 0
    }
}
const initSideEffects = ()=>{
    Tools.CreateScreenshot = CreateScreenshot,
    Tools.CreateScreenshotAsync = CreateScreenshotAsync,
    Tools.CreateScreenshotUsingRenderTarget = CreateScreenshotUsingRenderTarget,
    Tools.CreateScreenshotUsingRenderTargetAsync = CreateScreenshotUsingRenderTargetAsync
}
;
initSideEffects();
const VERSION$1 = "1.0.92";
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, i, o) {
        super(e, i, o),
        this.onLoadedObserverable.addOnce(()=>{
            this._particleGroups.forEach(s=>{
                const c = s.systems[0];
                c.getClassName() == "ParticleSystem" && (c.startPositionFunction = function(d, _) {
                    const k = 2 * Math.random() * Math.PI
                      , j = Math.random() * 15 * Math.sin(k)
                      , $ = this.minEmitBox.y
                      , _e = Math.random() * 15 * Math.cos(k);
                    Vector3.TransformCoordinatesFromFloatsToRef(j, $, _e, d, _)
                }
                )
            }
            )
        }
        )
    }
}
const log$t = new Logger$1("Billboard");
var BillboardStatus = (a=>(a[a.SHOW = 1] = "SHOW",
a[a.HIDE = 0] = "HIDE",
a[a.DISPOSE = -1] = "DISPOSE",
a))(BillboardStatus || {});
class XBillboard {
    constructor(e, i=!1, o=!1) {
        this._mesh = null,
        this._texture = null,
        this._scalingFactor = 1,
        this.offsets = null,
        this._background = null,
        this.poolobj = null,
        this._initMeshScale = new Vector3(1,1,1),
        this._status = -1,
        this._stageChanged = !1,
        this.DEFAULT_CONFIGS = {},
        this._billboardManager = e,
        this._pickable = i,
        this._usePool = o
    }
    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="", i=.001, o=.001, s=!1) {
        const c = this._billboardManager.sceneManager.Scene;
        if (this._usePool) {
            const d = this._billboardManager.billboardPool.getFree(c, i, o, s);
            this._mesh = d.data,
            this._mesh.isPickable = this._pickable,
            this._mesh.xid = e,
            this._mesh.xtype = EMeshType.XBillboard,
            this._texture = this._mesh.material.diffuseTexture,
            this.poolobj = d
        } else
            this._mesh = this._billboardManager.createBillboardAsset(c, s);
        this._mesh.isPickable = this._pickable,
        this._initMeshScale.x = i * 1e3,
        this._initMeshScale.y = o * 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(i=>{
            if (this._texture == null) {
                log$t.error("[Engine]Billboard texture not found");
                return
            }
            const o = this._mesh
              , s = this._texture
              , c = this._scalingFactor
              , d = this._initMeshScale.x
              , _ = this._initMeshScale.y
              , b = this._texture.getContext()
              , k = this._texture.getSize();
            b.clearRect(0, 0, k.width, k.height);
            const j = new Image;
            j.crossOrigin = "anonymous",
            j.src = e,
            j.onload = ()=>{
                const $ = j.width * c
                  , _e = j.height * c;
                o.scaling.x = $ * d,
                o.scaling.y = _e * _,
                s.scaleTo($, _e),
                b.drawImage(j, 0, 0, $, _e),
                s.hasAlpha = !0,
                s.update(),
                i()
            }
        }
        )
    }
    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 i = ue4Position2Xverse(e);
            this._mesh.position = i
        }
    }
    updateText(e, i, o=!0, s=[], c=30, d="monospace", _="black", b="bold", k) {
        if (this._texture == null) {
            log$t.error("[Engine]Billboard texture not found");
            return
        }
        const j = this._texture
          , $ = this._mesh
          , _e = this._scalingFactor
          , et = this._initMeshScale.x
          , tt = this._initMeshScale.y;
        if (e != "") {
            const rt = this._texture.getContext()
              , it = this._texture.getSize();
            rt.clearRect(0, 0, it.width, it.height);
            const nt = new Image;
            if (o) {
                i != null ? i ? this._background = this._billboardManager.userBackGroundBlob : this._background = this._billboardManager.npcBackGroundBlob : this._background || (this._background = this._billboardManager.userBackGroundBlob);
                let ot = e
                  , at = k && k < s.length - 1 ? k : s.length - 1;
                if (this._background) {
                    if (at > this._background.length) {
                        for (let st = 0; st < at - this._background.length; st++)
                            s.pop();
                        at = s.length - 1,
                        ot = e.slice(0, s[at] - 1) + String.fromCharCode(8230)
                    }
                    nt.crossOrigin = "anonymous",
                    nt.src = this._background[at - 1],
                    nt.onload = function() {
                        const st = nt.width * _e
                          , ut = nt.height * _e;
                        $.scaling.x = st * et,
                        $.scaling.y = ut * tt,
                        j.scaleTo(st, ut),
                        rt.textAlign = "center",
                        rt.textBaseline = "middle",
                        rt.drawImage(nt, 0, 0, st, ut);
                        for (let ct = 0; ct < at; ct++)
                            j.drawText(ot.slice(s[0 + ct], s[1 + ct]), st / 2, ut * (ct + 1) / (at + 1) + (ct - (at - 1) / 2) * _e * 10, b + " " + c * _e + "px " + d, _, "transparent", !0);
                        j.hasAlpha = !0
                    }
                }
            } else {
                const ot = k && k < s.length - 1 ? k : s.length - 1
                  , at = 480 * _e
                  , st = 60 * _e * ot;
                this._mesh.scaling = new Vector3(at * et,st * tt,1),
                j.scaleTo(at, st);
                const ut = j.getContext();
                ut.textAlign = "center",
                ut.textBaseline = "middle";
                for (let ct = 0; ct < ot; ct++)
                    setTimeout(()=>{
                        j.drawText(e.slice(s[0 + ct], s[1 + ct]), at / 2 + 2 * _e, st * (ct + 1) / (ot + 1) + (ct - (ot - 1) / 2) * _e * 10 + 2 * _e, b + " " + c * _e + "px " + d, "#333333", "transparent", !0),
                        j.drawText(e.slice(s[0 + ct], s[1 + ct]), at / 2, st * (ct + 1) / (ot + 1) + (ct - (ot - 1) / 2) * _e * 10, b + " " + c * _e + "px " + d, _, "transparent", !0)
                    }
                    , 0);
                j.hasAlpha = !0
            }
        } else
            this.clearText()
    }
    drawBillboard(e, i, o) {
        var it;
        const {imageList: s} = e
          , {texts: c, font: d="monospace", fontsize: _=40, fontcolor: b="#ffffff", fontstyle: k="", linesize: j=20, linelimit: $} = i
          , {position: _e, offsets: et, scale: tt, compensationZ: rt=0} = o;
        if (this.scalingFactor = tt || 1,
        et && (this.offsets = {
            x: et.x * this._scalingFactor,
            y: et.y * this._scalingFactor,
            z: et.z * this._scalingFactor
        }),
        this.offsets || (this.offsets = {
            x: 0,
            y: 0,
            z: 0
        }),
        this.setPosition(_e),
        s && !c)
            (it = this._billboardManager.sceneManager) == null || it.urlTransformer(s[0]).then(nt=>{
                this.updateImage(nt)
            }
            );
        else if (c && !s) {
            const [nt,ot] = getStringBoundaries(c, j, XBillboardManager.alphaWidthMap);
            this.offsets.z += this._scalingFactor * rt * (ot.length - 1),
            this.updateText(nt, void 0, !1, ot, _, d, b, k, $)
        } else if (c && s) {
            this.background = s;
            const [nt,ot] = getStringBoundaries(c, j, XBillboardManager.alphaWidthMap);
            this.offsets.z += this._scalingFactor * rt * (ot.length - 1),
            this.updateText(nt, void 0, !0, ot, _, d, b, k, $)
        }
        this.setStatus(1)
    }
    clearText() {
        if (this._texture != null) {
            const e = this._texture.getContext()
              , i = this._texture.getSize();
            e.clearRect(0, 0, i.width, i.height),
            this._texture.update()
        }
    }
}
var AvatarGroup = (a=>(a.Npc = "npc",
a.User = "user",
a))(AvatarGroup || {})
  , ChangeComponentsMode = (a=>(a[a.Preview = 0] = "Preview",
a[a.Confirm = 1] = "Confirm",
a[a.Cancel = 2] = "Cancel",
a))(ChangeComponentsMode || {})
  , MotionType = (a=>(a.Walk = "walk",
a.Run = "run",
a.Fly = "fly",
a))(MotionType || {});
class XverseError extends Error {
    constructor(i, o) {
        super(o);
        Tt(this, "code");
        this.code = i
    }
    toJSON() {
        return {
            code: this.code,
            message: this.message
        }
    }
    toString() {
        if (Object(this) !== this)
            throw new TypeError;
        let o = this.name;
        o = o === void 0 ? "Error" : String(o);
        let s = this.message;
        s = s === void 0 ? "" : String(s);
        const c = this.code;
        return s = c === void 0 ? s : c + "," + s,
        o === "" ? s : s === "" ? o : o + ": " + s
    }
}
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 UnReachableError extends XverseError {
    constructor(e) {
        super(2335, e || "\u533A\u57DF\u4E0D\u53EF\u5230\u8FBE")
    }
}
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 = (a=>(a[a.Success = 0] = "Success",
a[a.Param = 1001] = "Param",
a[a.Internal = 1002] = "Internal",
a[a.Timeout = 1003] = "Timeout",
a[a.Authentication = 1004] = "Authentication",
a[a.TokenExpired = 1005] = "TokenExpired",
a[a.Unsupported = 1006] = "Unsupported",
a[a.InitNetworkTimeout = 1007] = "InitNetworkTimeout",
a[a.InitDecoderTimeout = 1008] = "InitDecoderTimeout",
a[a.InitConfigTimeout = 1009] = "InitConfigTimeout",
a[a.InitEngineTimeout = 1010] = "InitEngineTimeout",
a[a.InitEngine = 1011] = "InitEngine",
a[a.ActionBlocked = 1012] = "ActionBlocked",
a[a.PreloadCanceled = 1013] = "PreloadCanceled",
a[a.FrequencyLimit = 1014] = "FrequencyLimit",
a[a.UsersUpperLimit = 2e3] = "UsersUpperLimit",
a[a.RoomsUpperLimit = 2001] = "RoomsUpperLimit",
a[a.ServerParam = 2002] = "ServerParam",
a[a.LackOfToken = 2003] = "LackOfToken",
a[a.LoginFailed = 2004] = "LoginFailed",
a[a.VerifyServiceDown = 2005] = "VerifyServiceDown",
a[a.CreateSessionFailed = 2006] = "CreateSessionFailed",
a[a.RtcConnection = 2008] = "RtcConnection",
a[a.DoActionFailed = 2009] = "DoActionFailed",
a[a.StateSyncFailed = 2010] = "StateSyncFailed",
a[a.BroadcastFailed = 2011] = "BroadcastFailed",
a[a.DataAbnormal = 2012] = "DataAbnormal",
a[a.GetOnVehicle = 2015] = "GetOnVehicle",
a[a.RepeatLogin = 2017] = "RepeatLogin",
a[a.RoomDoseNotExist = 2018] = "RoomDoseNotExist",
a[a.TicketExpire = 2019] = "TicketExpire",
a[a.ServerRateLimit = 2020] = "ServerRateLimit",
a[a.DoActionBlocked = 2333] = "DoActionBlocked",
a[a.UnReachable = 2335] = "UnReachable",
a[a.ActionMaybeDelay = 2334] = "ActionMaybeDelay",
a[a.ActionResponseTimeout = 2999] = "ActionResponseTimeout",
a))(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,
    2335: UnReachableError,
    2334: ActionMaybeDelayError,
    2999: ActionResponseTimeoutError
};
class EventEmitter {
    constructor() {
        Tt(this, "topics", {});
        Tt(this, "on", (e,i,o)=>this.register(!1, e, i, o));
        Tt(this, "once", (e,i,o)=>this.register(!0, e, i, o));
        Tt(this, "register", (e,i,o,s)=>{
            this.topics[i] || (this.topics[i] = {
                once: e,
                listeners: [],
                excuted: !1
            });
            const c = {
                order: s || 0,
                listener: o,
                once: e
            };
            return this.topics[i].listeners.push(c),
            this.topics[i].listeners.sort((d,_)=>d.order - _.order),
            {
                unsub: ()=>{
                    this.off(i, o)
                }
            }
        }
        );
        Tt(this, "off", (e,i)=>{
            const o = this.topics[e];
            if (!o)
                return;
            const s = o.listeners.findIndex(c=>c.listener === i);
            this.topics[e].listeners.splice(s, 1),
            this.topics[e].listeners.length === 0 && delete this.topics[e]
        }
        );
        Tt(this, "removeAllListener", ()=>{
            this.topics = {}
        }
        );
        Tt(this, "emit", (e,i)=>{
            !this.topics[e] || !this.topics[e].listeners || this.topics[e].listeners.length < 1 || this.topics[e].excuted || (this.topics[e].listeners.forEach(o=>{
                try {
                    o.listener(i !== void 0 ? i : {})
                } catch (s) {
                    console.error(s)
                }
            }
            ),
            this.topics[e] && this.topics[e].once && (this.topics[e].excuted = !0))
        }
        )
    }
}
const safeDecodeURIComponent = a=>{
    let e = "";
    try {
        e = decodeURIComponent(a)
    } catch {
        e = a
    }
    return e
}
  , safelyJsonParse = a=>{
    let e = {};
    try {
        e = JSON.parse(a)
    } catch {}
    return e
}
  , getRandomItem = a=>a.length === 0 ? null : a[Math.floor(Math.random() * a.length)]
  , ENV = "production";
function getFormattedDate(a) {
    const e = a.getMonth() + 1
      , i = a.getDate()
      , o = a.getHours()
      , s = a.getMinutes()
      , c = a.getSeconds()
      , d = a.getMilliseconds()
      , _ = (e < 10 ? "0" : "") + e
      , b = (i < 10 ? "0" : "") + i
      , k = (o < 10 ? "0" : "") + o
      , j = (s < 10 ? "0" : "") + s
      , $ = (c < 10 ? "0" : "") + c;
    return a.getFullYear() + "-" + _ + "-" + b + " " + k + ":" + j + ":" + $ + "." + d
}
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 = 5
  , lr = class extends EventEmitter {
    constructor() {
        super();
        Tt(this, "_header", {});
        Tt(this, "_body", {});
        Tt(this, "_queue", []);
        Tt(this, "_disabled", !1);
        Tt(this, "_interval", null);
        Tt(this, "_reportUrl");
        Tt(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)
    }
    static appendExtraMetrics(i) {
        this.VALID_METRICS.push(...i)
    }
    disable() {
        this._disabled = !0,
        this._interval && window.clearInterval(this._interval)
    }
    updateHeader(i) {
        Object.assign(this._header, i)
    }
    updateBody(i) {
        Object.assign(this._body, i)
    }
    updateReportUrl(i) {
        this._reportUrl = i
    }
    report(i, o, s) {
        if (i === "measurement" && (Array.isArray(o) || (o = [o]),
        o.forEach(b=>{
            var k;
            (k = b.metric) != null && k.endsWith("Action") || lr.VALID_METRICS.includes(b.metric) || console.warn("invalid upload metric", b.metric)
        }
        )),
        this._disabled)
            return;
        s || (s = {});
        const {immediate: c, sampleRate: d} = s;
        if (d && d > Math.random())
            return;
        this.updateBody({
            logTime: getFormattedDate(new Date),
            logTimestamp: Date.now()
        });
        const _ = b=>{
            const k = $t(Zt($t({}, this._body), {
                type: i
            }), b);
            this._queue.push(k),
            i === "measurement" && this.emit("report", b)
        }
        ;
        Array.isArray(o) ? o.forEach(b=>_(b)) : _(o),
        (c || this._queue.length >= REPORT_NUM_PER_REQUEST) && this._flushReport()
    }
    _flushReport() {
        if (this._disabled || !this._queue.length || !this.isDocumentLoaded())
            return;
        const i = {
            header: this._header,
            body: this._queue.splice(0, REPORT_NUM_PER_REQUEST)
        };
        this._post(i)
    }
    _post(i) {
        const o = this._reportUrl || REPORT_URL.DEV;
        return new Promise((s,c)=>{
            const d = new XMLHttpRequest;
            d.open("POST", o),
            d.setRequestHeader("Content-Type", "application/json");
            try {
                d.send(JSON.stringify(i))
            } catch (_) {
                console.error(_)
            }
            d.addEventListener("readystatechange", ()=>{
                if (d.readyState == 4)
                    return d.status == 200 ? s(d) : c("Unable to send log")
            }
            )
        }
        )
    }
}
;
let Reporter = lr;
Tt(Reporter, "VALID_METRICS", ["assetsPreload", "joinRoom", "changeSkin", "getOnVehicle", "getOffVehicle", "getOnWatchTower", "getOffWatchTower", "setPerson", "sendGift", "photobooth", "photoboothExit", "reconnect", "observer", "telescope", "telescopeExit", "avatarLoadDuration", "avatarLoadAt", "changeComponents", "playEffect", "startJoinRoomAt", "initRoomDuration", "webglInitCost", "webglInitAt", "configInitAt", "configInitCost", "networkInitAt", "networkInitCost", "wasmInitAt", "wasmInitCost", "wsOpenedCost", "datachannelOpenedAt", "datachannelOpenedCost", "wsOpenedAt", "baiduRtt", "workerRtt", "loadAssets", "playAnimationStart", "playAnimationEnd", "userAvatarStopMoving", "userAvatarStartMoving", "userAvatarStopRotating", "userAvatarStartRotating", "liveEntranceClick", "sdkInit", "networkQualityChange", "pageShow", "pageHide", "http", "renderError", "firstMediaArravalAt", "firstRenderAt", "firstUpdateStreamLength", "firstYUVDecodedAt", "startGame", "wasmDownloadCost", "getUserWithAvatar"]);
const reporter = new Reporter;
var LoggerLevels = (a=>(a[a.Debug = 1] = "Debug",
a[a.Info = 2] = "Info",
a[a.Warn = 3] = "Warn",
a[a.Error = 4] = "Error",
a[a.Off = 5] = "Off",
a))(LoggerLevels || {});
const ur = class {
    constructor(e) {
        Tt(this, "module", "log");
        Tt(this, "level", 1);
        this.module = e
    }
    static setLevel(e) {
        this.level = e
    }
    setLevel(e) {
        this.level = e
    }
    atleast(e) {
        return e >= this.level && e >= ur.level
    }
    print(e, i, ...o) {
        if (this.atleast(i)) {
            const s = e == "debug" ? "info" : e
              , c = this.prefix(e);
            console[s].call(null, c, ...o)
        }
        if (e !== "debug" && e !== "info") {
            const s = o.map(c=>{
                if (c instanceof Object)
                    try {
                        return JSON.stringify(c)
                    } catch {
                        return c
                    }
                else
                    return c
            }
            ).join(",");
            reporter.report("log", {
                message: s,
                level: e,
                module: this.module
            })
        }
    }
    debug(...e) {
        return this.print("debug", 1, ...e)
    }
    info(...e) {
        return this.print("info", 2, ...e)
    }
    infoAndReportLog(e, ...i) {
        const {reportOptions: o} = e;
        delete e.reportOptions,
        reporter.report("log", e, o),
        i.length || (i = [e.message]),
        this.debug(...i)
    }
    infoAndReportMeasurement(e, ...i) {
        var s;
        const {reportOptions: o} = e;
        if (e.startTime) {
            const c = Date.now();
            e.value === void 0 && (e.endTime = c),
            e.value === void 0 && (e.value = c - e.startTime)
        }
        if (e.error ? e.code = ((s = e.error) == null ? void 0 : s.code) || Codes$1.Internal : e.code = Codes$1.Success,
        reporter.report("measurement", e, o),
        i.length || (i = [e]),
        e.level === 4 || e.error) {
            this.error(...i);
            return
        }
        this.warn(...i)
    }
    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 = ur;
Tt(Logger, "level", 4);
function getDistance(a, e) {
    const {x: i, y: o, z: s} = a
      , {x: c, y: d, z: _} = e;
    return Math.sqrt(Math.abs(i - c) ** 2 + Math.abs(o - d) ** 2 + Math.abs(s - _) ** 2)
}
function uuid$1() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, a=>{
        const e = Math.random() * 16 | 0;
        return (a === "x" ? e : e & 3 | 8).toString(16)
    }
    )
}
function getErrorByCode(a) {
    if (a === Codes$1.Success)
        return InternalError;
    const e = CodeErrorMap[a];
    return e || console.warn("unkown code", a),
    e || InternalError
}
const log$s = new Logger("events");
class EventsManager extends EventEmitter {
    constructor() {
        super(...arguments);
        Tt(this, "events", new Map);
        Tt(this, "specialEvents", new Map)
    }
    remove(i, o, s, c) {
        if (this.specialEvents.has(i) && !c && o === Codes$1.Success)
            return;
        this.events.get(i) && (this.emit(i, {
            code: o,
            data: s
        }),
        this.events.delete(i),
        this.specialEvents.delete(i))
    }
    async track(i, o) {
        const s = i.traceId
          , {sampleRate: c=1, noReport: d=!1, special: _} = o || {}
          , b = Actions[i.event] + "Action"
          , k = i.tag;
        this.events.set(s, !0),
        _ && this.specialEvents.set(s, !0);
        const j = Date.now();
        let$ = null;
        return new Promise((_e,et)=>{
            if (d)
                return this.off(s),
                this.events.delete(s),
                _e(void 0);
            this.on(s, ({code: rt, data: it, msg: nt})=>{
                if (rt === Codes$1.Success)
                    _e(it),
                    this.off(s),
                    Math.random() < c && log$s.infoAndReportMeasurement({
                        metric: b,
                        tag: k,
                        extra: i.extra,
                        startTime: j,
                        traceId: s
                    });
                else {
                    if (rt === Codes$1.ActionMaybeDelay)
                        return;
                    if (rt === Codes$1.DoActionBlocked && i.event === Actions.Rotation) {
                        log$s.debug(b + " response code: " + rt);
                        return
                    }
                    const ot = getErrorByCode(rt)
                      , at = new ot(nt);
                    this.off(s),
                    et(at),
                    this.emit("actionResponseError", {
                        error: at,
                        event: i,
                        tag: k
                    }),
                    log$s.infoAndReportMeasurement({
                        metric: b,
                        tag: k,
                        extra: i.extra,
                        error: at,
                        startTime: j,
                        traceId: s
                    })
                }
            }
            );
            const tt = i.timeout || 2e3;
            $ = window.setTimeout(()=>{
                if ($ && clearTimeout($),
                !this.events.get(s))
                    return;
                const rt = new ActionResponseTimeoutError(`${b} timeout in ${tt}ms`);
                this.emit("actionResponseTimeout", {
                    error: rt,
                    event: i,
                    tag: k
                }),
                et(rt),
                this.events.delete(s),
                this.off(s),
                log$s.infoAndReportMeasurement({
                    metric: b,
                    tag: k,
                    extra: i.extra,
                    error: rt,
                    startTime: j,
                    traceId: s
                })
            }
            , tt)
        }
        )
    }
    emitTraceIdToDecoder(i, o) {
        if (i === Actions.Rotation || i === Actions.Clicking || i === Actions.GetOnVehicle || i === Actions.GetOffVehicle || i === Actions.Joystick) {
            const s = {
                [Actions.Rotation]: "Rotation",
                [Actions.GetOnVehicle]: "GetOnVehicle",
                [Actions.GetOffVehicle]: "GetOffVehicle",
                [Actions.Clicking]: "MoveTo",
                [Actions.Joystick]: "Joystick"
            };
            this.emit("traceId", {
                traceId: o,
                timestamp: Date.now(),
                event: s[i]
            })
        }
    }
}
const eventsManager = new EventsManager;
var Actions = (a=>(a[a.Clicking = 1] = "Clicking",
a[a.PlayCG = 6] = "PlayCG",
a[a.Back = 7] = "Back",
a[a.ChangeRoom = 8] = "ChangeRoom",
a[a.ChangeSkin = 13] = "ChangeSkin",
a[a.Joystick = 15] = "Joystick",
a[a.Transfer = 18] = "Transfer",
a[a.GetOnVehicle = 22] = "GetOnVehicle",
a[a.GetOffVehicle = 23] = "GetOffVehicle",
a[a.StopMoving = 34] = "StopMoving",
a[a.UnaryActionLine = 1e3] = "UnaryActionLine",
a[a.Init = 1001] = "Init",
a[a.Exit = 1002] = "Exit",
a[a.SetIFrameInfo = 1003] = "SetIFrameInfo",
a[a.GetNeighborPoints = 1004] = "GetNeighborPoints",
a[a.ReserveSeat = 1005] = "ReserveSeat",
a[a.GetReserveStatus = 1006] = "GetReserveStatus",
a[a.ChangeNickname = 1007] = "ChangeNickname",
a[a.ChangeBitRateInfo = 1008] = "ChangeBitRateInfo",
a[a.Echo = 1009] = "Echo",
a[a.SetPlayerState = 1010] = "SetPlayerState",
a[a.TurnTo = 1011] = "TurnTo",
a[a.TurnToFace = 1012] = "TurnToFace",
a[a.RotateTo = 1013] = "RotateTo",
a[a.Rotation = 1014] = "Rotation",
a[a.CameraTurnTo = 1015] = "CameraTurnTo",
a[a.ConfirmEvent = 1016] = "ConfirmEvent",
a[a.Broadcast = 1017] = "Broadcast",
a[a.NotifyActionLine = 2e4] = "NotifyActionLine",
a[a.AudienceChangeToVisitor = 1020] = "AudienceChangeToVisitor",
a[a.VisitorChangeToAudience = 1021] = "VisitorChangeToAudience",
a[a.RemoveVisitor = 1022] = "RemoveVisitor",
a[a.GetUserWithAvatar = 1023] = "GetUserWithAvatar",
a[a.GetNewUserState = 1024] = "GetNewUserState",
a[a.SetSyncPolicy = 1025] = "SetSyncPolicy",
a))(Actions || {})
  , RemoveVisitorType = (a=>(a[a.RVT_ChangeToObserver = 1] = "RVT_ChangeToObserver",
a[a.RVT_MoveOutOfTheRoom = 2] = "RVT_MoveOutOfTheRoom",
a))(RemoveVisitorType || {})
  , NewUserStateType = (a=>(a[a.NUST_Undefined = 0] = "NUST_Undefined",
a[a.NUST_Myself = 1] = "NUST_Myself",
a[a.NUST_FollowingList = 2] = "NUST_FollowingList",
a))(NewUserStateType || {})
  , CoreBroadcastType = (a=>(a.PlayAnimation = "PlayAnimation",
a))(CoreBroadcastType || {})
  , MessageHandleType = (a=>(a[a.MHT_Undefined = 0] = "MHT_Undefined",
a[a.MHT_RoomMulticast = 1] = "MHT_RoomMulticast",
a[a.MHT_FollowListMulticast = 2] = "MHT_FollowListMulticast",
a[a.MHT_CustomTargetSync = 3] = "MHT_CustomTargetSync",
a))(MessageHandleType || {});
new Logger("xverse-broadcast");
const cr = class {
    constructor(e, i) {
        this.room = e,
        cr.handlers.push(i)
    }
    broadcast(e) {
        const {data: i, msgType: o=MessageHandleType.MHT_FollowListMulticast, targetUserIds: s, sampleRate: c=1} = e;
        return this.room.actionsHandler.broadcast({
            data: i,
            msgType: o,
            targetUserIds: s,
            sampleRate: c
        })
    }
}
;
let Broadcast = cr;
Tt(Broadcast, "handlers", []);
const log$r = new Logger("actions-handler")
  , QueueActions = [Actions.Transfer, Actions.ChangeSkin, Actions.GetOnVehicle, Actions.GetOffVehicle];
class ActionsHandler {
    constructor(e) {
        Tt(this, "room");
        Tt(this, "currentActiveAction");
        Tt(this, "blockedActions", []);
        Tt(this, "avatarComponentsSync", e=>{
            const i = {
                action_type: Actions.SetPlayerState,
                set_player_state_action: {
                    player_state: {
                        avatar_components: JSON.stringify(e)
                    }
                }
            };
            this.sendData({
                data: i
            })
        }
        );
        this.room = e
    }
    addBlockedActions(e) {
        this.blockedActions.push(...e)
    }
    removeBlockedActions(e) {
        if (!e) {
            this.blockedActions = [];
            return
        }
        const i = this.blockedActions.indexOf(e);
        this.blockedActions.splice(i, 1)
    }
    async sendData(e) {
        await this.beforeSend(e);
        const i = uuid$1();
        if (this.room.networkController.sendRtcData(Zt($t({}, e.data), {
            trace_id: i,
            user_id: this.room.options.userId
        })),
        eventsManager.emitTraceIdToDecoder(e.data.action_type, i),
        this.blockedActions.includes(e.data.action_type))
            return new Promise(()=>{}
            );
        if (e.track === !1)
            return Promise.resolve(null);
        const {sampleRate: o=1, timeout: s=2e3, tag: c, data: d, special: _} = e;
        return eventsManager.track({
            timeout: s,
            traceId: i,
            event: d.action_type,
            tag: c,
            extra: d
        }, {
            special: _,
            sampleRate: o,
            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 c;
        const i = (c = this.room._userAvatar) == null ? void 0 : c.isMoving
          , o = e.data.action_type;
        if (QueueActions.includes(o)) {
            if (this.currentActiveAction)
                return log$r.error(`${Actions[this.currentActiveAction]} still pending, reject ${Actions[o]}`),
                Promise.reject(new FrequencyLimitError(`${Actions[o]} action request frequency limit`));
            this.currentActiveAction = o
        }
        if (i && QueueActions.includes(e.data.action_type))
            try {
                await this.stopMoving()
            } catch (d) {
                this.currentActiveAction = void 0,
                log$r.error("before action stopMoving failed", d)
            }
    }
    async moveTo(e) {
        const {point: i, extra: o="", motionType: s} = e
          , c = {
            action_type: Actions.Clicking,
            clicking_action: {
                clicking_point: i,
                clicking_type: ClickType.IgnoreView,
                extra: encodeURIComponent(o),
                attitude: s
            },
            clicking_state: this.room._currentClickingState
        };
        return this.sendData({
            data: c
        })
    }
    transfer(e) {
        const {renderType: i, player: o, camera: s, areaName: c, attitude: d, pathName: _, person: b, noMedia: k, timeout: j, tag: $, special: _e} = e
          , et = {
            data: {
                action_type: Actions.Transfer,
                transfer_action: {
                    render_type: i,
                    player: o,
                    camera: s,
                    areaName: c,
                    attitude: d,
                    pathName: _,
                    person: {
                        type: b
                    },
                    noMedia: k,
                    tiles: [0, 1, 2, 4]
                }
            },
            special: _e,
            timeout: j || 4e3,
            tag: $
        };
        return this.sendData(et).then(tt=>(typeof b != "undefined" && this.room.updateCurrentNetworkOptions({
            person: b,
            rotationRenderType: i
        }),
        tt))
    }
    changeRotationRenderType(e) {
        const {renderType: i, player: o, camera: s, areaName: c, attitude: d, pathName: _} = e;
        return this.transfer({
            renderType: i,
            player: o,
            camera: s,
            areaName: c,
            attitude: d,
            pathName: _,
            tag: "changeToRotationVideo"
        })
    }
    requestPanorama(e, i, o) {
        const {camera: s, player: c, areaName: d, attitude: _, pathName: b, tag: k} = e;
        return this.transfer({
            renderType: RenderType.ClientRotationPano,
            player: c,
            camera: s,
            person: Person.First,
            areaName: d,
            attitude: _,
            pathName: b,
            noMedia: i,
            timeout: o,
            tag: k || "requestPanorama",
            special: !i
        })
    }
    setMotionType(e) {
        return this.transfer({
            attitude: e,
            tag: "setMotionType"
        })
    }
    setNickName(e) {
        const i = {
            action_type: Actions.ChangeNickname,
            change_nickname_action: {
                nickname: e
            }
        };
        return this.sendData({
            data: i
        })
    }
    getReserveSeat({routeId: e, name: i}) {
        const o = {
            action_type: Actions.ReserveSeat,
            reserve_seat_action: {
                route_id: e,
                name: i
            }
        };
        return this.sendData({
            data: o
        })
    }
    getReserveStatus({routeId: e, name: i, need_detail: o}) {
        const s = {
            action_type: Actions.GetReserveStatus,
            get_reserve_status_action: {
                route_id: e,
                name: i,
                need_detail: o
            }
        };
        return this.sendData({
            data: s,
            timeout: 2e3
        }).then(c=>c.reserveDetail)
    }
    stopMoving() {
        const e = {
            action_type: Actions.StopMoving,
            stop_move_action: {}
        };
        return this.sendData({
            data: e
        })
    }
    getOnVehicle({routeId: e, name: i, camera: o}) {
        const s = {
            action_type: Actions.GetOnVehicle,
            get_on_vehicle_action: {
                route_id: e,
                name: i,
                camera: o
            }
        };
        return this.sendData({
            data: s
        })
    }
    getOffVehicle({renderType: e, player: i, camera: o}) {
        const s = {
            action_type: Actions.GetOffVehicle,
            get_off_vehicle_action: {
                render_type: e,
                player: i,
                camera: o
            }
        };
        return this.sendData({
            data: s
        })
    }
    confirmEvent(e) {
        const i = {
            action_type: Actions.ConfirmEvent,
            confirm_event_action: {
                id: e
            }
        };
        return this.sendData({
            data: i,
            track: !1
        })
    }
    echo(e) {
        const i = {
            action_type: Actions.Echo,
            echo_msg: {
                echoMsg: e
            }
        };
        return this.sendData({
            data: i,
            track: !1
        })
    }
    async changeSkin(e) {
        const i = e.special === void 0 ? e.renderType === RenderType.ClientRotationPano : e.special
          , {skinId: o, mode: s, landingType: c=LandingType.Stay, landingPoint: d, landingCamera: _, renderType: b, areaName: k, attitude: j, pathName: $, person: _e, noMedia: et, timeout: tt, roomTypeId: rt=""} = e
          , it = this.room.skinList.filter(ot=>ot.id === o)[0];
        if (!it) {
            const ot = `skin ${o} is invalid`;
            return log$r.error(ot),
            Promise.reject(new ParamError(ot))
        }
        const nt = {
            action_type: Actions.ChangeSkin,
            change_skin_action: {
                skinID: o,
                mode: s === ChangeMode.Preview ? ChangeMode.Preview : ChangeMode.Confirm,
                skin_data_version: o + it.versionId,
                landing_type: c,
                landing_point: d,
                landing_camera: _,
                render_wrapper: {
                    render_type: b
                },
                areaName: k,
                attitude: j,
                noMedia: et,
                person: _e,
                pathName: $,
                roomTypeId: rt
            }
        };
        return this.sendData({
            data: nt,
            timeout: tt || 6e3,
            special: i
        }).then(async ot=>(b === RenderType.ClientRotationPano && ot && await this.room.panorama.handleReceivePanorama(ot),
        this.handleChangeSkin(e))).catch(ot=>et ? this.handleChangeSkin(e) : Promise.reject(ot))
    }
    handleChangeSkin(e) {
        const {skinId: i, mode: o, renderType: s, areaName: c, attitude: d, pathName: _} = e;
        return this.room.sceneManager.staticmeshComponent.getCgMesh().show(),
        this.room.sceneManager.cameraComponent.switchToCgCamera(),
        this.room.engineProxy._updateSkinAssets(i).then(()=>{
            this.room.sceneManager.staticmeshComponent.getCgMesh().hide(),
            this.room.sceneManager.cameraComponent.switchToMainCamera(),
            this.room.pathManager.currentArea = c,
            log$r.info("changeSkin _updateSkinAssets susccss"),
            this.room.updateCurrentNetworkOptions({
                pathName: _,
                attitude: d,
                areaName: c
            }),
            this.room.skinChangedHook(),
            this.room.emit("skinChanged", {
                skin: {
                    id: i
                },
                mode: o
            }),
            s === RenderType.ClientRotationPano && this.room.sceneManager.cameraComponent.allowMainCameraController()
        }
        )
    }
    rotate({pitch: e, yaw: i}) {
        var s;
        if (this.room.isPano || ((s = this.room._userAvatar) == null ? void 0 : s._isChangingComponentsMode))
            return;
        const o = {
            action_type: Actions.Rotation,
            rotation_action: {
                vertical_move: e,
                horizontal_move: -i
            }
        };
        this.sendData({
            data: o,
            track: !1
        })
    }
    turnTo(e) {
        const {point: i, timeout: o=2e3, offset: s=8} = e || {}
          , c = {
            action_type: Actions.TurnTo,
            turn_to_action: {
                turn_to_point: i,
                offset: s
            }
        };
        return this.sendData({
            data: c,
            timeout: o
        })
    }
    rotateTo(e) {
        const {point: i, offset: o=0, speed: s=3} = e || {}
          , c = {
            action_type: Actions.RotateTo,
            rotate_to_action: {
                rotate_to_point: i,
                offset: o,
                speed: s
            }
        };
        return this.sendData({
            data: c
        })
    }
    broadcast(e) {
        const {data: i, msgType: o=MessageHandleType.MHT_FollowListMulticast, targetUserIds: s, sampleRate: c=1} = e;
        if (o === MessageHandleType.MHT_CustomTargetSync && !Array.isArray(s))
            return Promise.reject(new ParamError(`param targetUserIds is required  when msgType is ${MessageHandleType[o]}`));
        const d = {
            action_type: Actions.Broadcast,
            broadcast_action: {
                data: JSON.stringify(i),
                user_id: this.room.options.userId,
                msgType: o
            }
        };
        return Array.isArray(s) && o === MessageHandleType.MHT_CustomTargetSync && (d.broadcast_action.target_user_ids = s),
        this.room.actionsHandler.sendData({
            data: d,
            tag: i.broadcastType,
            sampleRate: c
        })
    }
    getNeighborPoints(e) {
        const {point: i, containSelf: o=!1, searchRange: s=500} = e
          , c = {
            action_type: Actions.GetNeighborPoints,
            get_neighbor_points_action: {
                point: i,
                level: 1,
                containSelf: o,
                searchRange: s
            }
        };
        return this.sendData({
            data: c
        }).then(d=>d.nps)
    }
    playCG(e) {
        const i = {
            action_type: Actions.PlayCG,
            play_cg_action: {
                cg_name: e
            }
        };
        return this.sendData({
            data: i
        })
    }
    audienceToVisitor(e) {
        const {avatarId: i, avatarComponents: o, player: s, camera: c} = e
          , d = {
            action_type: Actions.AudienceChangeToVisitor,
            audienceChangeToVisitorAction: {
                avatarID: i,
                avatarComponents: o,
                player: s,
                camera: c
            }
        };
        return log$r.debug("send data: audience to visitor"),
        this.sendData({
            data: d
        })
    }
    visitorToAudience(e) {
        const {renderType: i, player: o, camera: s, areaName: c, attitude: d, pathName: _, person: b, noMedia: k} = e
          , j = {
            action_type: Actions.VisitorChangeToAudience,
            visitorChangeToAudienceAction: {
                transferAction: {
                    render_type: i,
                    player: o,
                    camera: s,
                    areaName: c,
                    attitude: d,
                    pathName: _,
                    person: {
                        type: b
                    },
                    noMedia: k,
                    tiles: [0, 1, 2, 4]
                }
            }
        };
        return log$r.debug("send data: visitor to audience"),
        this.sendData({
            data: j
        })
    }
    removeVisitor(e) {
        const {removeType: i, userIDList: o, extraInfo: s=""} = e
          , c = {
            action_type: Actions.RemoveVisitor,
            removeVisitorAction: {
                removeVisitorEvent: i,
                userIDList: o.map(d=>String(d)),
                extraInfo: encodeURIComponent(s)
            }
        };
        return log$r.debug("send data: remove visitor"),
        this.sendData({
            data: c
        })
    }
    getUserWithAvatar(e, i) {
        const o = {
            action_type: Actions.GetUserWithAvatar,
            getUserWithAvatarAction: {
                userType: e,
                roomID: i
            }
        };
        return log$r.debug("send data: get user with avatar"),
        this.sendData({
            data: o,
            sampleRate: 0
        }).then(s=>(Math.random() < .1 && log$r.infoAndReportMeasurement({
            metric: "getUserWithAvatar",
            startTime: Date.now(),
            extra: {
                visitors: s.userWithAvatarList,
                avatars: this.room.avatars.filter(c=>c.withModel).map(c=>({
                    isHost: c.isHost,
                    userID: c.userId
                }))
            }
        }),
        s.userWithAvatarList))
    }
    getNewUserState(e) {
        const i = {
            action_type: Actions.GetNewUserState,
            getNewUserStateAction: {
                userType: e
            }
        };
        return this.sendData({
            data: i,
            sampleRate: 0
        }).then(o=>o)
    }
    setSyncPolicy({syncPolicy: e}) {
        const i = {
            action_type: Actions.SetSyncPolicy,
            setSyncPolicyAction: {
                syncPolicy: e
            }
        };
        return this.sendData({
            data: i
        })
    }
    joystick(e) {
        const {degree: i, level: o=1} = e
          , s = uuid$1();
        let c = -i + 90 + 360;
        c >= 360 && (c -= 360);
        const d = {
            action_type: Actions.Joystick,
            dir_action: {
                move_angle: c,
                speed_level: o
            },
            trace_id: s,
            user_id: this.room.options.userId,
            packet_id: s
        };
        return this.sendData({
            data: d,
            track: !1
        })
    }
}
const log$q = new Logger("db");
class BaseTable {
    constructor(e, i) {
        Tt(this, "db");
        Tt(this, "isCreatingTable", !1);
        Tt(this, "hasCleared", !1);
        this.dbName = e,
        this.dbVersion = i
    }
    async clearDataBase(e) {
        return this.hasCleared || (e && (this.hasCleared = !0),
        !window.indexedDB.databases) ? Promise.resolve() : new Promise((i,o)=>{
            const s = window.indexedDB.deleteDatabase(this.dbName);
            s.onsuccess = ()=>{
                i()
            }
            ,
            s.onerror = o
        }
        )
    }
    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,i)=>{
            const s = setTimeout(()=>{
                log$q.warn("wait db to open for", 200),
                this.db ? e(this.db) : e(this.checkAndOpenDatabase()),
                clearTimeout(s)
            }
            , 200);
            this.openDatabase(this.dbName, this.dbVersion || 1, ()=>{
                this.db && !this.isCreatingTable && e(this.db),
                log$q.warn(`successCallback called, this.db: ${!!this.db}, this.isCreatingStore: ${this.isCreatingTable}`),
                clearTimeout(s)
            }
            , ()=>{
                i(new Error("Failed to open database!")),
                clearTimeout(s)
            }
            , ()=>{
                this.db && e(this.db),
                clearTimeout(s),
                log$q.warn(`successCallback called, this.db: ${!!this.db}, this.isCreatingStore: ${this.isCreatingTable}`)
            }
            )
        }
        )
    }
    openDatabase(e, i, o, s, c) {
        if (this.isCreatingTable)
            return;
        this.isCreatingTable = !0,
        log$q.warn({
            database: e,
            version: i
        });
        const d = window.indexedDB.open(e, i)
          , _ = this.tableName();
        d.onsuccess = b=>{
            this.db = d.result,
            log$q.warn(`IndexedDb ${e} is opened.`),
            this.db.objectStoreNames.contains(_) && (this.isCreatingTable = !1),
            o && o(b)
        }
        ,
        d.onerror = b=>{
            var k;
            log$q.error("Failed to open database", (k = b == null ? void 0 : b.srcElement) == null ? void 0 : k.error),
            this.isCreatingTable = !1,
            s && s(b),
            this.clearDataBase(!0)
        }
        ,
        d.onupgradeneeded = b=>{
            const k = b.target.result
              , j = this.index();
            log$q.warn(`Creating table ${_}.`);
            let$ = k.objectStoreNames.contains(_);
            if ($)
                $ = k.transaction([_], "readwrite").objectStore(_);
            else {
                const _e = this.keyPath();
                $ = k.createObjectStore(_, {
                    keyPath: _e
                })
            }
            j.map(_e=>{
                $.createIndex(_e, _e, {
                    unique: !1
                })
            }
            ),
            this.isCreatingTable = !1,
            log$q.warn(`Table ${_} opened`),
            c && c(b)
        }
    }
    async add(e) {
        const i = this.tableName()
          , c = (await this.checkAndOpenDatabase()).transaction([i], "readwrite").objectStore(i).add(e);
        return new Promise(function(d, _) {
            c.onsuccess = b=>{
                d(b)
            }
            ,
            c.onerror = b=>{
                var k;
                log$q.error((k = b.srcElement) == null ? void 0 : k.error),
                _(b)
            }
        }
        )
    }
    async put(e) {
        const i = this.tableName()
          , c = (await this.checkAndOpenDatabase()).transaction([i], "readwrite").objectStore(i).put(e);
        return new Promise(function(d, _) {
            c.onsuccess = b=>{
                d(b)
            }
            ,
            c.onerror = b=>{
                var k;
                log$q.error("db put error", (k = b.srcElement) == null ? void 0 : k.error),
                _(b)
            }
        }
        )
    }
    delete(e, i, o) {
        const s = this.tableName();
        this.checkAndOpenDatabase().then(c=>{
            const _ = c.transaction([s], "readwrite").objectStore(s).delete(e);
            _.onsuccess = i,
            _.onerror = o
        }
        )
    }
    update() {
        this.checkAndOpenDatabase().then(e=>{}
        )
    }
    async getAllKeys() {
        const e = this.tableName()
          , i = await this.checkAndOpenDatabase();
        return new Promise((o,s)=>{
            const d = i.transaction([e], "readonly").objectStore(e).getAllKeys();
            d.onsuccess = _=>{
                o(_.target.result)
            }
            ,
            d.onerror = _=>{
                log$q.error("db getAllKeys error", _),
                s(_)
            }
        }
        )
    }
    async query(e, i) {
        const o = this.tableName()
          , s = await this.checkAndOpenDatabase();
        return new Promise((c,d)=>{
            const k = s.transaction([o], "readonly").objectStore(o).index(e).get(i);
            k.onsuccess = function(j) {
                var _e;
                const $ = (_e = j == null ? void 0 : j.target) == null ? void 0 : _e.result;
                c && c($)
            }
            ,
            k.onerror = j=>{
                log$q.error("db query error", j),
                d(j)
            }
        }
        )
    }
    async sleep(e) {
        return new Promise(i=>{
            setTimeout(()=>{
                i("")
            }
            , e)
        }
        )
    }
}
class ModelTable extends BaseTable {
    constructor() {
        super("XverseDatabase", 1)
    }
    tableName() {
        return "models"
    }
    index() {
        return ["url"]
    }
    keyPath() {
        return "url"
    }
}
const modelTable = new ModelTable;
var axios$2 = {
    exports: {}
}
  , bind$2 = function(e, i) {
    return function() {
        for (var s = new Array(arguments.length), c = 0; c < s.length; c++)
            s[c] = arguments[c];
        return e.apply(i, s)
    }
}
  , bind$1 = bind$2
  , toString = Object.prototype.toString;
function isArray$1(a) {
    return toString.call(a) === "[object Array]"
}
function isUndefined(a) {
    return typeof a == "undefined"
}
function isBuffer(a) {
    return a !== null && !isUndefined(a) && a.constructor !== null && !isUndefined(a.constructor) && typeof a.constructor.isBuffer == "function" && a.constructor.isBuffer(a)
}
function isArrayBuffer(a) {
    return toString.call(a) === "[object ArrayBuffer]"
}
function isFormData(a) {
    return typeof FormData != "undefined" && a instanceof FormData
}
function isArrayBufferView(a) {
    var e;
    return typeof ArrayBuffer != "undefined" && ArrayBuffer.isView ? e = ArrayBuffer.isView(a) : e = a && a.buffer && a.buffer instanceof ArrayBuffer,
    e
}
function isString(a) {
    return typeof a == "string"
}
function isNumber(a) {
    return typeof a == "number"
}
function isObject(a) {
    return a !== null && typeof a == "object"
}
function isPlainObject(a) {
    if (toString.call(a) !== "[object Object]")
        return !1;
    var e = Object.getPrototypeOf(a);
    return e === null || e === Object.prototype
}
function isDate(a) {
    return toString.call(a) === "[object Date]"
}
function isFile(a) {
    return toString.call(a) === "[object File]"
}
function isBlob(a) {
    return toString.call(a) === "[object Blob]"
}
function isFunction$1(a) {
    return toString.call(a) === "[object Function]"
}
function isStream(a) {
    return isObject(a) && isFunction$1(a.pipe)
}
function isURLSearchParams(a) {
    return typeof URLSearchParams != "undefined" && a instanceof URLSearchParams
}
function trim(a) {
    return a.trim ? a.trim() : a.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(a, e) {
    if (!(a === null || typeof a == "undefined"))
        if (typeof a != "object" && (a = [a]),
        isArray$1(a))
            for (var i = 0, o = a.length; i < o; i++)
                e.call(null, a[i], i, a);
        else
            for (var s in a)
                Object.prototype.hasOwnProperty.call(a, s) && e.call(null, a[s], s, a)
}
function merge() {
    var a = {};
    function e(s, c) {
        isPlainObject(a[c]) && isPlainObject(s) ? a[c] = merge(a[c], s) : isPlainObject(s) ? a[c] = merge({}, s) : isArray$1(s) ? a[c] = s.slice() : a[c] = s
    }
    for (var i = 0, o = arguments.length; i < o; i++)
        forEach(arguments[i], e);
    return a
}
function extend$2(a, e, i) {
    return forEach(e, function(s, c) {
        i && typeof s == "function" ? a[c] = bind$1(s, i) : a[c] = s
    }),
    a
}
function stripBOM(a) {
    return a.charCodeAt(0) === 65279 && (a = a.slice(1)),
    a
}
var utils$d = {
    isArray: isArray$1,
    isArrayBuffer,
    isBuffer,
    isFormData,
    isArrayBufferView,
    isString,
    isNumber,
    isObject,
    isPlainObject,
    isUndefined,
    isDate,
    isFile,
    isBlob,
    isFunction: isFunction$1,
    isStream,
    isURLSearchParams,
    isStandardBrowserEnv,
    forEach,
    merge,
    extend: extend$2,
    trim,
    stripBOM
}
  , utils$c = utils$d;
function encode(a) {
    return encodeURIComponent(a).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]")
}
var buildURL$2 = function(e, i, o) {
    if (!i)
        return e;
    var s;
    if (o)
        s = o(i);
    else if (utils$c.isURLSearchParams(i))
        s = i.toString();
    else {
        var c = [];
        utils$c.forEach(i, function(b, k) {
            b === null || typeof b == "undefined" || (utils$c.isArray(b) ? k = k + "[]" : b = [b],
            utils$c.forEach(b, function($) {
                utils$c.isDate($) ? $ = $.toISOString() : utils$c.isObject($) && ($ = JSON.stringify($)),
                c.push(encode(k) + "=" + encode($))
            }))
        }),
        s = c.join("&")
    }
    if (s) {
        var d = e.indexOf("#");
        d !== -1 && (e = e.slice(0, d)),
        e += (e.indexOf("?") === -1 ? "?" : "&") + s
    }
    return e
}
  , utils$b = utils$d;
function InterceptorManager$1() {
    this.handlers = []
}
InterceptorManager$1.prototype.use = function(e, i, o) {
    return this.handlers.push({
        fulfilled: e,
        rejected: i,
        synchronous: o ? o.synchronous : !1,
        runWhen: o ? o.runWhen : null
    }),
    this.handlers.length - 1
}
;
InterceptorManager$1.prototype.eject = function(e) {
    this.handlers[e] && (this.handlers[e] = null)
}
;
InterceptorManager$1.prototype.forEach = function(e) {
    utils$b.forEach(this.handlers, function(o) {
        o !== null && e(o)
    })
}
;
var InterceptorManager_1 = InterceptorManager$1
  , utils$a = utils$d
  , normalizeHeaderName$1 = function(e, i) {
    utils$a.forEach(e, function(s, c) {
        c !== i && c.toUpperCase() === i.toUpperCase() && (e[i] = s,
        delete e[c])
    })
}
  , enhanceError$2 = function(e, i, o, s, c) {
    return e.config = i,
    o && (e.code = o),
    e.request = s,
    e.response = c,
    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(e, i, o, s, c) {
    var d = new Error(e);
    return enhanceError$1(d, i, o, s, c)
}
  , createError$1 = createError$2
  , settle$1 = function(e, i, o) {
    var s = o.config.validateStatus;
    !o.status || !s || s(o.status) ? e(o) : i(createError$1("Request failed with status code " + o.status, o.config, null, o.request, o))
}
  , utils$9 = utils$d
  , cookies$1 = utils$9.isStandardBrowserEnv() ? function() {
    return {
        write: function(i, o, s, c, d, _) {
            var b = [];
            b.push(i + "=" + encodeURIComponent(o)),
            utils$9.isNumber(s) && b.push("expires=" + new Date(s).toGMTString()),
            utils$9.isString(c) && b.push("path=" + c),
            utils$9.isString(d) && b.push("domain=" + d),
            _ === !0 && b.push("secure"),
            document.cookie = b.join("; ")
        },
        read: function(i) {
            var o = document.cookie.match(new RegExp("(^|;\\s*)(" + i + ")=([^;]*)"));
            return o ? decodeURIComponent(o[3]) : null
        },
        remove: function(i) {
            this.write(i, "", Date.now() - 864e5)
        }
    }
}() : function() {
    return {
        write: function() {},
        read: function() {
            return null
        },
        remove: function() {}
    }
}()
  , isAbsoluteURL$1 = function(e) {
    return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)
}
  , combineURLs$1 = function(e, i) {
    return i ? e.replace(/\/+$/, "") + "/" + i.replace(/^\/+/, "") : e
}
  , isAbsoluteURL = isAbsoluteURL$1
  , combineURLs = combineURLs$1
  , buildFullPath$1 = function(e, i) {
    return e && !isAbsoluteURL(i) ? combineURLs(e, i) : i
}
  , 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(e) {
    var i = {}, o, s, c;
    return e && utils$8.forEach(e.split(`
`), function(_) {
        if (c = _.indexOf(":"),
        o = utils$8.trim(_.substr(0, c)).toLowerCase(),
        s = utils$8.trim(_.substr(c + 1)),
        o) {
            if (i[o] && ignoreDuplicateOf.indexOf(o) >= 0)
                return;
            o === "set-cookie" ? i[o] = (i[o] ? i[o] : []).concat([s]) : i[o] = i[o] ? i[o] + ", " + s : s
        }
    }),
    i
}
  , utils$7 = utils$d
  , isURLSameOrigin$1 = utils$7.isStandardBrowserEnv() ? function() {
    var e = /(msie|trident)/i.test(navigator.userAgent), i = document.createElement("a"), o;
    function s(c) {
        var d = c;
        return e && (i.setAttribute("href", d),
        d = i.href),
        i.setAttribute("href", d),
        {
            href: i.href,
            protocol: i.protocol ? i.protocol.replace(/:$/, "") : "",
            host: i.host,
            search: i.search ? i.search.replace(/^\?/, "") : "",
            hash: i.hash ? i.hash.replace(/^#/, "") : "",
            hostname: i.hostname,
            port: i.port,
            pathname: i.pathname.charAt(0) === "/" ? i.pathname : "/" + i.pathname
        }
    }
    return o = s(window.location.href),
    function(d) {
        var _ = utils$7.isString(d) ? s(d) : d;
        return _.protocol === o.protocol && _.host === o.host
    }
}() : function() {
    return function() {
        return !0
    }
}();
function Cancel$3(a) {
    this.message = a
}
Cancel$3.prototype.toString = function() {
    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(e) {
    return new Promise(function(o, s) {
        var c = e.data, d = e.headers, _ = e.responseType, b;
        function k() {
            e.cancelToken && e.cancelToken.unsubscribe(b),
            e.signal && e.signal.removeEventListener("abort", b)
        }
        utils$6.isFormData(c) && delete d["Content-Type"];
        var j = new XMLHttpRequest;
        if (e.auth) {
            var $ = e.auth.username || ""
              , _e = e.auth.password ? unescape(encodeURIComponent(e.auth.password)) : "";
            d.Authorization = "Basic " + btoa($ + ":" + _e)
        }
        var et = buildFullPath(e.baseURL, e.url);
        j.open(e.method.toUpperCase(), buildURL$1(et, e.params, e.paramsSerializer), !0),
        j.timeout = e.timeout;
        function tt() {
            if (!!j) {
                var it = "getAllResponseHeaders"in j ? parseHeaders(j.getAllResponseHeaders()) : null
                  , nt = !_ || _ === "text" || _ === "json" ? j.responseText : j.response
                  , ot = {
                    data: nt,
                    status: j.status,
                    statusText: j.statusText,
                    headers: it,
                    config: e,
                    request: j
                };
                settle(function(st) {
                    o(st),
                    k()
                }, function(st) {
                    s(st),
                    k()
                }, ot),
                j = null
            }
        }
        if ("onloadend"in j ? j.onloadend = tt : j.onreadystatechange = function() {
            !j || j.readyState !== 4 || j.status === 0 && !(j.responseURL && j.responseURL.indexOf("file:") === 0) || setTimeout(tt)
        }
        ,
        j.onabort = function() {
            !j || (s(createError("Request aborted", e, "ECONNABORTED", j)),
            j = null)
        }
        ,
        j.onerror = function() {
            s(createError("Network Error", e, null, j)),
            j = null
        }
        ,
        j.ontimeout = function() {
            var nt = e.timeout ? "timeout of " + e.timeout + "ms exceeded" : "timeout exceeded"
              , ot = e.transitional || defaults$4.transitional;
            e.timeoutErrorMessage && (nt = e.timeoutErrorMessage),
            s(createError(nt, e, ot.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED", j)),
            j = null
        }
        ,
        utils$6.isStandardBrowserEnv()) {
            var rt = (e.withCredentials || isURLSameOrigin(et)) && e.xsrfCookieName ? cookies.read(e.xsrfCookieName) : void 0;
            rt && (d[e.xsrfHeaderName] = rt)
        }
        "setRequestHeader"in j && utils$6.forEach(d, function(nt, ot) {
            typeof c == "undefined" && ot.toLowerCase() === "content-type" ? delete d[ot] : j.setRequestHeader(ot, nt)
        }),
        utils$6.isUndefined(e.withCredentials) || (j.withCredentials = !!e.withCredentials),
        _ && _ !== "json" && (j.responseType = e.responseType),
        typeof e.onDownloadProgress == "function" && j.addEventListener("progress", e.onDownloadProgress),
        typeof e.onUploadProgress == "function" && j.upload && j.upload.addEventListener("progress", e.onUploadProgress),
        (e.cancelToken || e.signal) && (b = function(it) {
            !j || (s(!it || it && it.type ? new Cancel$2("canceled") : it),
            j.abort(),
            j = null)
        }
        ,
        e.cancelToken && e.cancelToken.subscribe(b),
        e.signal && (e.signal.aborted ? b() : e.signal.addEventListener("abort", b))),
        c || (c = null),
        j.send(c)
    }
    )
}
  , utils$5 = utils$d
  , normalizeHeaderName = normalizeHeaderName$1
  , enhanceError = enhanceError$2
  , DEFAULT_CONTENT_TYPE = {
    "Content-Type": "application/x-www-form-urlencoded"
};
function setContentTypeIfUnset(a, e) {
    !utils$5.isUndefined(a) && utils$5.isUndefined(a["Content-Type"]) && (a["Content-Type"] = e)
}
function getDefaultAdapter() {
    var a;
    return (typeof XMLHttpRequest != "undefined" || typeof process != "undefined" && Object.prototype.toString.call(process) === "[object process]") && (a = xhr),
    a
}
function stringifySafely(a, e, i) {
    if (utils$5.isString(a))
        try {
            return (e || JSON.parse)(a),
            utils$5.trim(a)
        } catch (o) {
            if (o.name !== "SyntaxError")
                throw o
        }
    return (i || JSON.stringify)(a)
}
var defaults$3 = {
    transitional: {
        silentJSONParsing: !0,
        forcedJSONParsing: !0,
        clarifyTimeoutError: !1
    },
    adapter: getDefaultAdapter(),
    transformRequest: [function(e, i) {
        return normalizeHeaderName(i, "Accept"),
        normalizeHeaderName(i, "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(i, "application/x-www-form-urlencoded;charset=utf-8"),
        e.toString()) : utils$5.isObject(e) || i && i["Content-Type"] === "application/json" ? (setContentTypeIfUnset(i, "application/json"),
        stringifySafely(e)) : e
    }
    ],
    transformResponse: [function(e) {
        var i = this.transitional || defaults$3.transitional
          , o = i && i.silentJSONParsing
          , s = i && i.forcedJSONParsing
          , c = !o && this.responseType === "json";
        if (c || s && utils$5.isString(e) && e.length)
            try {
                return JSON.parse(e)
            } catch (d) {
                if (c)
                    throw d.name === "SyntaxError" ? enhanceError(d, this, "E_JSON_PARSE") : d
            }
        return e
    }
    ],
    timeout: 0,
    xsrfCookieName: "XSRF-TOKEN",
    xsrfHeaderName: "X-XSRF-TOKEN",
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: function(e) {
        return e >= 200 && e < 300
    },
    headers: {
        common: {
            Accept: "application/json, text/plain, */*"
        }
    }
};
utils$5.forEach(["delete", "get", "head"], function(e) {
    defaults$3.headers[e] = {}
});
utils$5.forEach(["post", "put", "patch"], function(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(e, i, o) {
    var s = this || defaults$2;
    return utils$4.forEach(o, function(d) {
        e = d.call(s, e, i)
    }),
    e
}
  , isCancel$1 = function(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(a) {
    if (a.cancelToken && a.cancelToken.throwIfRequested(),
    a.signal && a.signal.aborted)
        throw new Cancel$1("canceled")
}
var dispatchRequest$1 = function(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(s) {
        delete e.headers[s]
    });
    var i = e.adapter || defaults$1.adapter;
    return i(e).then(function(s) {
        return throwIfCancellationRequested(e),
        s.data = transformData.call(e, s.data, s.headers, e.transformResponse),
        s
    }, function(s) {
        return isCancel(s) || (throwIfCancellationRequested(e),
        s && s.response && (s.response.data = transformData.call(e, s.response.data, s.response.headers, e.transformResponse))),
        Promise.reject(s)
    })
}
  , utils$2 = utils$d
  , mergeConfig$2 = function(e, i) {
    i = i || {};
    var o = {};
    function s(j, $) {
        return utils$2.isPlainObject(j) && utils$2.isPlainObject($) ? utils$2.merge(j, $) : utils$2.isPlainObject($) ? utils$2.merge({}, $) : utils$2.isArray($) ? $.slice() : $
    }
    function c(j) {
        if (utils$2.isUndefined(i[j])) {
            if (!utils$2.isUndefined(e[j]))
                return s(void 0, e[j])
        } else
            return s(e[j], i[j])
    }
    function d(j) {
        if (!utils$2.isUndefined(i[j]))
            return s(void 0, i[j])
    }
    function _(j) {
        if (utils$2.isUndefined(i[j])) {
            if (!utils$2.isUndefined(e[j]))
                return s(void 0, e[j])
        } else
            return s(void 0, i[j])
    }
    function b(j) {
        if (j in i)
            return s(e[j], i[j]);
        if (j in e)
            return s(void 0, e[j])
    }
    var k = {
        url: d,
        method: d,
        data: d,
        baseURL: _,
        transformRequest: _,
        transformResponse: _,
        paramsSerializer: _,
        timeout: _,
        timeoutMessage: _,
        withCredentials: _,
        adapter: _,
        responseType: _,
        xsrfCookieName: _,
        xsrfHeaderName: _,
        onUploadProgress: _,
        onDownloadProgress: _,
        decompress: _,
        maxContentLength: _,
        maxBodyLength: _,
        transport: _,
        httpAgent: _,
        httpsAgent: _,
        cancelToken: _,
        socketPath: _,
        responseEncoding: _,
        validateStatus: b
    };
    return utils$2.forEach(Object.keys(e).concat(Object.keys(i)), function($) {
        var _e = k[$] || c
          , et = _e($);
        utils$2.isUndefined(et) && _e !== b || (o[$] = et)
    }),
    o
}
  , data = {
    version: "0.24.0"
}
  , VERSION = data.version
  , validators$1 = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach(function(a, e) {
    validators$1[a] = function(o) {
        return typeof o === a || "a" + (e < 1 ? "n " : " ") + a
    }
});
var deprecatedWarnings = {};
validators$1.transitional = function(e, i, o) {
    function s(c, d) {
        return "[Axios v" + VERSION + "] Transitional option '" + c + "'" + d + (o ? ". " + o : "")
    }
    return function(c, d, _) {
        if (e === !1)
            throw new Error(s(d, " has been removed" + (i ? " in " + i : "")));
        return i && !deprecatedWarnings[d] && (deprecatedWarnings[d] = !0,
        console.warn(s(d, " has been deprecated since v" + i + " and will be removed in the near future"))),
        e ? e(c, d, _) : !0
    }
}
;
function assertOptions(a, e, i) {
    if (typeof a != "object")
        throw new TypeError("options must be an object");
    for (var o = Object.keys(a), s = o.length; s-- > 0; ) {
        var c = o[s]
          , d = e[c];
        if (d) {
            var _ = a[c]
              , b = _ === void 0 || d(_, c, a);
            if (b !== !0)
                throw new TypeError("option " + c + " must be " + b);
            continue
        }
        if (i !== !0)
            throw Error("Unknown option " + c)
    }
}
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(a) {
    this.defaults = a,
    this.interceptors = {
        request: new InterceptorManager,
        response: new InterceptorManager
    }
}
Axios$1.prototype.request = function(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 i = e.transitional;
    i !== void 0 && validator.assertOptions(i, {
        silentJSONParsing: validators.transitional(validators.boolean),
        forcedJSONParsing: validators.transitional(validators.boolean),
        clarifyTimeoutError: validators.transitional(validators.boolean)
    }, !1);
    var o = []
      , s = !0;
    this.interceptors.request.forEach(function(_e) {
        typeof _e.runWhen == "function" && _e.runWhen(e) === !1 || (s = s && _e.synchronous,
        o.unshift(_e.fulfilled, _e.rejected))
    });
    var c = [];
    this.interceptors.response.forEach(function(_e) {
        c.push(_e.fulfilled, _e.rejected)
    });
    var d;
    if (!s) {
        var _ = [dispatchRequest, void 0];
        for (Array.prototype.unshift.apply(_, o),
        _ = _.concat(c),
        d = Promise.resolve(e); _.length; )
            d = d.then(_.shift(), _.shift());
        return d
    }
    for (var b = e; o.length; ) {
        var k = o.shift()
          , j = o.shift();
        try {
            b = k(b)
        } catch ($) {
            j($);
            break
        }
    }
    try {
        d = dispatchRequest(b)
    } catch ($) {
        return Promise.reject($)
    }
    for (; c.length; )
        d = d.then(c.shift(), c.shift());
    return d
}
;
Axios$1.prototype.getUri = function(e) {
    return e = mergeConfig$1(this.defaults, e),
    buildURL(e.url, e.params, e.paramsSerializer).replace(/^\?/, "")
}
;
utils$1.forEach(["delete", "get", "head", "options"], function(e) {
    Axios$1.prototype[e] = function(i, o) {
        return this.request(mergeConfig$1(o || {}, {
            method: e,
            url: i,
            data: (o || {}).data
        }))
    }
});
utils$1.forEach(["post", "put", "patch"], function(e) {
    Axios$1.prototype[e] = function(i, o, s) {
        return this.request(mergeConfig$1(s || {}, {
            method: e,
            url: i,
            data: o
        }))
    }
});
var Axios_1 = Axios$1
  , Cancel = Cancel_1;
function CancelToken(a) {
    if (typeof a != "function")
        throw new TypeError("executor must be a function.");
    var e;
    this.promise = new Promise(function(s) {
        e = s
    }
    );
    var i = this;
    this.promise.then(function(o) {
        if (!!i._listeners) {
            var s, c = i._listeners.length;
            for (s = 0; s < c; s++)
                i._listeners[s](o);
            i._listeners = null
        }
    }),
    this.promise.then = function(o) {
        var s, c = new Promise(function(d) {
            i.subscribe(d),
            s = d
        }
        ).then(o);
        return c.cancel = function() {
            i.unsubscribe(s)
        }
        ,
        c
    }
    ,
    a(function(s) {
        i.reason || (i.reason = new Cancel(s),
        e(i.reason))
    })
}
CancelToken.prototype.throwIfRequested = function() {
    if (this.reason)
        throw this.reason
}
;
CancelToken.prototype.subscribe = function(e) {
    if (this.reason) {
        e(this.reason);
        return
    }
    this._listeners ? this._listeners.push(e) : this._listeners = [e]
}
;
CancelToken.prototype.unsubscribe = function(e) {
    if (!!this._listeners) {
        var i = this._listeners.indexOf(e);
        i !== -1 && this._listeners.splice(i, 1)
    }
}
;
CancelToken.source = function() {
    var e, i = new CancelToken(function(s) {
        e = s
    }
    );
    return {
        token: i,
        cancel: e
    }
}
;
var CancelToken_1 = CancelToken
  , spread = function(e) {
    return function(o) {
        return e.apply(null, o)
    }
}
  , isAxiosError = function(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(a) {
    var e = new Axios(a)
      , i = bind(Axios.prototype.request, e);
    return utils.extend(i, Axios.prototype, e),
    utils.extend(i, e),
    i.create = function(s) {
        return createInstance(mergeConfig(a, s))
    }
    ,
    i
}
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(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 = a=>typeof a == "function";
class AxiosCanceler {
    constructor() {
        Tt(this, "pendingMap", new Map)
    }
    addPending(e) {
        return new axios.CancelToken(i=>{
            this.pendingMap.has(e) || this.pendingMap.set(e, i)
        }
        )
    }
    removeAllPending() {
        this.pendingMap.forEach(e=>{
            e && isFunction(e) && e()
        }
        ),
        this.pendingMap.clear()
    }
    removePending(e) {
        if (this.pendingMap.has(e)) {
            const i = this.pendingMap.get(e);
            i && i(e),
            this.pendingMap.delete(e)
        }
    }
    removeCancelToken(e) {
        this.pendingMap.has(e) && this.pendingMap.delete(e)
    }
    reset() {
        this.pendingMap = new Map
    }
}
const log$p = new Logger("http");
class Http$1 {
    constructor() {
        Tt(this, "instatnce");
        Tt(this, "canceler");
        Tt(this, "requestParams", e=>$t({}, e.params));
        Tt(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(Zt($t({}, e), {
            method: "GET"
        }))
    }
    post(e) {
        return this.request(Zt($t({}, e), {
            method: "POST"
        }))
    }
    request(e) {
        const {url: i, timeout: o=1e4, method: s, key: c, beforeRequest: d, responseType: _, data: b} = e;
        let {retry: k=0} = e;
        const j = this.transformUrlHook(i)
          , $ = this.canceler.addPending(i);
        d && isFunction(d) && d(e);
        const _e = this.requestParams(e);
        let et = {
            url: j,
            method: s,
            timeout: o,
            cancelToken: $,
            responseType: _,
            params: _e
        };
        s === "POST" && (et = $t({
            data: b
        }, et));
        const tt = Date.now()
          , rt = ()=>this.instatnce.request(et).then(it=>(c && log$p.infoAndReportMeasurement({
            metric: "http",
            startTime: tt,
            extra: i,
            group: "http",
            tag: c
        }),
        this.canceler.removeCancelToken(i),
        it)).catch(it=>{
            const nt = axios.isCancel(it);
            return k > 0 && !nt ? (k--,
            log$p.warn(`request ${i} retry, left retry count`, k),
            rt()) : (log$p.infoAndReportMeasurement({
                metric: "http",
                startTime: tt,
                error: it,
                extra: {
                    url: i,
                    isCanceled: nt
                },
                tag: c,
                group: "http"
            }),
            this.canceler.removeCancelToken(i),
            Promise.reject(it))
        }
        );
        return rt()
    }
    transformUrlHook(e) {
        return e
    }
    randomString() {
        let e = "";
        const i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
          , o = i.length;
        for (let s = 0; s < 8; s++)
            e += i.charAt(Math.floor(Math.random() * o));
        return e
    }
}
const http$1 = new Http$1
  , log$o = new Logger("AssetsStorage");
class AssetsStorage {
    static async readOrRequest(e, i) {
        let o = null;
        try {
            o = await modelTable.query("url", e)
        } catch (c) {
            return log$o.debug(c),
            log$o.warn("cache query error", e),
            Promise.resolve(e)
        }
        let s = o && o.model;
        return s || (s = await this.requestAndPut({
            url: e,
            responseType: "blob",
            retry: 2
        })),
        typeof s == "string" && (s = this.dataURItoBlob(s)),
        i && i.returnBlob ? s : URL.createObjectURL(s)
    }
    static async requestAndPut(e) {
        try {
            const i = await http$1.get(e);
            return await modelTable.put({
                url: e.url,
                model: i.data
            }),
            i.data
        } catch {
            return Promise.reject(new InternalError("request and put error"))
        }
    }
}
Tt(AssetsStorage, "dataURItoBlob", e=>{
    let i;
    e.split(",")[0].indexOf("base64") >= 0 ? i = atob(e.split(",")[1]) : i = unescape(e.split(",")[1]);
    const o = e.split(",")[0].split(":")[1].split(";")[0]
      , s = new Uint8Array(i.length);
    for (let d = 0; d < i.length; d++)
        s[d] = i.charCodeAt(d);
    return new Blob([s],{
        type: o
    })
}
);
const fr = class {
    static _GetStorage() {
        try {
            return localStorage.setItem("test", ""),
            localStorage.removeItem("test"),
            localStorage
        } catch {
            const e = {};
            return {
                getItem: i=>{
                    const o = e[i];
                    return o === void 0 ? null : o
                }
                ,
                setItem: (i,o)=>{
                    e[i] = o
                }
            }
        }
    }
    static ReadString(e, i) {
        const o = this._Storage.getItem(e);
        return o !== null ? o : i
    }
    static WriteString(e, i) {
        this._Storage.setItem(e, i)
    }
    static ReadBoolean(e, i) {
        const o = this._Storage.getItem(e);
        return o !== null ? o === "true" : i
    }
    static WriteBoolean(e, i) {
        this._Storage.setItem(e, i ? "true" : "false")
    }
    static ReadNumber(e, i) {
        const o = this._Storage.getItem(e);
        return o !== null ? parseFloat(o) : i
    }
    static WriteNumber(e, i) {
        this._Storage.setItem(e, i.toString())
    }
}
;
let DataStorage = fr;
Tt(DataStorage, "_Storage", fr._GetStorage());
const urlMap = new Map
  , urlTransformer = async(a,e=!1)=>typeof a != "string" ? (console.warn("url transformer error", a),
a) : a.startsWith("blob:") ? a : e ? AssetsStorage.readOrRequest(a, {
    returnBlob: !0
}) : urlMap.has(a) ? urlMap.get(a) : AssetsStorage.readOrRequest(a).then(i=>(urlMap.set(a, i),
i));
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$n = new Logger("detect");
let worker = null;
function checkNetworkQuality(a) {
    if (!a)
        return;
    const e = Date.now();
    if (pingOthers("https://www.baidu.com", function(i, o) {
        log$n.infoAndReportMeasurement({
            metric: "baiduRtt",
            group: "http",
            value: o,
            startTime: e
        })
    }),
    !worker) {
        const i = new Blob([workerSourceCode],{
            type: "application/javascript"
        });
        worker = new Worker(URL.createObjectURL(i)),
        worker.onmessage = function(o) {
            log$n.infoAndReportMeasurement({
                metric: "workerRtt",
                group: "http",
                startTime: e,
                value: o.data
            })
        }
    }
}
function pingOthers(a, e) {
    let i = !1;
    const o = new Image;
    o.onload = c,
    o.onerror = d;
    const s = Date.now();
    function c(b) {
        i = !0,
        _()
    }
    function d(b) {}
    function _() {
        const b = Date.now() - s;
        if (typeof e == "function")
            return i ? e(null, b) : (console.error("error loading resource"),
            e("error", b))
    }
    o.src = a + "/favicon.ico?" + +new Date
}
const log$m = new Logger("heartbeat");
class Heartbeat {
    constructor(e) {
        Tt(this, "_interval", null);
        Tt(this, "ping", ()=>{
            const e = Date.now().toString();
            this.handler.ping(e)
        }
        );
        this.handler = e
    }
    start() {
        this.stop(),
        log$m.debug(`Setting ping interval to ${PING_INTERVAL_MS}ms`),
        this._interval = window.setInterval(this.ping, PING_INTERVAL_MS)
    }
    stop() {
        log$m.debug("stop heartbeat"),
        this._interval && window.clearInterval(this._interval)
    }
    pong(e, i) {
        !e || typeof e == "string" && this.handler.pong(Date.now() - Number(e), i)
    }
}
class NetworkMonitor {
    constructor(e) {
        Tt(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(a) {
        if (!a)
            return;
        const e = ++this.id
          , i = {
            id: e,
            handler: a
        };
        return this.subscribers.push(i),
        ()=>{
            this.subscribers = this.subscribers.filter(s=>s.id == e)
        }
    },
    destroy() {
        !this.bindFunc || (document.hidden !== void 0 ? document.removeEventListener("visibilitychange", this.bindFunc, !1) : document.webkitHidden && document.removeEventListener("webkitvisibilitychange", this.bindFunc, !1))
    },
    broadcast(a) {
        this.subscribers.forEach(e=>e.handler(a))
    },
    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/v17/lib_ff264dec.js",
    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(a, e) {
    return e == -1 && (e = 0),
    a + e
}
function count_valid(a, e) {
    let i = 0;
    return e != -1 && (i = 1),
    a + i
}
function count_less(a, e) {
    function i(o, s) {
        let c = 0;
        return s != -1 && s < e && (c = 1),
        o + c
    }
    return a.reduce(i, 0)
}
function count_sd(a, e) {
    function i(o, s) {
        let c = 0;
        return s == -1 ? c = 0 : c = (s - e) * (s - e),
        o + c
    }
    return Math.sqrt(a.reduce(i, 0) / a.reduce(count_valid, 0)) || 0
}
function max(a, e) {
    return Math.max(a, e)
}
class CircularArray {
    constructor(e, i, o) {
        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,
        i && (this.countLess = !0,
        this.lessThreshes = o)
    }
    add(e) {
        e < 0 || (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.computeMax(this.circularData))) : 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 i = count_less(e, this.lessThreshes[0]) || 0
              , o = count_less(e, this.lessThreshes[1]) || 0
              , s = count_less(e, this.lessThreshes[2]) || 0
              , c = count_less(e, this.lessThreshes[3]) || 0
              , d = e.reduce(count_valid, 0);
            return [i, o, s, c, d]
        } else
            return [0, 0, 0, 0, 0]
    }
    getAvg() {
        return this.sum / this.count || 0 || 0
    }
    getMax(e=!0) {
        return this.max || 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()
    }
}
class SecondArray {
    constructor() {
        this.circularData = []
    }
    add(e) {
        this.circularData.push(e)
    }
    getAvg() {
        let e = 0;
        for (let i = 0; i < this.circularData.length; i++)
            e += this.circularData[i];
        return {
            sum: e,
            avg: e / this.circularData.length || 0
        }
    }
    getMax() {
        let e = 0;
        for (let i = 0; i < this.circularData.length; i++)
            e < this.circularData[i] && (e = this.circularData[i]);
        return e || 0
    }
    clear() {
        this.circularData = []
    }
    getStat() {
        const e = this.getAvg()
          , i = {
            sum: e.sum,
            avg: e.avg,
            max: this.getMax()
        };
        return this.clear(),
        i
    }
}
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)
      // currently only need to use flushDecoder for pano mode.
      ret = Module._flushDecoder(0, 0, 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,
      metadata: data.data.metadata,
      // 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) {
        objData.postTs = Date.now()
        self.postMessage(objData, [objData.data.buffer])
        send_out_buffer += 1
        this.receivedEmit++
      } else {
        objData.postTs = Date.now()
        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(a) {
    return a / 180 * Math.PI
}
function ToAngle(a) {
    return a / Math.PI * 180
}
function getAngleInView(a, e) {
    const i = {}
      , o = e.x - a.width * .5
      , s = a.height * .5 - e.y
      , c = -1 * ToRadius(a.angle.pitch)
      , d = ToRadius(a.angle.yaw)
      , _ = a.width / 2 / Math.tan(ToRadius(a.horz_fov / 2))
      , b = Math.sin(c)
      , k = Math.cos(c);
    for (i.yaw = Math.atan2(o, _ * k + s * b),
    i.pitch = Math.atan2((s - _ * Math.tan(c)) * Math.cos(i.yaw), _ + s * Math.tan(c)),
    i.pitch = ToAngle(i.pitch),
    i.yaw = ToAngle(d + i.yaw); i.yaw > 359.9; )
        i.yaw -= 360;
    for (; i.yaw < 0; )
        i.yaw += 360;
    return i
}
function getRectangleInView(a) {
    const e = {}
      , i = Array(9)
      , o = a.height
      , s = a.width;
    for (let d = 0, _ = 0; _ <= o; _ += o / 2)
        for (let b = 0; b <= s; b += s / 2,
        d++) {
            const k = {};
            k.x = b,
            k.y = _;
            let j = {};
            j = a,
            j.angle.pitch >= 90 && (j.angle.pitch = 89.999),
            j.angle.pitch <= -90 && (j.angle.pitch = -89.999),
            j.angle.yaw = 0,
            i[d] = getAngleInView(a, k),
            i[d].pitch < -90 ? i[d].pitch = 90 : i[d].pitch > 90 && (i[d].pitch = -90)
        }
    let c = i[0].yaw > i[3].yaw ? 3 : 0;
    return i[c].yaw > i[6].yaw && (c = 6),
    i[c].yaw > i[c + 2].yaw && (i[c + 2].yaw += 360),
    i[c + 2].yaw > i[c].yaw + 180 ? (e.x = 0,
    e.width = panorama_width) : (e.x = (i[c].yaw / 360 - .5) * panorama_width,
    e.width = (i[c + 2].yaw / 360 - .5) * panorama_width - e.x),
    e.y = (.5 - i[i[0].pitch > i[1].pitch ? 0 : 1].pitch / 180) * panorama_height,
    e.height = (.5 - i[i[6].pitch > i[7].pitch ? 7 : 6].pitch / 180) * panorama_height - e.y,
    e
}
function MaskSetToOne(a, e) {
    const i = a / 8
      , o = a % 8;
    e.setUint8(i, e.getUint8(i) | 1 << 7 - o)
}
function IsAll0(a) {
    return a.getUint32(0) == 0 && a.getUint32(4) == 0
}
function getMaskFromTiles(a, e) {
    const i = new DataView(e);
    a.forEach(function(o, s) {
        MaskSetToOne(o, i)
    })
}
function operateForDataView(a, e, i, o) {
    i.setUint32(0, o(a.getUint32(0), e.getUint32(0))),
    i.setUint32(4, o(a.getUint32(4), e.getUint32(4)))
}
function getTilesInView(a, e) {
    const i = getRectangleInView(a)
      , o = Math.floor(i.x / tile_width)
      , s = Math.floor((i.x + i.width - 1) / tile_width)
      , c = Math.floor(i.y / tile_height)
      , d = Math.floor((i.y + i.height - 1) / tile_height);
    console.log({
        left: o,
        right: s,
        top: c,
        bottom: d
    });
    const b = []
      , k = panorama_height / tile_height;
    for (let j = o; j <= s; j++)
        for (let$ = c; $ <= d; $++)
            b.push(j * k + $);
    return console.log(b),
    getMaskFromTiles(b, e),
    b
}
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(a) {
            return Object.prototype.toString.call(a) === "[object Array]"
        }
        ),
        ARRAY_BUFFER && (root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView) && (ArrayBuffer.isView = function(a) {
            return typeof a == "object" && a.buffer && a.buffer.constructor === ArrayBuffer
        }
        );
        var createOutputMethod = function(a) {
            return function(e, i) {
                return new Md5(!0).update(e, i)[a]()
            }
        }
          , createMethod = function() {
            var a = createOutputMethod("hex");
            NODE_JS && (a = nodeWrap(a)),
            a.getCtx = a.create = function() {
                return new Md5
            }
            ,
            a.update = function(o) {
                return a.create().update(o)
            }
            ;
            for (var e = 0; e < OUTPUT_TYPES.length; ++e) {
                var i = OUTPUT_TYPES[e];
                a[i] = createOutputMethod(i)
            }
            return a
        }
          , nodeWrap = function(method) {
            var crypto = eval("require('crypto')")
              , Buffer = eval("require('buffer').Buffer")
              , nodeMethod = function(a) {
                if (typeof a == "string")
                    return crypto.createHash("md5").update(a, "utf8").digest("hex");
                if (a == null)
                    throw ERROR;
                return a.constructor === ArrayBuffer && (a = new Uint8Array(a)),
                Array.isArray(a) || ArrayBuffer.isView(a) || a.constructor === Buffer ? crypto.createHash("md5").update(new Buffer(a)).digest("hex") : method(a)
            };
            return nodeMethod
        };
        function Md5(a) {
            if (a)
                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(a, e) {
            if (!this.finalized) {
                for (var i, o = 0, s, c = a.length, d = this.blocks, _ = this.buffer8; o < c; ) {
                    if (this.hashed && (this.hashed = !1,
                    d[0] = d[16],
                    d[16] = d[1] = d[2] = d[3] = d[4] = d[5] = d[6] = d[7] = d[8] = d[9] = d[10] = d[11] = d[12] = d[13] = d[14] = d[15] = 0),
                    ARRAY_BUFFER)
                        for (s = this.start; o < c && s < 64; ++o)
                            i = a.charCodeAt(o),
                            e || i < 128 ? _[s++] = i : i < 2048 ? (_[s++] = 192 | i >> 6,
                            _[s++] = 128 | i & 63) : i < 55296 || i >= 57344 ? (_[s++] = 224 | i >> 12,
                            _[s++] = 128 | i >> 6 & 63,
                            _[s++] = 128 | i & 63) : (i = 65536 + ((i & 1023) << 10 | a.charCodeAt(++o) & 1023),
                            _[s++] = 240 | i >> 18,
                            _[s++] = 128 | i >> 12 & 63,
                            _[s++] = 128 | i >> 6 & 63,
                            _[s++] = 128 | i & 63);
                    else
                        for (s = this.start; o < c && s < 64; ++o)
                            i = a.charCodeAt(o),
                            e || i < 128 ? d[s >> 2] |= i << SHIFT[s++ & 3] : i < 2048 ? (d[s >> 2] |= (192 | i >> 6) << SHIFT[s++ & 3],
                            d[s >> 2] |= (128 | i & 63) << SHIFT[s++ & 3]) : i < 55296 || i >= 57344 ? (d[s >> 2] |= (224 | i >> 12) << SHIFT[s++ & 3],
                            d[s >> 2] |= (128 | i >> 6 & 63) << SHIFT[s++ & 3],
                            d[s >> 2] |= (128 | i & 63) << SHIFT[s++ & 3]) : (i = 65536 + ((i & 1023) << 10 | a.charCodeAt(++o) & 1023),
                            d[s >> 2] |= (240 | i >> 18) << SHIFT[s++ & 3],
                            d[s >> 2] |= (128 | i >> 12 & 63) << SHIFT[s++ & 3],
                            d[s >> 2] |= (128 | i >> 6 & 63) << SHIFT[s++ & 3],
                            d[s >> 2] |= (128 | i & 63) << SHIFT[s++ & 3]);
                    this.lastByteIndex = s,
                    this.bytes += s - this.start,
                    s >= 64 ? (this.start = s - 64,
                    this.hash(),
                    this.hashed = !0) : this.start = s
                }
                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 a = this.blocks
                  , e = this.lastByteIndex;
                a[e >> 2] |= EXTRA[e & 3],
                e >= 56 && (this.hashed || this.hash(),
                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),
                a[14] = this.bytes << 3,
                a[15] = this.hBytes << 3 | this.bytes >>> 29,
                this.hash()
            }
        }
        ,
        Md5.prototype.hash = function() {
            var a, e, i, o, s, c, d = this.blocks;
            this.first ? (a = d[0] - 680876937,
            a = (a << 7 | a >>> 25) - 271733879 << 0,
            o = (-1732584194 ^ a & 2004318071) + d[1] - 117830708,
            o = (o << 12 | o >>> 20) + a << 0,
            i = (-271733879 ^ o & (a ^ -271733879)) + d[2] - 1126478375,
            i = (i << 17 | i >>> 15) + o << 0,
            e = (a ^ i & (o ^ a)) + d[3] - 1316259209,
            e = (e << 22 | e >>> 10) + i << 0) : (a = this.h0,
            e = this.h1,
            i = this.h2,
            o = this.h3,
            a += (o ^ e & (i ^ o)) + d[0] - 680876936,
            a = (a << 7 | a >>> 25) + e << 0,
            o += (i ^ a & (e ^ i)) + d[1] - 389564586,
            o = (o << 12 | o >>> 20) + a << 0,
            i += (e ^ o & (a ^ e)) + d[2] + 606105819,
            i = (i << 17 | i >>> 15) + o << 0,
            e += (a ^ i & (o ^ a)) + d[3] - 1044525330,
            e = (e << 22 | e >>> 10) + i << 0),
            a += (o ^ e & (i ^ o)) + d[4] - 176418897,
            a = (a << 7 | a >>> 25) + e << 0,
            o += (i ^ a & (e ^ i)) + d[5] + 1200080426,
            o = (o << 12 | o >>> 20) + a << 0,
            i += (e ^ o & (a ^ e)) + d[6] - 1473231341,
            i = (i << 17 | i >>> 15) + o << 0,
            e += (a ^ i & (o ^ a)) + d[7] - 45705983,
            e = (e << 22 | e >>> 10) + i << 0,
            a += (o ^ e & (i ^ o)) + d[8] + 1770035416,
            a = (a << 7 | a >>> 25) + e << 0,
            o += (i ^ a & (e ^ i)) + d[9] - 1958414417,
            o = (o << 12 | o >>> 20) + a << 0,
            i += (e ^ o & (a ^ e)) + d[10] - 42063,
            i = (i << 17 | i >>> 15) + o << 0,
            e += (a ^ i & (o ^ a)) + d[11] - 1990404162,
            e = (e << 22 | e >>> 10) + i << 0,
            a += (o ^ e & (i ^ o)) + d[12] + 1804603682,
            a = (a << 7 | a >>> 25) + e << 0,
            o += (i ^ a & (e ^ i)) + d[13] - 40341101,
            o = (o << 12 | o >>> 20) + a << 0,
            i += (e ^ o & (a ^ e)) + d[14] - 1502002290,
            i = (i << 17 | i >>> 15) + o << 0,
            e += (a ^ i & (o ^ a)) + d[15] + 1236535329,
            e = (e << 22 | e >>> 10) + i << 0,
            a += (i ^ o & (e ^ i)) + d[1] - 165796510,
            a = (a << 5 | a >>> 27) + e << 0,
            o += (e ^ i & (a ^ e)) + d[6] - 1069501632,
            o = (o << 9 | o >>> 23) + a << 0,
            i += (a ^ e & (o ^ a)) + d[11] + 643717713,
            i = (i << 14 | i >>> 18) + o << 0,
            e += (o ^ a & (i ^ o)) + d[0] - 373897302,
            e = (e << 20 | e >>> 12) + i << 0,
            a += (i ^ o & (e ^ i)) + d[5] - 701558691,
            a = (a << 5 | a >>> 27) + e << 0,
            o += (e ^ i & (a ^ e)) + d[10] + 38016083,
            o = (o << 9 | o >>> 23) + a << 0,
            i += (a ^ e & (o ^ a)) + d[15] - 660478335,
            i = (i << 14 | i >>> 18) + o << 0,
            e += (o ^ a & (i ^ o)) + d[4] - 405537848,
            e = (e << 20 | e >>> 12) + i << 0,
            a += (i ^ o & (e ^ i)) + d[9] + 568446438,
            a = (a << 5 | a >>> 27) + e << 0,
            o += (e ^ i & (a ^ e)) + d[14] - 1019803690,
            o = (o << 9 | o >>> 23) + a << 0,
            i += (a ^ e & (o ^ a)) + d[3] - 187363961,
            i = (i << 14 | i >>> 18) + o << 0,
            e += (o ^ a & (i ^ o)) + d[8] + 1163531501,
            e = (e << 20 | e >>> 12) + i << 0,
            a += (i ^ o & (e ^ i)) + d[13] - 1444681467,
            a = (a << 5 | a >>> 27) + e << 0,
            o += (e ^ i & (a ^ e)) + d[2] - 51403784,
            o = (o << 9 | o >>> 23) + a << 0,
            i += (a ^ e & (o ^ a)) + d[7] + 1735328473,
            i = (i << 14 | i >>> 18) + o << 0,
            e += (o ^ a & (i ^ o)) + d[12] - 1926607734,
            e = (e << 20 | e >>> 12) + i << 0,
            s = e ^ i,
            a += (s ^ o) + d[5] - 378558,
            a = (a << 4 | a >>> 28) + e << 0,
            o += (s ^ a) + d[8] - 2022574463,
            o = (o << 11 | o >>> 21) + a << 0,
            c = o ^ a,
            i += (c ^ e) + d[11] + 1839030562,
            i = (i << 16 | i >>> 16) + o << 0,
            e += (c ^ i) + d[14] - 35309556,
            e = (e << 23 | e >>> 9) + i << 0,
            s = e ^ i,
            a += (s ^ o) + d[1] - 1530992060,
            a = (a << 4 | a >>> 28) + e << 0,
            o += (s ^ a) + d[4] + 1272893353,
            o = (o << 11 | o >>> 21) + a << 0,
            c = o ^ a,
            i += (c ^ e) + d[7] - 155497632,
            i = (i << 16 | i >>> 16) + o << 0,
            e += (c ^ i) + d[10] - 1094730640,
            e = (e << 23 | e >>> 9) + i << 0,
            s = e ^ i,
            a += (s ^ o) + d[13] + 681279174,
            a = (a << 4 | a >>> 28) + e << 0,
            o += (s ^ a) + d[0] - 358537222,
            o = (o << 11 | o >>> 21) + a << 0,
            c = o ^ a,
            i += (c ^ e) + d[3] - 722521979,
            i = (i << 16 | i >>> 16) + o << 0,
            e += (c ^ i) + d[6] + 76029189,
            e = (e << 23 | e >>> 9) + i << 0,
            s = e ^ i,
            a += (s ^ o) + d[9] - 640364487,
            a = (a << 4 | a >>> 28) + e << 0,
            o += (s ^ a) + d[12] - 421815835,
            o = (o << 11 | o >>> 21) + a << 0,
            c = o ^ a,
            i += (c ^ e) + d[15] + 530742520,
            i = (i << 16 | i >>> 16) + o << 0,
            e += (c ^ i) + d[2] - 995338651,
            e = (e << 23 | e >>> 9) + i << 0,
            a += (i ^ (e | ~o)) + d[0] - 198630844,
            a = (a << 6 | a >>> 26) + e << 0,
            o += (e ^ (a | ~i)) + d[7] + 1126891415,
            o = (o << 10 | o >>> 22) + a << 0,
            i += (a ^ (o | ~e)) + d[14] - 1416354905,
            i = (i << 15 | i >>> 17) + o << 0,
            e += (o ^ (i | ~a)) + d[5] - 57434055,
            e = (e << 21 | e >>> 11) + i << 0,
            a += (i ^ (e | ~o)) + d[12] + 1700485571,
            a = (a << 6 | a >>> 26) + e << 0,
            o += (e ^ (a | ~i)) + d[3] - 1894986606,
            o = (o << 10 | o >>> 22) + a << 0,
            i += (a ^ (o | ~e)) + d[10] - 1051523,
            i = (i << 15 | i >>> 17) + o << 0,
            e += (o ^ (i | ~a)) + d[1] - 2054922799,
            e = (e << 21 | e >>> 11) + i << 0,
            a += (i ^ (e | ~o)) + d[8] + 1873313359,
            a = (a << 6 | a >>> 26) + e << 0,
            o += (e ^ (a | ~i)) + d[15] - 30611744,
            o = (o << 10 | o >>> 22) + a << 0,
            i += (a ^ (o | ~e)) + d[6] - 1560198380,
            i = (i << 15 | i >>> 17) + o << 0,
            e += (o ^ (i | ~a)) + d[13] + 1309151649,
            e = (e << 21 | e >>> 11) + i << 0,
            a += (i ^ (e | ~o)) + d[4] - 145523070,
            a = (a << 6 | a >>> 26) + e << 0,
            o += (e ^ (a | ~i)) + d[11] - 1120210379,
            o = (o << 10 | o >>> 22) + a << 0,
            i += (a ^ (o | ~e)) + d[2] + 718787259,
            i = (i << 15 | i >>> 17) + o << 0,
            e += (o ^ (i | ~a)) + d[9] - 343485551,
            e = (e << 21 | e >>> 11) + i << 0,
            this.first ? (this.h0 = a + 1732584193 << 0,
            this.h1 = e - 271733879 << 0,
            this.h2 = i - 1732584194 << 0,
            this.h3 = o + 271733878 << 0,
            this.first = !1) : (this.h0 = this.h0 + a << 0,
            this.h1 = this.h1 + e << 0,
            this.h2 = this.h2 + i << 0,
            this.h3 = this.h3 + o << 0)
        }
        ,
        Md5.prototype.hex = function() {
            this.finalize();
            var a = this.h0
              , e = this.h1
              , i = this.h2
              , o = this.h3;
            return HEX_CHARS[a >> 4 & 15] + HEX_CHARS[a & 15] + HEX_CHARS[a >> 12 & 15] + HEX_CHARS[a >> 8 & 15] + HEX_CHARS[a >> 20 & 15] + HEX_CHARS[a >> 16 & 15] + HEX_CHARS[a >> 28 & 15] + HEX_CHARS[a >> 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[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[o >> 4 & 15] + HEX_CHARS[o & 15] + HEX_CHARS[o >> 12 & 15] + HEX_CHARS[o >> 8 & 15] + HEX_CHARS[o >> 20 & 15] + HEX_CHARS[o >> 16 & 15] + HEX_CHARS[o >> 28 & 15] + HEX_CHARS[o >> 24 & 15]
        }
        ,
        Md5.prototype.toString = Md5.prototype.hex,
        Md5.prototype.digest = function(a) {
            if (a === "hex")
                return this.hex();
            this.finalize();
            var e = this.h0
              , i = this.h1
              , o = this.h2
              , s = this.h3
              , c = [e & 255, e >> 8 & 255, e >> 16 & 255, e >> 24 & 255, i & 255, i >> 8 & 255, i >> 16 & 255, i >> 24 & 255, o & 255, o >> 8 & 255, o >> 16 & 255, o >> 24 & 255, s & 255, s >> 8 & 255, s >> 16 & 255, s >> 24 & 255];
            return c
        }
        ,
        Md5.prototype.array = Md5.prototype.digest,
        Md5.prototype.arrayBuffer = function() {
            this.finalize();
            var a = new ArrayBuffer(16)
              , e = new Uint32Array(a);
            return e[0] = this.h0,
            e[1] = this.h1,
            e[2] = this.h2,
            e[3] = this.h3,
            a
        }
        ,
        Md5.prototype.buffer = Md5.prototype.arrayBuffer,
        Md5.prototype.base64 = function() {
            for (var a, e, i, o = "", s = this.array(), c = 0; c < 15; )
                a = s[c++],
                e = s[c++],
                i = s[c++],
                o += BASE64_ENCODE_CHAR[a >>> 2] + BASE64_ENCODE_CHAR[(a << 4 | e >>> 4) & 63] + BASE64_ENCODE_CHAR[(e << 2 | i >>> 6) & 63] + BASE64_ENCODE_CHAR[i & 63];
            return a = s[c],
            o += BASE64_ENCODE_CHAR[a >>> 2] + BASE64_ENCODE_CHAR[a << 4 & 63] + "==",
            o
        }
        ;
        var exports = createMethod();
        COMMON_JS ? module.exports = exports : root.md5 = exports
    }
    )()
}
)(md5$1);
var crypto = {
    exports: {}
};
(function(a) {
    var e = e || function(i, o) {
        var s = {}
          , c = s.lib = {}
          , d = function() {}
          , _ = c.Base = {
            extend: function(rt) {
                d.prototype = this;
                var it = new d;
                return rt && it.mixIn(rt),
                it.hasOwnProperty("init") || (it.init = function() {
                    it.$super.init.apply(this, arguments)
                }
                ),
                it.init.prototype = it,
                it.$super = this,
                it
            },
            create: function() {
                var rt = this.extend();
                return rt.init.apply(rt, arguments),
                rt
            },
            init: function() {},
            mixIn: function(rt) {
                for (var it in rt)
                    rt.hasOwnProperty(it) && (this[it] = rt[it]);
                rt.hasOwnProperty("toString") && (this.toString = rt.toString)
            },
            clone: function() {
                return this.init.prototype.extend(this)
            }
        }
          , b = c.WordArray = _.extend({
            init: function(rt, it) {
                rt = this.words = rt || [],
                this.sigBytes = it != o ? it : 4 * rt.length
            },
            toString: function(rt) {
                return (rt || j).stringify(this)
            },
            concat: function(rt) {
                var it = this.words
                  , nt = rt.words
                  , ot = this.sigBytes;
                if (rt = rt.sigBytes,
                this.clamp(),
                ot % 4)
                    for (var at = 0; at < rt; at++)
                        it[ot + at >>> 2] |= (nt[at >>> 2] >>> 24 - 8 * (at % 4) & 255) << 24 - 8 * ((ot + at) % 4);
                else if (65535 < nt.length)
                    for (at = 0; at < rt; at += 4)
                        it[ot + at >>> 2] = nt[at >>> 2];
                else
                    it.push.apply(it, nt);
                return this.sigBytes += rt,
                this
            },
            clamp: function() {
                var rt = this.words
                  , it = this.sigBytes;
                rt[it >>> 2] &= 4294967295 << 32 - 8 * (it % 4),
                rt.length = i.ceil(it / 4)
            },
            clone: function() {
                var rt = _.clone.call(this);
                return rt.words = this.words.slice(0),
                rt
            },
            random: function(rt) {
                for (var it = [], nt = 0; nt < rt; nt += 4)
                    it.push(4294967296 * i.random() | 0);
                return new b.init(it,rt)
            }
        })
          , k = s.enc = {}
          , j = k.Hex = {
            stringify: function(rt) {
                var it = rt.words;
                rt = rt.sigBytes;
                for (var nt = [], ot = 0; ot < rt; ot++) {
                    var at = it[ot >>> 2] >>> 24 - 8 * (ot % 4) & 255;
                    nt.push((at >>> 4).toString(16)),
                    nt.push((at & 15).toString(16))
                }
                return nt.join("")
            },
            parse: function(rt) {
                for (var it = rt.length, nt = [], ot = 0; ot < it; ot += 2)
                    nt[ot >>> 3] |= parseInt(rt.substr(ot, 2), 16) << 24 - 4 * (ot % 8);
                return new b.init(nt,it / 2)
            }
        }
          , $ = k.Latin1 = {
            stringify: function(rt) {
                var it = rt.words;
                rt = rt.sigBytes;
                for (var nt = [], ot = 0; ot < rt; ot++)
                    nt.push(String.fromCharCode(it[ot >>> 2] >>> 24 - 8 * (ot % 4) & 255));
                return nt.join("")
            },
            parse: function(rt) {
                for (var it = rt.length, nt = [], ot = 0; ot < it; ot++)
                    nt[ot >>> 2] |= (rt.charCodeAt(ot) & 255) << 24 - 8 * (ot % 4);
                return new b.init(nt,it)
            }
        }
          , _e = k.Utf8 = {
            stringify: function(rt) {
                try {
                    return decodeURIComponent(escape($.stringify(rt)))
                } catch {
                    throw Error("Malformed UTF-8 data")
                }
            },
            parse: function(rt) {
                return $.parse(unescape(encodeURIComponent(rt)))
            }
        }
          , et = c.BufferedBlockAlgorithm = _.extend({
            reset: function() {
                this._data = new b.init,
                this._nDataBytes = 0
            },
            _append: function(rt) {
                typeof rt == "string" && (rt = _e.parse(rt)),
                this._data.concat(rt),
                this._nDataBytes += rt.sigBytes
            },
            _process: function(rt) {
                var it = this._data
                  , nt = it.words
                  , ot = it.sigBytes
                  , at = this.blockSize
                  , st = ot / (4 * at)
                  , st = rt ? i.ceil(st) : i.max((st | 0) - this._minBufferSize, 0);
                if (rt = st * at,
                ot = i.min(4 * rt, ot),
                rt) {
                    for (var ut = 0; ut < rt; ut += at)
                        this._doProcessBlock(nt, ut);
                    ut = nt.splice(0, rt),
                    it.sigBytes -= ot
                }
                return new b.init(ut,ot)
            },
            clone: function() {
                var rt = _.clone.call(this);
                return rt._data = this._data.clone(),
                rt
            },
            _minBufferSize: 0
        });
        c.Hasher = et.extend({
            cfg: _.extend(),
            init: function(rt) {
                this.cfg = this.cfg.extend(rt),
                this.reset()
            },
            reset: function() {
                et.reset.call(this),
                this._doReset()
            },
            update: function(rt) {
                return this._append(rt),
                this._process(),
                this
            },
            finalize: function(rt) {
                return rt && this._append(rt),
                this._doFinalize()
            },
            blockSize: 16,
            _createHelper: function(rt) {
                return function(it, nt) {
                    return new rt.init(nt).finalize(it)
                }
            },
            _createHmacHelper: function(rt) {
                return function(it, nt) {
                    return new tt.HMAC.init(rt,nt).finalize(it)
                }
            }
        });
        var tt = s.algo = {};
        return s
    }(Math);
    (function() {
        var i = e
          , d = i.lib
          , o = d.WordArray
          , s = d.Hasher
          , c = []
          , d = i.algo.SHA1 = s.extend({
            _doReset: function() {
                this._hash = new o.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520])
            },
            _doProcessBlock: function(_, b) {
                for (var k = this._hash.words, j = k[0], $ = k[1], _e = k[2], et = k[3], tt = k[4], rt = 0; 80 > rt; rt++) {
                    if (16 > rt)
                        c[rt] = _[b + rt] | 0;
                    else {
                        var it = c[rt - 3] ^ c[rt - 8] ^ c[rt - 14] ^ c[rt - 16];
                        c[rt] = it << 1 | it >>> 31
                    }
                    it = (j << 5 | j >>> 27) + tt + c[rt],
                    it = 20 > rt ? it + (($ & _e | ~$ & et) + 1518500249) : 40 > rt ? it + (($ ^ _e ^ et) + 1859775393) : 60 > rt ? it + (($ & _e | $ & et | _e & et) - 1894007588) : it + (($ ^ _e ^ et) - 899497514),
                    tt = et,
                    et = _e,
                    _e = $ << 30 | $ >>> 2,
                    $ = j,
                    j = it
                }
                k[0] = k[0] + j | 0,
                k[1] = k[1] + $ | 0,
                k[2] = k[2] + _e | 0,
                k[3] = k[3] + et | 0,
                k[4] = k[4] + tt | 0
            },
            _doFinalize: function() {
                var _ = this._data
                  , b = _.words
                  , k = 8 * this._nDataBytes
                  , j = 8 * _.sigBytes;
                return b[j >>> 5] |= 128 << 24 - j % 32,
                b[(j + 64 >>> 9 << 4) + 14] = Math.floor(k / 4294967296),
                b[(j + 64 >>> 9 << 4) + 15] = k,
                _.sigBytes = 4 * b.length,
                this._process(),
                this._hash
            },
            clone: function() {
                var _ = s.clone.call(this);
                return _._hash = this._hash.clone(),
                _
            }
        });
        i.SHA1 = s._createHelper(d),
        i.HmacSHA1 = s._createHmacHelper(d)
    }
    )(),
    function() {
        var i = e
          , o = i.enc.Utf8;
        i.algo.HMAC = i.lib.Base.extend({
            init: function(s, c) {
                s = this._hasher = new s.init,
                typeof c == "string" && (c = o.parse(c));
                var d = s.blockSize
                  , _ = 4 * d;
                c.sigBytes > _ && (c = s.finalize(c)),
                c.clamp();
                for (var b = this._oKey = c.clone(), k = this._iKey = c.clone(), j = b.words, $ = k.words, _e = 0; _e < d; _e++)
                    j[_e] ^= 1549556828,
                    $[_e] ^= 909522486;
                b.sigBytes = k.sigBytes = _,
                this.reset()
            },
            reset: function() {
                var s = this._hasher;
                s.reset(),
                s.update(this._iKey)
            },
            update: function(s) {
                return this._hasher.update(s),
                this
            },
            finalize: function(s) {
                var c = this._hasher;
                return s = c.finalize(s),
                c.reset(),
                c.finalize(this._oKey.clone().concat(s))
            }
        })
    }(),
    function() {
        var i = e
          , o = i.lib
          , s = o.WordArray
          , c = i.enc;
        c.Base64 = {
            stringify: function(d) {
                var _ = d.words
                  , b = d.sigBytes
                  , k = this._map;
                d.clamp();
                for (var j = [], $ = 0; $ < b; $ += 3)
                    for (var _e = _[$ >>> 2] >>> 24 - $ % 4 * 8 & 255, et = _[$ + 1 >>> 2] >>> 24 - ($ + 1) % 4 * 8 & 255, tt = _[$ + 2 >>> 2] >>> 24 - ($ + 2) % 4 * 8 & 255, rt = _e << 16 | et << 8 | tt, it = 0; it < 4 && $ + it * .75 < b; it++)
                        j.push(k.charAt(rt >>> 6 * (3 - it) & 63));
                var nt = k.charAt(64);
                if (nt)
                    for (; j.length % 4; )
                        j.push(nt);
                return j.join("")
            },
            parse: function(d) {
                var _ = d.length
                  , b = this._map
                  , k = b.charAt(64);
                if (k) {
                    var j = d.indexOf(k);
                    j != -1 && (_ = j)
                }
                for (var $ = [], _e = 0, et = 0; et < _; et++)
                    if (et % 4) {
                        var tt = b.indexOf(d.charAt(et - 1)) << et % 4 * 2
                          , rt = b.indexOf(d.charAt(et)) >>> 6 - et % 4 * 2;
                        $[_e >>> 2] |= (tt | rt) << 24 - _e % 4 * 8,
                        _e++
                    }
                return s.create($, _e)
            },
            _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        }
    }(),
    a.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(a, e, i) {
        var o = this.domBuilder;
        o.startDocument(),
        _copy(e, e = {}),
        parse(a, e, i, o, this.errorHandler),
        o.endDocument()
    }
};
function parse(a, e, i, o, s) {
    function c(Et) {
        if (Et > 65535) {
            Et -= 65536;
            var At = 55296 + (Et >> 10)
              , gt = 56320 + (Et & 1023);
            return String.fromCharCode(At, gt)
        } else
            return String.fromCharCode(Et)
    }
    function d(Et) {
        var At = Et.slice(1, -1);
        return At in i ? i[At] : At.charAt(0) === "#" ? c(parseInt(At.substr(1).replace("x", "0x"))) : (s.error("entity not found:" + Et),
        Et)
    }
    function _(Et) {
        if (Et > rt) {
            var At = a.substring(rt, Et).replace(/&#?\w+;/g, d);
            _e && b(rt),
            o.characters(At, 0, Et - rt),
            rt = Et
        }
    }
    function b(Et, At) {
        for (; Et >= j && (At = $.exec(a)); )
            k = At.index,
            j = k + At[0].length,
            _e.lineNumber++;
        _e.columnNumber = Et - k + 1
    }
    for (var k = 0, j = 0, $ = /.*(?:\r\n?|\n)|.*$/g, _e = o.locator, et = [{
        currentNSMap: e
    }], tt = {}, rt = 0; ; ) {
        try {
            var it = a.indexOf("<", rt);
            if (it < 0) {
                if (!a.substr(rt).match(/^\s*$/)) {
                    var nt = o.doc
                      , ot = nt.createTextNode(a.substr(rt));
                    nt.appendChild(ot),
                    o.currentElement = ot
                }
                return
            }
            switch (it > rt && _(it),
            a.charAt(it + 1)) {
            case "/":
                var dt = a.indexOf(">", it + 3)
                  , at = a.substring(it + 2, dt)
                  , st = et.pop();
                dt < 0 ? (at = a.substring(it + 2).replace(/[\s<].*/, ""),
                s.error("end tag name: " + at + " is not complete:" + st.tagName),
                dt = it + 1 + at.length) : at.match(/\s</) && (at = at.replace(/[\s<].*/, ""),
                s.error("end tag name: " + at + " maybe not complete"),
                dt = it + 1 + at.length);
                var ut = st.localNSMap
                  , ct = st.tagName == at
                  , lt = ct || st.tagName && st.tagName.toLowerCase() == at.toLowerCase();
                if (lt) {
                    if (o.endElement(st.uri, st.localName, at),
                    ut)
                        for (var ft in ut)
                            o.endPrefixMapping(ft);
                    ct || s.fatalError("end tag name: " + at + " is not match the current start tagName:" + st.tagName)
                } else
                    et.push(st);
                dt++;
                break;
            case "?":
                _e && b(it),
                dt = parseInstruction(a, it, o);
                break;
            case "!":
                _e && b(it),
                dt = parseDCC(a, it, o, s);
                break;
            default:
                _e && b(it);
                var ht = new ElementAttributes
                  , pt = et[et.length - 1].currentNSMap
                  , dt = parseElementStartPart(a, it, ht, pt, d, s)
                  , _t = ht.length;
                if (!ht.closed && fixSelfClosed(a, dt, ht.tagName, tt) && (ht.closed = !0,
                i.nbsp || s.warning("unclosed xml attribute")),
                _e && _t) {
                    for (var mt = copyLocator(_e, {}), vt = 0; vt < _t; vt++) {
                        var yt = ht[vt];
                        b(yt.offset),
                        yt.locator = copyLocator(_e, {})
                    }
                    o.locator = mt,
                    appendElement$1(ht, o, pt) && et.push(ht),
                    o.locator = _e
                } else
                    appendElement$1(ht, o, pt) && et.push(ht);
                ht.uri === "http://www.w3.org/1999/xhtml" && !ht.closed ? dt = parseHtmlSpecialContent(a, dt, ht.tagName, d, o) : dt++
            }
        } catch (Et) {
            s.error("element parse error: " + Et),
            dt = -1
        }
        dt > rt ? rt = dt : _(Math.max(it, rt) + 1)
    }
}
function copyLocator(a, e) {
    return e.lineNumber = a.lineNumber,
    e.columnNumber = a.columnNumber,
    e
}
function parseElementStartPart(a, e, i, o, s, c) {
    for (var d, _, b = ++e, k = S_TAG; ; ) {
        var j = a.charAt(b);
        switch (j) {
        case "=":
            if (k === S_ATTR)
                d = a.slice(e, b),
                k = S_EQ;
            else if (k === S_ATTR_SPACE)
                k = S_EQ;
            else
                throw new Error("attribute equal must after attrName");
            break;
        case "'":
        case '"':
            if (k === S_EQ || k === S_ATTR)
                if (k === S_ATTR && (c.warning('attribute value must after "="'),
                d = a.slice(e, b)),
                e = b + 1,
                b = a.indexOf(j, e),
                b > 0)
                    _ = a.slice(e, b).replace(/&#?\w+;/g, s),
                    i.add(d, _, e - 1),
                    k = S_ATTR_END;
                else
                    throw new Error("attribute value no end '" + j + "' match");
            else if (k == S_ATTR_NOQUOT_VALUE)
                _ = a.slice(e, b).replace(/&#?\w+;/g, s),
                i.add(d, _, e),
                c.warning('attribute "' + d + '" missed start quot(' + j + ")!!"),
                e = b + 1,
                k = S_ATTR_END;
            else
                throw new Error('attribute value must after "="');
            break;
        case "/":
            switch (k) {
            case S_TAG:
                i.setTagName(a.slice(e, b));
            case S_ATTR_END:
            case S_TAG_SPACE:
            case S_TAG_CLOSE:
                k = S_TAG_CLOSE,
                i.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 c.error("unexpected end of input"),
            k == S_TAG && i.setTagName(a.slice(e, b)),
            b;
        case ">":
            switch (k) {
            case S_TAG:
                i.setTagName(a.slice(e, b));
            case S_ATTR_END:
            case S_TAG_SPACE:
            case S_TAG_CLOSE:
                break;
            case S_ATTR_NOQUOT_VALUE:
            case S_ATTR:
                _ = a.slice(e, b),
                _.slice(-1) === "/" && (i.closed = !0,
                _ = _.slice(0, -1));
            case S_ATTR_SPACE:
                k === S_ATTR_SPACE && (_ = d),
                k == S_ATTR_NOQUOT_VALUE ? (c.warning('attribute "' + _ + '" missed quot(")!!'),
                i.add(d, _.replace(/&#?\w+;/g, s), e)) : ((o[""] !== "http://www.w3.org/1999/xhtml" || !_.match(/^(?:disabled|checked|selected)$/i)) && c.warning('attribute "' + _ + '" missed value!! "' + _ + '" instead!!'),
                i.add(_, _, e));
                break;
            case S_EQ:
                throw new Error("attribute value missed!!")
            }
            return b;
        case "\x80":
            j = " ";
        default:
            if (j <= " ")
                switch (k) {
                case S_TAG:
                    i.setTagName(a.slice(e, b)),
                    k = S_TAG_SPACE;
                    break;
                case S_ATTR:
                    d = a.slice(e, b),
                    k = S_ATTR_SPACE;
                    break;
                case S_ATTR_NOQUOT_VALUE:
                    var _ = a.slice(e, b).replace(/&#?\w+;/g, s);
                    c.warning('attribute "' + _ + '" missed quot(")!!'),
                    i.add(d, _, e);
                case S_ATTR_END:
                    k = S_TAG_SPACE;
                    break
                }
            else
                switch (k) {
                case S_ATTR_SPACE:
                    i.tagName,
                    (o[""] !== "http://www.w3.org/1999/xhtml" || !d.match(/^(?:disabled|checked|selected)$/i)) && c.warning('attribute "' + d + '" missed value!! "' + d + '" instead2!!'),
                    i.add(d, d, e),
                    e = b,
                    k = S_ATTR;
                    break;
                case S_ATTR_END:
                    c.warning('attribute space is required"' + d + '"!!');
                case S_TAG_SPACE:
                    k = S_ATTR,
                    e = b;
                    break;
                case S_EQ:
                    k = S_ATTR_NOQUOT_VALUE,
                    e = b;
                    break;
                case S_TAG_CLOSE:
                    throw new Error("elements closed character '/' and '>' must be connected to")
                }
        }
        b++
    }
}
function appendElement$1(a, e, i) {
    for (var o = a.tagName, s = null, $ = a.length; $--; ) {
        var c = a[$]
          , d = c.qName
          , _ = c.value
          , _e = d.indexOf(":");
        if (_e > 0)
            var b = c.prefix = d.slice(0, _e)
              , k = d.slice(_e + 1)
              , j = b === "xmlns" && k;
        else
            k = d,
            b = null,
            j = d === "xmlns" && "";
        c.localName = k,
        j !== !1 && (s == null && (s = {},
        _copy(i, i = {})),
        i[j] = s[j] = _,
        c.uri = "http://www.w3.org/2000/xmlns/",
        e.startPrefixMapping(j, _))
    }
    for (var $ = a.length; $--; ) {
        c = a[$];
        var b = c.prefix;
        b && (b === "xml" && (c.uri = "http://www.w3.org/XML/1998/namespace"),
        b !== "xmlns" && (c.uri = i[b || ""]))
    }
    var _e = o.indexOf(":");
    _e > 0 ? (b = a.prefix = o.slice(0, _e),
    k = a.localName = o.slice(_e + 1)) : (b = null,
    k = a.localName = o);
    var et = a.uri = i[b || ""];
    if (e.startElement(et, k, o, a),
    a.closed) {
        if (e.endElement(et, k, o),
        s)
            for (b in s)
                e.endPrefixMapping(b)
    } else
        return a.currentNSMap = i,
        a.localNSMap = s,
        !0
}
function parseHtmlSpecialContent(a, e, i, o, s) {
    if (/^(?:script|textarea)$/i.test(i)) {
        var c = a.indexOf("</" + i + ">", e)
          , d = a.substring(e + 1, c);
        if (/[&<]/.test(d))
            return /^script$/i.test(i) ? (s.characters(d, 0, d.length),
            c) : (d = d.replace(/&#?\w+;/g, o),
            s.characters(d, 0, d.length),
            c)
    }
    return e + 1
}
function fixSelfClosed(a, e, i, o) {
    var s = o[i];
    return s == null && (s = a.lastIndexOf("</" + i + ">"),
    s < e && (s = a.lastIndexOf("</" + i)),
    o[i] = s),
    s < e
}
function _copy(a, e) {
    for (var i in a)
        e[i] = a[i]
}
function parseDCC(a, e, i, o) {
    var s = a.charAt(e + 2);
    switch (s) {
    case "-":
        if (a.charAt(e + 3) === "-") {
            var c = a.indexOf("-->", e + 4);
            return c > e ? (i.comment(a, e + 4, c - e - 4),
            c + 3) : (o.error("Unclosed comment"),
            -1)
        } else
            return -1;
    default:
        if (a.substr(e + 3, 6) == "CDATA[") {
            var c = a.indexOf("]]>", e + 9);
            return i.startCDATA(),
            i.characters(a, e + 9, c - e - 9),
            i.endCDATA(),
            c + 3
        }
        var d = split(a, e)
          , _ = d.length;
        if (_ > 1 && /!doctype/i.test(d[0][0])) {
            var b = d[1][0]
              , k = _ > 3 && /^public$/i.test(d[2][0]) && d[3][0]
              , j = _ > 4 && d[4][0]
              , $ = d[_ - 1];
            return i.startDTD(b, k && k.replace(/^(['"])(.*?)\1$/, "$2"), j && j.replace(/^(['"])(.*?)\1$/, "$2")),
            i.endDTD(),
            $.index + $[0].length
        }
    }
    return -1
}
function parseInstruction(a, e, i) {
    var o = a.indexOf("?>", e);
    if (o) {
        var s = a.substring(e, o).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
        return s ? (s[0].length,
        i.processingInstruction(s[1], s[2]),
        o + 2) : -1
    }
    return -1
}
function ElementAttributes(a) {}
ElementAttributes.prototype = {
    setTagName: function(a) {
        if (!tagNamePattern.test(a))
            throw new Error("invalid tagName:" + a);
        this.tagName = a
    },
    add: function(a, e, i) {
        if (!tagNamePattern.test(a))
            throw new Error("invalid attribute:" + a);
        this[this.length++] = {
            qName: a,
            value: e,
            offset: i
        }
    },
    length: 0,
    getLocalName: function(a) {
        return this[a].localName
    },
    getLocator: function(a) {
        return this[a].locator
    },
    getQName: function(a) {
        return this[a].qName
    },
    getURI: function(a) {
        return this[a].uri
    },
    getValue: function(a) {
        return this[a].value
    }
};
function _set_proto_(a, e) {
    return a.__proto__ = e,
    a
}
_set_proto_({}, _set_proto_.prototype)instanceof _set_proto_ || (_set_proto_ = function(a, e) {
    function i() {}
    i.prototype = e,
    i = new i;
    for (e in a)
        i[e] = a[e];
    return i
}
);
function split(a, e) {
    var i, o = [], s = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
    for (s.lastIndex = e,
    s.exec(a); i = s.exec(a); )
        if (o.push(i),
        i[1])
            return o
}
sax.XMLReader = XMLReader$1;
var dom = {};
function copy(a, e) {
    for (var i in a)
        e[i] = a[i]
}
function _extends(a, e) {
    var i = a.prototype;
    if (Object.create) {
        var o = Object.create(e.prototype);
        i.__proto__ = o
    }
    if (!(i instanceof e)) {
        let c = function() {};
        var s = c;
        c.prototype = e.prototype,
        c = new c,
        copy(i, c),
        a.prototype = i = c
    }
    i.constructor != a && (typeof a != "function" && console.error("unknow Class:" + a),
    i.constructor = a)
}
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$1(a, e) {
    if (e instanceof Error)
        var i = e;
    else
        i = this,
        Error.call(this, ExceptionMessage[a]),
        this.message = ExceptionMessage[a],
        Error.captureStackTrace && Error.captureStackTrace(this, DOMException$1);
    return i.code = a,
    e && (this.message = this.message + ": " + e),
    i
}
DOMException$1.prototype = Error.prototype;
copy(ExceptionCode, DOMException$1);
function NodeList() {}
NodeList.prototype = {
    length: 0,
    item: function(a) {
        return this[a] || null
    },
    toString: function(a, e) {
        for (var i = [], o = 0; o < this.length; o++)
            serializeToString(this[o], i, a, e);
        return i.join("")
    }
};
function LiveNodeList(a, e) {
    this._node = a,
    this._refresh = e,
    _updateLiveList(this)
}
function _updateLiveList(a) {
    var e = a._node._inc || a._node.ownerDocument._inc;
    if (a._inc != e) {
        var i = a._refresh(a._node);
        __set__(a, "length", i.length),
        copy(i, a),
        a._inc = e
    }
}
LiveNodeList.prototype.item = function(a) {
    return _updateLiveList(this),
    this[a]
}
;
_extends(LiveNodeList, NodeList);
function NamedNodeMap() {}
function _findNodeIndex(a, e) {
    for (var i = a.length; i--; )
        if (a[i] === e)
            return i
}
function _addNamedNode(a, e, i, o) {
    if (o ? e[_findNodeIndex(e, o)] = i : e[e.length++] = i,
    a) {
        i.ownerElement = a;
        var s = a.ownerDocument;
        s && (o && _onRemoveAttribute(s, a, o),
        _onAddAttribute(s, a, i))
    }
}
function _removeNamedNode(a, e, i) {
    var o = _findNodeIndex(e, i);
    if (o >= 0) {
        for (var s = e.length - 1; o < s; )
            e[o] = e[++o];
        if (e.length = s,
        a) {
            var c = a.ownerDocument;
            c && (_onRemoveAttribute(c, a, i),
            i.ownerElement = null)
        }
    } else
        throw DOMException$1(NOT_FOUND_ERR, new Error(a.tagName + "@" + i))
}
NamedNodeMap.prototype = {
    length: 0,
    item: NodeList.prototype.item,
    getNamedItem: function(a) {
        for (var e = this.length; e--; ) {
            var i = this[e];
            if (i.nodeName == a)
                return i
        }
    },
    setNamedItem: function(a) {
        var e = a.ownerElement;
        if (e && e != this._ownerElement)
            throw new DOMException$1(INUSE_ATTRIBUTE_ERR);
        var i = this.getNamedItem(a.nodeName);
        return _addNamedNode(this._ownerElement, this, a, i),
        i
    },
    setNamedItemNS: function(a) {
        var e = a.ownerElement, i;
        if (e && e != this._ownerElement)
            throw new DOMException$1(INUSE_ATTRIBUTE_ERR);
        return i = this.getNamedItemNS(a.namespaceURI, a.localName),
        _addNamedNode(this._ownerElement, this, a, i),
        i
    },
    removeNamedItem: function(a) {
        var e = this.getNamedItem(a);
        return _removeNamedNode(this._ownerElement, this, e),
        e
    },
    removeNamedItemNS: function(a, e) {
        var i = this.getNamedItemNS(a, e);
        return _removeNamedNode(this._ownerElement, this, i),
        i
    },
    getNamedItemNS: function(a, e) {
        for (var i = this.length; i--; ) {
            var o = this[i];
            if (o.localName == e && o.namespaceURI == a)
                return o
        }
        return null
    }
};
function DOMImplementation$1(a) {
    if (this._features = {},
    a)
        for (var e in a)
            this._features = a[e]
}
DOMImplementation$1.prototype = {
    hasFeature: function(a, e) {
        var i = this._features[a.toLowerCase()];
        return !!(i && (!e || e in i))
    },
    createDocument: function(a, e, i) {
        var o = new Document;
        if (o.implementation = this,
        o.childNodes = new NodeList,
        o.doctype = i,
        i && o.appendChild(i),
        e) {
            var s = o.createElementNS(a, e);
            o.appendChild(s)
        }
        return o
    },
    createDocumentType: function(a, e, i) {
        var o = new DocumentType;
        return o.name = a,
        o.nodeName = a,
        o.publicId = e,
        o.systemId = i,
        o
    }
};
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(a, e) {
        return _insertBefore(this, a, e)
    },
    replaceChild: function(a, e) {
        this.insertBefore(a, e),
        e && this.removeChild(e)
    },
    removeChild: function(a) {
        return _removeChild(this, a)
    },
    appendChild: function(a) {
        return this.insertBefore(a, null)
    },
    hasChildNodes: function() {
        return this.firstChild != null
    },
    cloneNode: function(a) {
        return cloneNode(this.ownerDocument || this, this, a)
    },
    normalize: function() {
        for (var a = this.firstChild; a; ) {
            var e = a.nextSibling;
            e && e.nodeType == TEXT_NODE && a.nodeType == TEXT_NODE ? (this.removeChild(e),
            a.appendData(e.data)) : (a.normalize(),
            a = e)
        }
    },
    isSupported: function(a, e) {
        return this.ownerDocument.implementation.hasFeature(a, e)
    },
    hasAttributes: function() {
        return this.attributes.length > 0
    },
    lookupPrefix: function(a) {
        for (var e = this; e; ) {
            var i = e._nsMap;
            if (i) {
                for (var o in i)
                    if (i[o] == a)
                        return o
            }
            e = e.nodeType == ATTRIBUTE_NODE ? e.ownerDocument : e.parentNode
        }
        return null
    },
    lookupNamespaceURI: function(a) {
        for (var e = this; e; ) {
            var i = e._nsMap;
            if (i && a in i)
                return i[a];
            e = e.nodeType == ATTRIBUTE_NODE ? e.ownerDocument : e.parentNode
        }
        return null
    },
    isDefaultNamespace: function(a) {
        var e = this.lookupPrefix(a);
        return e == null
    }
};
function _xmlEncoder(a) {
    return a == "<" && "&lt;" || a == ">" && "&gt;" || a == "&" && "&amp;" || a == '"' && "&quot;" || "&#" + a.charCodeAt() + ";"
}
copy(NodeType, Node$1);
copy(NodeType, Node$1.prototype);
function _visitNode(a, e) {
    if (e(a))
        return !0;
    if (a = a.firstChild)
        do
            if (_visitNode(a, e))
                return !0;
        while (a = a.nextSibling)
}
function Document() {}
function _onAddAttribute(a, e, i) {
    a && a._inc++;
    var o = i.namespaceURI;
    o == "http://www.w3.org/2000/xmlns/" && (e._nsMap[i.prefix ? i.localName : ""] = i.value)
}
function _onRemoveAttribute(a, e, i, o) {
    a && a._inc++;
    var s = i.namespaceURI;
    s == "http://www.w3.org/2000/xmlns/" && delete e._nsMap[i.prefix ? i.localName : ""]
}
function _onUpdateChild(a, e, i) {
    if (a && a._inc) {
        a._inc++;
        var o = e.childNodes;
        if (i)
            o[o.length++] = i;
        else {
            for (var s = e.firstChild, c = 0; s; )
                o[c++] = s,
                s = s.nextSibling;
            o.length = c
        }
    }
}
function _removeChild(a, e) {
    var i = e.previousSibling
      , o = e.nextSibling;
    return i ? i.nextSibling = o : a.firstChild = o,
    o ? o.previousSibling = i : a.lastChild = i,
    _onUpdateChild(a.ownerDocument, a),
    e
}
function _insertBefore(a, e, i) {
    var o = e.parentNode;
    if (o && o.removeChild(e),
    e.nodeType === DOCUMENT_FRAGMENT_NODE) {
        var s = e.firstChild;
        if (s == null)
            return e;
        var c = e.lastChild
    } else
        s = c = e;
    var d = i ? i.previousSibling : a.lastChild;
    s.previousSibling = d,
    c.nextSibling = i,
    d ? d.nextSibling = s : a.firstChild = s,
    i == null ? a.lastChild = c : i.previousSibling = c;
    do
        s.parentNode = a;
    while (s !== c && (s = s.nextSibling));
    return _onUpdateChild(a.ownerDocument || a, a),
    e.nodeType == DOCUMENT_FRAGMENT_NODE && (e.firstChild = e.lastChild = null),
    e
}
function _appendSingleChild(a, e) {
    var i = e.parentNode;
    if (i) {
        var o = a.lastChild;
        i.removeChild(e);
        var o = a.lastChild
    }
    var o = a.lastChild;
    return e.parentNode = a,
    e.previousSibling = o,
    e.nextSibling = null,
    o ? o.nextSibling = e : a.firstChild = e,
    a.lastChild = e,
    _onUpdateChild(a.ownerDocument, a, e),
    e
}
Document.prototype = {
    nodeName: "#document",
    nodeType: DOCUMENT_NODE,
    doctype: null,
    documentElement: null,
    _inc: 1,
    insertBefore: function(a, e) {
        if (a.nodeType == DOCUMENT_FRAGMENT_NODE) {
            for (var i = a.firstChild; i; ) {
                var o = i.nextSibling;
                this.insertBefore(i, e),
                i = o
            }
            return a
        }
        return this.documentElement == null && a.nodeType == ELEMENT_NODE && (this.documentElement = a),
        _insertBefore(this, a, e),
        a.ownerDocument = this,
        a
    },
    removeChild: function(a) {
        return this.documentElement == a && (this.documentElement = null),
        _removeChild(this, a)
    },
    importNode: function(a, e) {
        return importNode(this, a, e)
    },
    getElementById: function(a) {
        var e = null;
        return _visitNode(this.documentElement, function(i) {
            if (i.nodeType == ELEMENT_NODE && i.getAttribute("id") == a)
                return e = i,
                !0
        }),
        e
    },
    createElement: function(a) {
        var e = new Element;
        e.ownerDocument = this,
        e.nodeName = a,
        e.tagName = a,
        e.childNodes = new NodeList;
        var i = e.attributes = new NamedNodeMap;
        return i._ownerElement = e,
        e
    },
    createDocumentFragment: function() {
        var a = new DocumentFragment;
        return a.ownerDocument = this,
        a.childNodes = new NodeList,
        a
    },
    createTextNode: function(a) {
        var e = new Text;
        return e.ownerDocument = this,
        e.appendData(a),
        e
    },
    createComment: function(a) {
        var e = new Comment;
        return e.ownerDocument = this,
        e.appendData(a),
        e
    },
    createCDATASection: function(a) {
        var e = new CDATASection;
        return e.ownerDocument = this,
        e.appendData(a),
        e
    },
    createProcessingInstruction: function(a, e) {
        var i = new ProcessingInstruction;
        return i.ownerDocument = this,
        i.tagName = i.target = a,
        i.nodeValue = i.data = e,
        i
    },
    createAttribute: function(a) {
        var e = new Attr;
        return e.ownerDocument = this,
        e.name = a,
        e.nodeName = a,
        e.localName = a,
        e.specified = !0,
        e
    },
    createEntityReference: function(a) {
        var e = new EntityReference;
        return e.ownerDocument = this,
        e.nodeName = a,
        e
    },
    createElementNS: function(a, e) {
        var i = new Element
          , o = e.split(":")
          , s = i.attributes = new NamedNodeMap;
        return i.childNodes = new NodeList,
        i.ownerDocument = this,
        i.nodeName = e,
        i.tagName = e,
        i.namespaceURI = a,
        o.length == 2 ? (i.prefix = o[0],
        i.localName = o[1]) : i.localName = e,
        s._ownerElement = i,
        i
    },
    createAttributeNS: function(a, e) {
        var i = new Attr
          , o = e.split(":");
        return i.ownerDocument = this,
        i.nodeName = e,
        i.name = e,
        i.namespaceURI = a,
        i.specified = !0,
        o.length == 2 ? (i.prefix = o[0],
        i.localName = o[1]) : i.localName = e,
        i
    }
};
_extends(Document, Node$1);
function Element() {
    this._nsMap = {}
}
Element.prototype = {
    nodeType: ELEMENT_NODE,
    hasAttribute: function(a) {
        return this.getAttributeNode(a) != null
    },
    getAttribute: function(a) {
        var e = this.getAttributeNode(a);
        return e && e.value || ""
    },
    getAttributeNode: function(a) {
        return this.attributes.getNamedItem(a)
    },
    setAttribute: function(a, e) {
        var i = this.ownerDocument.createAttribute(a);
        i.value = i.nodeValue = "" + e,
        this.setAttributeNode(i)
    },
    removeAttribute: function(a) {
        var e = this.getAttributeNode(a);
        e && this.removeAttributeNode(e)
    },
    appendChild: function(a) {
        return a.nodeType === DOCUMENT_FRAGMENT_NODE ? this.insertBefore(a, null) : _appendSingleChild(this, a)
    },
    setAttributeNode: function(a) {
        return this.attributes.setNamedItem(a)
    },
    setAttributeNodeNS: function(a) {
        return this.attributes.setNamedItemNS(a)
    },
    removeAttributeNode: function(a) {
        return this.attributes.removeNamedItem(a.nodeName)
    },
    removeAttributeNS: function(a, e) {
        var i = this.getAttributeNodeNS(a, e);
        i && this.removeAttributeNode(i)
    },
    hasAttributeNS: function(a, e) {
        return this.getAttributeNodeNS(a, e) != null
    },
    getAttributeNS: function(a, e) {
        var i = this.getAttributeNodeNS(a, e);
        return i && i.value || ""
    },
    setAttributeNS: function(a, e, i) {
        var o = this.ownerDocument.createAttributeNS(a, e);
        o.value = o.nodeValue = "" + i,
        this.setAttributeNode(o)
    },
    getAttributeNodeNS: function(a, e) {
        return this.attributes.getNamedItemNS(a, e)
    },
    getElementsByTagName: function(a) {
        return new LiveNodeList(this,function(e) {
            var i = [];
            return _visitNode(e, function(o) {
                o !== e && o.nodeType == ELEMENT_NODE && (a === "*" || o.tagName == a) && i.push(o)
            }),
            i
        }
        )
    },
    getElementsByTagNameNS: function(a, e) {
        return new LiveNodeList(this,function(i) {
            var o = [];
            return _visitNode(i, function(s) {
                s !== i && s.nodeType === ELEMENT_NODE && (a === "*" || s.namespaceURI === a) && (e === "*" || s.localName == e) && o.push(s)
            }),
            o
        }
        )
    }
};
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(a, e) {
        return this.data.substring(a, a + e)
    },
    appendData: function(a) {
        a = this.data + a,
        this.nodeValue = this.data = a,
        this.length = a.length
    },
    insertData: function(a, e) {
        this.replaceData(a, 0, e)
    },
    appendChild: function(a) {
        throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
    },
    deleteData: function(a, e) {
        this.replaceData(a, e, "")
    },
    replaceData: function(a, e, i) {
        var o = this.data.substring(0, a)
          , s = this.data.substring(a + e);
        i = o + i + s,
        this.nodeValue = this.data = i,
        this.length = i.length
    }
};
_extends(CharacterData, Node$1);
function Text() {}
Text.prototype = {
    nodeName: "#text",
    nodeType: TEXT_NODE,
    splitText: function(a) {
        var e = this.data
          , i = e.substring(a);
        e = e.substring(0, a),
        this.data = this.nodeValue = e,
        this.length = e.length;
        var o = this.ownerDocument.createTextNode(i);
        return this.parentNode && this.parentNode.insertBefore(o, this.nextSibling),
        o
    }
};
_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(a, e, i) {
    return nodeSerializeToString.call(a, e, i)
}
;
Node$1.prototype.toString = nodeSerializeToString;
function nodeSerializeToString(a, e) {
    var i = []
      , o = this.nodeType == 9 ? this.documentElement : this
      , s = o.prefix
      , c = o.namespaceURI;
    if (c && s == null) {
        var s = o.lookupPrefix(c);
        if (s == null)
            var d = [{
                namespace: c,
                prefix: null
            }]
    }
    return serializeToString(this, i, a, e, d),
    i.join("")
}
function needNamespaceDefine(a, e, i) {
    var o = a.prefix || ""
      , s = a.namespaceURI;
    if (!o && !s || o === "xml" && s === "http://www.w3.org/XML/1998/namespace" || s == "http://www.w3.org/2000/xmlns/")
        return !1;
    for (var c = i.length; c--; ) {
        var d = i[c];
        if (d.prefix == o)
            return d.namespace != s
    }
    return !0
}
function serializeToString(a, e, i, o, s) {
    if (o)
        if (a = o(a),
        a) {
            if (typeof a == "string") {
                e.push(a);
                return
            }
        } else
            return;
    switch (a.nodeType) {
    case ELEMENT_NODE:
        s || (s = []),
        s.length;
        var c = a.attributes
          , d = c.length
          , et = a.firstChild
          , _ = a.tagName;
        i = htmlns === a.namespaceURI || i,
        e.push("<", _);
        for (var b = 0; b < d; b++) {
            var k = c.item(b);
            k.prefix == "xmlns" ? s.push({
                prefix: k.localName,
                namespace: k.value
            }) : k.nodeName == "xmlns" && s.push({
                prefix: "",
                namespace: k.value
            })
        }
        for (var b = 0; b < d; b++) {
            var k = c.item(b);
            if (needNamespaceDefine(k, i, s)) {
                var j = k.prefix || ""
                  , $ = k.namespaceURI
                  , _e = j ? " xmlns:" + j : " xmlns";
                e.push(_e, '="', $, '"'),
                s.push({
                    prefix: j,
                    namespace: $
                })
            }
            serializeToString(k, e, i, o, s)
        }
        if (needNamespaceDefine(a, i, s)) {
            var j = a.prefix || ""
              , $ = a.namespaceURI
              , _e = j ? " xmlns:" + j : " xmlns";
            e.push(_e, '="', $, '"'),
            s.push({
                prefix: j,
                namespace: $
            })
        }
        if (et || i && !/^(?:meta|link|img|br|hr|input)$/i.test(_)) {
            if (e.push(">"),
            i && /^script$/i.test(_))
                for (; et; )
                    et.data ? e.push(et.data) : serializeToString(et, e, i, o, s),
                    et = et.nextSibling;
            else
                for (; et; )
                    serializeToString(et, e, i, o, s),
                    et = et.nextSibling;
            e.push("</", _, ">")
        } else
            e.push("/>");
        return;
    case DOCUMENT_NODE:
    case DOCUMENT_FRAGMENT_NODE:
        for (var et = a.firstChild; et; )
            serializeToString(et, e, i, o, s),
            et = et.nextSibling;
        return;
    case ATTRIBUTE_NODE:
        return e.push(" ", a.name, '="', a.value.replace(/[<&"]/g, _xmlEncoder), '"');
    case TEXT_NODE:
        return e.push(a.data.replace(/[<&]/g, _xmlEncoder));
    case CDATA_SECTION_NODE:
        return e.push("<![CDATA[", a.data, "]]>");
    case COMMENT_NODE:
        return e.push("<!--", a.data, "-->");
    case DOCUMENT_TYPE_NODE:
        var tt = a.publicId
          , rt = a.systemId;
        if (e.push("<!DOCTYPE ", a.name),
        tt)
            e.push(' PUBLIC "', tt),
            rt && rt != "." && e.push('" "', rt),
            e.push('">');
        else if (rt && rt != ".")
            e.push(' SYSTEM "', rt, '">');
        else {
            var it = a.internalSubset;
            it && e.push(" [", it, "]"),
            e.push(">")
        }
        return;
    case PROCESSING_INSTRUCTION_NODE:
        return e.push("<?", a.target, " ", a.data, "?>");
    case ENTITY_REFERENCE_NODE:
        return e.push("&", a.nodeName, ";");
    default:
        e.push("??", a.nodeName)
    }
}
function importNode(a, e, i) {
    var o;
    switch (e.nodeType) {
    case ELEMENT_NODE:
        o = e.cloneNode(!1),
        o.ownerDocument = a;
    case DOCUMENT_FRAGMENT_NODE:
        break;
    case ATTRIBUTE_NODE:
        i = !0;
        break
    }
    if (o || (o = e.cloneNode(!1)),
    o.ownerDocument = a,
    o.parentNode = null,
    i)
        for (var s = e.firstChild; s; )
            o.appendChild(importNode(a, s, i)),
            s = s.nextSibling;
    return o
}
function cloneNode(a, e, i) {
    var o = new e.constructor;
    for (var s in e) {
        var c = e[s];
        typeof c != "object" && c != o[s] && (o[s] = c)
    }
    switch (e.childNodes && (o.childNodes = new NodeList),
    o.ownerDocument = a,
    o.nodeType) {
    case ELEMENT_NODE:
        var d = e.attributes
          , _ = o.attributes = new NamedNodeMap
          , b = d.length;
        _._ownerElement = o;
        for (var k = 0; k < b; k++)
            o.setAttributeNode(cloneNode(a, d.item(k), !0));
        break;
    case ATTRIBUTE_NODE:
        i = !0
    }
    if (i)
        for (var j = e.firstChild; j; )
            o.appendChild(cloneNode(a, j, i)),
            j = j.nextSibling;
    return o
}
function __set__(a, e, i) {
    a[e] = i
}
try {
    if (Object.defineProperty) {
        let a = function(e) {
            switch (e.nodeType) {
            case ELEMENT_NODE:
            case DOCUMENT_FRAGMENT_NODE:
                var i = [];
                for (e = e.firstChild; e; )
                    e.nodeType !== 7 && e.nodeType !== 8 && i.push(a(e)),
                    e = e.nextSibling;
                return i.join("");
            default:
                return e.nodeValue
            }
        };
        var getTextContent = a;
        Object.defineProperty(LiveNodeList.prototype, "length", {
            get: function() {
                return _updateLiveList(this),
                this.$$length
            }
        }),
        Object.defineProperty(Node$1.prototype, "textContent", {
            get: function() {
                return a(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, i, o) {
            e["$$" + i] = o
        }
    }
} catch (a) {}
dom.DOMImplementation = DOMImplementation$1;
dom.XMLSerializer = XMLSerializer$1;
function DOMParser$1(a) {
    this.options = a || {
        locator: {}
    }
}
DOMParser$1.prototype.parseFromString = function(a, e) {
    var i = this.options
      , o = new XMLReader
      , s = i.domBuilder || new DOMHandler
      , c = i.errorHandler
      , d = i.locator
      , _ = i.xmlns || {}
      , b = {
        lt: "<",
        gt: ">",
        amp: "&",
        quot: '"',
        apos: "'"
    };
    return d && s.setDocumentLocator(d),
    o.errorHandler = buildErrorHandler(c, s, d),
    o.domBuilder = i.domBuilder || s,
    /\/x?html?$/.test(e) && (b.nbsp = "\xA0",
    b.copy = "\xA9",
    _[""] = "http://www.w3.org/1999/xhtml"),
    _.xml = _.xml || "http://www.w3.org/XML/1998/namespace",
    a ? o.parse(a, _, b) : o.errorHandler.error("invalid doc source"),
    s.doc
}
;
function buildErrorHandler(a, e, i) {
    if (!a) {
        if (e instanceof DOMHandler)
            return e;
        a = e
    }
    var o = {}
      , s = a instanceof Function;
    i = i || {};
    function c(d) {
        var _ = a[d];
        !_ && s && (_ = a.length == 2 ? function(b) {
            a(d, b)
        }
        : a),
        o[d] = _ && function(b) {
            _("[xmldom " + d + "]	" + b + _locator(i))
        }
        || function() {}
    }
    return c("warning"),
    c("error"),
    c("fatalError"),
    o
}
function DOMHandler() {
    this.cdata = !1
}
function position(a, e) {
    e.lineNumber = a.lineNumber,
    e.columnNumber = a.columnNumber
}
DOMHandler.prototype = {
    startDocument: function() {
        this.doc = new DOMImplementation().createDocument(null, null, null),
        this.locator && (this.doc.documentURI = this.locator.systemId)
    },
    startElement: function(a, e, i, o) {
        var s = this.doc
          , c = s.createElementNS(a, i || e)
          , d = o.length;
        appendElement(this, c),
        this.currentElement = c,
        this.locator && position(this.locator, c);
        for (var _ = 0; _ < d; _++) {
            var a = o.getURI(_)
              , b = o.getValue(_)
              , i = o.getQName(_)
              , k = s.createAttributeNS(a, i);
            this.locator && position(o.getLocator(_), k),
            k.value = k.nodeValue = b,
            c.setAttributeNode(k)
        }
    },
    endElement: function(a, e, i) {
        var o = this.currentElement;
        o.tagName,
        this.currentElement = o.parentNode
    },
    startPrefixMapping: function(a, e) {},
    endPrefixMapping: function(a) {},
    processingInstruction: function(a, e) {
        var i = this.doc.createProcessingInstruction(a, e);
        this.locator && position(this.locator, i),
        appendElement(this, i)
    },
    ignorableWhitespace: function(a, e, i) {},
    characters: function(a, e, i) {
        if (a = _toString.apply(this, arguments),
        a) {
            if (this.cdata)
                var o = this.doc.createCDATASection(a);
            else
                var o = this.doc.createTextNode(a);
            this.currentElement ? this.currentElement.appendChild(o) : /^\s*$/.test(a) && this.doc.appendChild(o),
            this.locator && position(this.locator, o)
        }
    },
    skippedEntity: function(a) {},
    endDocument: function() {
        this.doc.normalize()
    },
    setDocumentLocator: function(a) {
        (this.locator = a) && (a.lineNumber = 0)
    },
    comment: function(a, e, i) {
        a = _toString.apply(this, arguments);
        var o = this.doc.createComment(a);
        this.locator && position(this.locator, o),
        appendElement(this, o)
    },
    startCDATA: function() {
        this.cdata = !0
    },
    endCDATA: function() {
        this.cdata = !1
    },
    startDTD: function(a, e, i) {
        var o = this.doc.implementation;
        if (o && o.createDocumentType) {
            var s = o.createDocumentType(a, e, i);
            this.locator && position(this.locator, s),
            appendElement(this, s)
        }
    },
    warning: function(a) {
        console.warn("[xmldom warning]	" + a, _locator(this.locator))
    },
    error: function(a) {
        console.error("[xmldom error]	" + a, _locator(this.locator))
    },
    fatalError: function(a) {
        throw console.error("[xmldom fatalError]	" + a, _locator(this.locator)),
        a
    }
};
function _locator(a) {
    if (a)
        return `
@` + (a.systemId || "") + "#[line:" + a.lineNumber + ",col:" + a.columnNumber + "]"
}
function _toString(a, e, i) {
    return typeof a == "string" ? a.substr(e, i) : a.length >= e + i || e ? new java.lang.String(a,e,i) + "" : a
}
"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function(a) {
    DOMHandler.prototype[a] = function() {
        return null
    }
});
function appendElement(a, e) {
    a.currentElement ? a.currentElement.appendChild(e) : a.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 a = {
        mergeCDATA: !0,
        normalize: !0,
        stripElemPrefix: !0
    }
      , e = new RegExp(/(?!xmlns)^.*:/);
    return this.grokType = function(i) {
        return /^\s*$/.test(i) ? null : /^(?:true|false)$/i.test(i) ? i.toLowerCase() === "true" : isFinite(i) ? parseFloat(i) : i
    }
    ,
    this.parseString = function(i, o) {
        if (i) {
            var s = this.stringToXML(i);
            return s.getElementsByTagName("parsererror").length ? null : this.parseXML(s, o)
        } else
            return null
    }
    ,
    this.parseXML = function(i, o) {
        for (var s in o)
            a[s] = o[s];
        var c = {}
          , d = 0
          , _ = ""
          , b = i.childNodes.length;
        if (b)
            for (var k, j, $, _e = 0; _e < i.childNodes.length; _e++)
                k = i.childNodes.item(_e),
                k.nodeType === 4 ? a.mergeCDATA && (_ += k.nodeValue) : k.nodeType === 3 ? _ += k.nodeValue : k.nodeType === 1 && (d === 0 && (c = {}),
                a.stripElemPrefix ? j = k.nodeName.replace(e, "") : j = k.nodeName,
                $ = xmlToJSON.parseXML(k),
                c.hasOwnProperty(j) ? (c[j].constructor !== Array && (c[j] = [c[j]]),
                c[j].push($)) : (c[j] = $,
                d++));
        return Object.keys(c).length || (c = _ || ""),
        c
    }
    ,
    this.xmlToString = function(i) {
        try {
            var o = i.xml ? i.xml : new XMLSerializer().serializeToString(i);
            return o
        } catch {
            return null
        }
    }
    ,
    this.stringToXML = function(i) {
        try {
            var o = null;
            if (window.DOMParser) {
                var s = new DOMParser;
                return o = s.parseFromString(i, "text/xml"),
                o
            } else
                return o = new ActiveXObject("Microsoft.XMLDOM"),
                o.async = !1,
                o.loadXML(i),
                o
        } catch {
            return null
        }
    }
    ,
    this
}
.call({})
  , xml2json$1 = function(a) {
    return xmlToJSON.parseString(a)
}
  , 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(a) {
    var e = [];
    if (a instanceof Object)
        for (var i in a)
            a.hasOwnProperty(i) && e.push(i);
    return e
}
  , process_to_xml = function(a, e) {
    var i = function(o, s, c, d, _) {
        var b = e.indent !== void 0 ? e.indent : "	"
          , k = e.prettyPrint ? `
` + new Array(d).join(b) : "";
        e.removeIllegalNameCharacters && (o = o.replace(element_replace, "_"));
        var j = [k, "<", o, c || ""];
        return s && s.length > 0 ? (j.push(">"),
        j.push(s),
        _ && j.push(k),
        j.push("</"),
        j.push(o),
        j.push(">")) : j.push("/>"),
        j.join("")
    };
    return function o(s, c, d) {
        var _ = typeof s;
        switch ((Array.isArray ? Array.isArray(s) : s instanceof Array) ? _ = "array" : s instanceof Date && (_ = "date"),
        _) {
        case "array":
            var b = [];
            return s.map(function(_e) {
                b.push(o(_e, 1, d + 1))
            }),
            e.prettyPrint && b.push(`
`),
            b.join("");
        case "date":
            return s.toJSON ? s.toJSON() : s + "";
        case "object":
            var k = [];
            for (var j in s)
                if (s.hasOwnProperty(j))
                    if (s[j]instanceof Array)
                        for (var $ = 0; $ < s[j].length; $++)
                            s[j].hasOwnProperty($) && k.push(i(j, o(s[j][$], 0, d + 1), null, d + 1, objKeys(s[j][$]).length));
                    else
                        k.push(i(j, o(s[j], 0, d + 1), null, d + 1));
            return e.prettyPrint && k.length > 0 && k.push(`
`),
            k.join("");
        case "function":
            return s();
        default:
            return e.escape ? esc(s) : "" + s
        }
    }(a, 0, 0)
}
  , xml_header = function(a) {
    var e = ['<?xml version="1.0" encoding="UTF-8"'];
    return a && e.push(' standalone="yes"'),
    e.push("?>"),
    e.join("")
};
function esc(a) {
    return ("" + a).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/'/g, "&apos;").replace(/"/g, "&quot;").replace(not_safe_in_xml, "")
}
var json2xml$1 = function(a, e) {
    if (e || (e = {
        xmlHeader: {
            standalone: !0
        },
        prettyPrint: !0,
        indent: "  ",
        escape: !0
    }),
    typeof a == "string")
        try {
            a = JSON.parse(a.toString())
        } catch {
            return !1
        }
    var i = ""
      , o = "";
    e && (typeof e == "object" ? (e.xmlHeader && (i = xml_header(!!e.xmlHeader.standalone)),
    typeof e.docType != "undefined" && (o = "<!DOCTYPE " + e.docType + ">")) : i = xml_header()),
    e = e || {};
    var s = [i, e.prettyPrint && o ? `
` : "", o, process_to_xml(a, e)];
    return s.join("").replace(/\n{2,}/g, `
`).replace(/\s+$/g, "")
}
  , md5 = md5$1.exports
  , CryptoJS = crypto.exports
  , xml2json = xml2json_1
  , json2xml = json2xml$1;
function camSafeUrlEncode(a) {
    return encodeURIComponent(a).replace(/!/g, "%21").replace(/'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/\*/g, "%2A")
}
function getObjectKeys(a, e) {
    var i = [];
    for (var o in a)
        a.hasOwnProperty(o) && i.push(e ? camSafeUrlEncode(o).toLowerCase() : o);
    return i.sort(function(s, c) {
        return s = s.toLowerCase(),
        c = c.toLowerCase(),
        s === c ? 0 : s > c ? 1 : -1
    })
}
var obj2str = function(a, e) {
    var i, o, s, c = [], d = getObjectKeys(a);
    for (i = 0; i < d.length; i++)
        o = d[i],
        s = a[o] === void 0 || a[o] === null ? "" : "" + a[o],
        o = e ? camSafeUrlEncode(o).toLowerCase() : camSafeUrlEncode(o),
        s = camSafeUrlEncode(s) || "",
        c.push(o + "=" + s);
    return c.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(a) {
    var e = {};
    for (var i in a) {
        var o = i.toLowerCase();
        (o.indexOf("x-cos-") > -1 || signHeaders.indexOf(o) > -1) && (e[i] = a[i])
    }
    return e
}
  , getAuth$1 = function(a) {
    a = a || {};
    var e = a.SecretId, i = a.SecretKey, o = a.KeyTime, s = (a.method || a.Method || "get").toLowerCase(), c = clone(a.Query || a.params || {}), d = getSignHeaderObj(clone(a.Headers || a.headers || {})), _ = a.Key || "", b;
    a.UseRawKey ? b = a.Pathname || a.pathname || "/" + _ : (b = a.Pathname || a.pathname || _,
    b.indexOf("/") !== 0 && (b = "/" + b));
    var k = a.ForceSignHost !== !1;
    if (!d.Host && !d.host && a.Bucket && a.Region && k && (d.Host = a.Bucket + ".cos." + a.Region + ".myqcloud.com"),
    !e)
        throw new Error("missing param SecretId");
    if (!i)
        throw new Error("missing param SecretKey");
    var j = Math.round(getSkewTime(a.SystemClockOffset) / 1e3) - 1
      , $ = j
      , _e = a.Expires || a.expires;
    _e === void 0 ? $ += 900 : $ += _e * 1 || 0;
    var et = "sha1"
      , tt = e
      , rt = o || j + ";" + $
      , it = o || j + ";" + $
      , nt = getObjectKeys(d, !0).join(";").toLowerCase()
      , ot = getObjectKeys(c, !0).join(";").toLowerCase()
      , at = CryptoJS.HmacSHA1(it, i).toString()
      , st = [s, b, util$5.obj2str(c, !0), util$5.obj2str(d, !0), ""].join(`
`)
      , ut = ["sha1", rt, CryptoJS.SHA1(st).toString(), ""].join(`
`)
      , ct = CryptoJS.HmacSHA1(ut, at).toString()
      , lt = ["q-sign-algorithm=" + et, "q-ak=" + tt, "q-sign-time=" + rt, "q-key-time=" + it, "q-header-list=" + nt, "q-url-param-list=" + ot, "q-signature=" + ct].join("&");
    return lt
}
  , readIntBE = function(a, e, i) {
    var o = e / 8
      , s = a.slice(i, i + o);
    return new Uint8Array(s).reverse(),
    new {
        8: Uint8Array,
        16: Uint16Array,
        32: Uint32Array
    }[e](s)[0]
}
  , buf2str = function(a, e, i, o) {
    var s = a.slice(e, i)
      , c = "";
    return new Uint8Array(s).forEach(function(d) {
        c += String.fromCharCode(d)
    }),
    o && (c = decodeURIComponent(escape(c))),
    c
}
  , parseSelectPayload = function(a) {
    for (var e = {}, i = buf2str(a), o = {
        records: []
    }; a.byteLength; ) {
        var s = readIntBE(a, 32, 0), c = readIntBE(a, 32, 4), d = s - c - 16, _ = 0, b;
        for (a = a.slice(12); _ < c; ) {
            var k = readIntBE(a, 8, _)
              , j = buf2str(a, _ + 1, _ + 1 + k)
              , $ = readIntBE(a, 16, _ + k + 2)
              , _e = buf2str(a, _ + k + 4, _ + k + 4 + $);
            e[j] = _e,
            _ += k + 4 + $
        }
        if (e[":event-type"] === "Records")
            b = buf2str(a, _, _ + d, !0),
            o.records.push(b);
        else if (e[":event-type"] === "Stats")
            b = buf2str(a, _, _ + d, !0),
            o.stats = util$5.xml2json(b).Stats;
        else if (e[":event-type"] === "error") {
            var et = e[":error-code"]
              , tt = e[":error-message"]
              , rt = new Error(tt);
            rt.message = tt,
            rt.name = rt.code = et,
            o.error = rt
        } else
            ["Progress", "Continuation", "End"].includes(e[":event-type"]);
        a = a.slice(_ + d + 4)
    }
    return {
        payload: o.records.join(""),
        body: i
    }
}
  , getSourceParams = function(a) {
    var e = this.options.CopySourceParser;
    if (e)
        return e(a);
    var i = a.match(/^([^.]+-\d+)\.cos(v6|-cdc)?\.([^.]+)\.myqcloud\.com\/(.+)$/);
    return i ? {
        Bucket: i[1],
        Region: i[3],
        Key: i[4]
    } : null
}
  , noop = function() {}
  , clearKey = function(a) {
    var e = {};
    for (var i in a)
        a.hasOwnProperty(i) && a[i] !== void 0 && a[i] !== null && (e[i] = a[i]);
    return e
}
  , readAsBinaryString = function(a, e) {
    var i, o = new FileReader;
    FileReader.prototype.readAsBinaryString ? (i = FileReader.prototype.readAsBinaryString,
    o.onload = function() {
        e(this.result)
    }
    ) : FileReader.prototype.readAsArrayBuffer ? i = function(s) {
        var c = ""
          , d = new FileReader;
        d.onload = function(_) {
            for (var b = new Uint8Array(d.result), k = b.byteLength, j = 0; j < k; j++)
                c += String.fromCharCode(b[j]);
            e(c)
        }
        ,
        d.readAsArrayBuffer(s)
    }
    : console.error("FileReader not support readAsBinaryString"),
    i.call(o, a)
}
  , fileSliceNeedCopy = function() {
    var a = function(i, o) {
        i = i.split("."),
        o = o.split(".");
        for (var s = 0; s < o.length; s++)
            if (i[s] !== o[s])
                return parseInt(i[s]) > parseInt(o[s]) ? 1 : -1;
        return 0
    }
      , e = function(i) {
        if (!i)
            return !1;
        var o = (i.match(/Chrome\/([.\d]+)/) || [])[1]
          , s = (i.match(/QBCore\/([.\d]+)/) || [])[1]
          , c = (i.match(/QQBrowser\/([.\d]+)/) || [])[1]
          , d = o && a(o, "53.0.2785.116") < 0 && s && a(s, "3.53.991.400") < 0 && c && a(c, "9.0.2524.400") <= 0 || !1;
        return d
    };
    return e(typeof navigator != "undefined" && navigator.userAgent)
}()
  , fileSlice = function(a, e, i, o, s) {
    var c;
    if (a.slice ? c = a.slice(e, i) : a.mozSlice ? c = a.mozSlice(e, i) : a.webkitSlice && (c = a.webkitSlice(e, i)),
    o && fileSliceNeedCopy) {
        var d = new FileReader;
        d.onload = function(_) {
            c = null,
            s(new Blob([d.result]))
        }
        ,
        d.readAsArrayBuffer(c)
    } else
        s(c)
}
  , getBodyMd5 = function(a, e, i, o) {
    i = i || noop,
    a ? typeof e == "string" ? i(util$5.md5(e, !0)) : Blob && e instanceof Blob ? util$5.getFileMd5(e, function(s, c) {
        i(c)
    }, o) : i() : i()
}
  , md5ChunkSize = 1024 * 1024
  , getFileMd5 = function(a, e, i) {
    var o = a.size
      , s = 0
      , c = md5.getCtx()
      , d = function(_) {
        if (_ >= o) {
            var b = c.digest("hex");
            e(null, b);
            return
        }
        var k = Math.min(o, _ + md5ChunkSize);
        util$5.fileSlice(a, _, k, !1, function(j) {
            readAsBinaryString(j, function($) {
                j = null,
                c = c.update($, !0),
                s += $.length,
                $ = null,
                i && i({
                    loaded: s,
                    total: o,
                    percent: Math.round(s / o * 1e4) / 1e4
                }),
                d(_ + md5ChunkSize)
            })
        })
    };
    d(0)
};
function clone(a) {
    return map$1(a, function(e) {
        return typeof e == "object" && e !== null ? clone(e) : e
    })
}
function attr(a, e, i) {
    return a && e in a ? a[e] : i
}
function extend$1(a, e) {
    return each(e, function(i, o) {
        a[o] = e[o]
    }),
    a
}
function isArray(a) {
    return a instanceof Array
}
function isInArray(a, e) {
    for (var i = !1, o = 0; o < a.length; o++)
        if (e === a[o]) {
            i = !0;
            break
        }
    return i
}
function makeArray(a) {
    return isArray(a) ? a : [a]
}
function each(a, e) {
    for (var i in a)
        a.hasOwnProperty(i) && e(a[i], i)
}
function map$1(a, e) {
    var i = isArray(a) ? [] : {};
    for (var o in a)
        a.hasOwnProperty(o) && (i[o] = e(a[o], o));
    return i
}
function filter(a, e) {
    var i = isArray(a)
      , o = i ? [] : {};
    for (var s in a)
        a.hasOwnProperty(s) && e(a[s], s) && (i ? o.push(a[s]) : o[s] = a[s]);
    return o
}
var binaryBase64 = function(a) {
    var e, i, o, s = "";
    for (e = 0,
    i = a.length / 2; e < i; e++)
        o = parseInt(a[e * 2] + a[e * 2 + 1], 16),
        s += String.fromCharCode(o);
    return btoa(s)
}
  , uuid = function() {
    var a = function() {
        return ((1 + Math.random()) * 65536 | 0).toString(16).substring(1)
    };
    return a() + a() + "-" + a() + "-" + a() + "-" + a() + "-" + a() + a() + a()
}
  , hasMissingParams = function(a, e) {
    var i = e.Bucket
      , o = e.Region
      , s = e.Key
      , c = this.options.Domain
      , d = !c || c.indexOf("{Bucket}") > -1
      , _ = !c || c.indexOf("{Region}") > -1;
    if (a.indexOf("Bucket") > -1 || a === "deleteMultipleObject" || a === "multipartList" || a === "listObjectVersions") {
        if (d && !i)
            return "Bucket";
        if (_ && !o)
            return "Region"
    } else if (a.indexOf("Object") > -1 || a.indexOf("multipart") > -1 || a === "sliceUploadFile" || a === "abortUploadTask") {
        if (d && !i)
            return "Bucket";
        if (_ && !o)
            return "Region";
        if (!s)
            return "Key"
    }
    return !1
}
  , formatParams = function(a, e) {
    if (e = extend$1({}, e),
    a !== "getAuth" && a !== "getV4Auth" && a !== "getObjectUrl") {
        var i = e.Headers || {};
        if (e && typeof e == "object") {
            (function() {
                for (var s in e)
                    e.hasOwnProperty(s) && s.indexOf("x-cos-") > -1 && (i[s] = e[s])
            }
            )();
            var o = {
                "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(o, function(s, c) {
                e[s] !== void 0 && (i[c] = e[s])
            }),
            e.Headers = clearKey(i)
        }
    }
    return e
}
  , apiWrapper = function(a, e) {
    return function(i, o) {
        var s = this;
        typeof i == "function" && (o = i,
        i = {}),
        i = formatParams(a, i);
        var c = function($) {
            return $ && $.headers && ($.headers["x-cos-request-id"] && ($.RequestId = $.headers["x-cos-request-id"]),
            $.headers["x-ci-request-id"] && ($.RequestId = $.headers["x-ci-request-id"]),
            $.headers["x-cos-version-id"] && ($.VersionId = $.headers["x-cos-version-id"]),
            $.headers["x-cos-delete-marker"] && ($.DeleteMarker = $.headers["x-cos-delete-marker"])),
            $
        }
          , d = function($, _e) {
            o && o(c($), c(_e))
        }
          , _ = function() {
            if (a !== "getService" && a !== "abortUploadTask") {
                var $ = hasMissingParams.call(s, a, i);
                if ($)
                    return "missing param " + $;
                if (i.Region) {
                    if (s.options.CompatibilityMode) {
                        if (!/^([a-z\d-.]+)$/.test(i.Region))
                            return "Region format error."
                    } else {
                        if (i.Region.indexOf("cos.") > -1)
                            return 'param Region should not be start with "cos."';
                        if (!/^([a-z\d-]+)$/.test(i.Region))
                            return "Region format error."
                    }
                    !s.options.CompatibilityMode && i.Region.indexOf("-") === -1 && i.Region !== "yfb" && i.Region !== "default" && i.Region !== "accelerate" && console.warn("warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224")
                }
                if (i.Bucket) {
                    if (!/^([a-z\d-]+)-(\d+)$/.test(i.Bucket))
                        if (i.AppId)
                            i.Bucket = i.Bucket + "-" + i.AppId;
                        else if (s.options.AppId)
                            i.Bucket = i.Bucket + "-" + s.options.AppId;
                        else
                            return 'Bucket should format as "test-1250000000".';
                    i.AppId && (console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).'),
                    delete i.AppId)
                }
                !s.options.UseRawKey && i.Key && i.Key.substr(0, 1) === "/" && (i.Key = i.Key.substr(1))
            }
        }
          , b = _()
          , k = a === "getAuth" || a === "getObjectUrl";
        if (window.Promise && !k && !o)
            return new Promise(function($, _e) {
                if (o = function(et, tt) {
                    et ? _e(et) : $(tt)
                }
                ,
                b)
                    return d(util$5.error(new Error(b)));
                e.call(s, i, d)
            }
            );
        if (b)
            return d(util$5.error(new Error(b)));
        var j = e.call(s, i, d);
        if (k)
            return j
    }
}
  , throttleOnProgress = function(a, e) {
    var i = this, o = 0, s = 0, c = Date.now(), d, _;
    function b() {
        if (_ = 0,
        e && typeof e == "function") {
            d = Date.now();
            var k = Math.max(0, Math.round((s - o) / ((d - c) / 1e3) * 100) / 100) || 0, j;
            s === 0 && a === 0 ? j = 1 : j = Math.floor(s / a * 100) / 100 || 0,
            c = d,
            o = s;
            try {
                e({
                    loaded: s,
                    total: a,
                    speed: k,
                    percent: j
                })
            } catch {}
        }
    }
    return function(k, j) {
        if (k && (s = k.loaded,
        a = k.total),
        j)
            clearTimeout(_),
            b();
        else {
            if (_)
                return;
            _ = setTimeout(b, i.options.ProgressInterval)
        }
    }
}
  , getFileSize = function(a, e, i) {
    var o;
    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]"))
        o = e.Body.size;
    else {
        i(util$5.error(new Error("params body format error, Only allow File|Blob|String.")));
        return
    }
    e.ContentLength = o,
    i(null, o)
}
  , getSkewTime = function(a) {
    return Date.now() + (a || 0)
}
  , error = function(a, e) {
    var i = a;
    return a.message = a.message || null,
    typeof e == "string" ? (a.error = e,
    a.message = e) : typeof e == "object" && e !== null && (extend$1(a, e),
    (e.code || e.name) && (a.code = e.code || e.name),
    e.message && (a.message = e.message),
    e.stack && (a.stack = e.stack)),
    typeof Object.defineProperty == "function" && (Object.defineProperty(a, "name", {
        writable: !0,
        enumerable: !1
    }),
    Object.defineProperty(a, "message", {
        enumerable: !0
    })),
    a.name = e && e.name || a.name || a.code || "Error",
    a.code || (a.code = a.name),
    a.error || (a.error = clone(i)),
    a
}
  , isNode = function() {
    return typeof window != "object" && typeof process == "object" && typeof commonjsRequire == "function"
}
  , isCIHost = function(a) {
    return /^https?:\/\/([^/]+\.)?ci\.[^/]+/.test(a)
}
  , util$5 = {
    noop,
    formatParams,
    apiWrapper,
    xml2json,
    json2xml,
    md5,
    clearKey,
    fileSlice,
    getBodyMd5,
    getFileMd5,
    binaryBase64,
    extend: extend$1,
    isArray,
    isInArray,
    makeArray,
    each,
    map: map$1,
    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(a) {
    var e = {}
      , i = function(o) {
        return !e[o] && (e[o] = []),
        e[o]
    };
    a.on = function(o, s) {
        o === "task-list-update" && console.warn('warning: Event "' + o + '" has been deprecated. Please use "list-update" instead.'),
        i(o).push(s)
    }
    ,
    a.off = function(o, s) {
        for (var c = i(o), d = c.length - 1; d >= 0; d--)
            s === c[d] && c.splice(d, 1)
    }
    ,
    a.emit = function(o, s) {
        for (var c = i(o).map(function(_) {
            return _
        }), d = 0; d < c.length; d++)
            c[d](s)
    }
}
  , 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 a = JSON.parse(localStorage.getItem(cacheKey))
    } catch {}
    a || (a = []),
    cache = a
}, setCache = function() {
    try {
        localStorage.setItem(cacheKey, JSON.stringify(cache))
    } catch {}
}, init = function() {
    if (!cache) {
        getCache.call(this);
        for (var a = !1, e = Math.round(Date.now() / 1e3), i = cache.length - 1; i >= 0; i--) {
            var o = cache[i][2];
            (!o || o + expires < e) && (cache.splice(i, 1),
            a = !0)
        }
        a && setCache()
    }
}, save = function() {
    timer || (timer = setTimeout(function() {
        setCache(),
        timer = null
    }, 400))
}, mod = {
    using: {},
    setUsing: function(a) {
        mod.using[a] = !0
    },
    removeUsing: function(a) {
        delete mod.using[a]
    },
    getFileId: function(a, e, i, o) {
        return a.name && a.size && a.lastModifiedDate && e ? util$4.md5([a.name, a.size, a.lastModifiedDate, e, i, o].join("::")) : null
    },
    getUploadIdList: function(a) {
        if (!a)
            return null;
        init.call(this);
        for (var e = [], i = 0; i < cache.length; i++)
            cache[i][0] === a && e.push(cache[i][1]);
        return e.length ? e : null
    },
    saveUploadId: function(a, e, i) {
        if (init.call(this),
        !!a) {
            for (var o = cache.length - 1; o >= 0; o--) {
                var s = cache[o];
                s[0] === a && s[1] === e && cache.splice(o, 1)
            }
            cache.unshift([a, e, Math.round(Date.now() / 1e3)]),
            cache.length > i && cache.splice(i),
            save()
        }
    },
    removeUploadId: function(a) {
        init.call(this),
        delete mod.using[a];
        for (var e = cache.length - 1; e >= 0; e--)
            cache[e][1] === a && cache.splice(e, 1);
        save()
    }
}, session$2 = mod, session$1 = session$2, util$3 = util_1, originApiMap = {}, transferToTaskMethod = function(a, e) {
    originApiMap[e] = a[e],
    a[e] = function(i, o) {
        i.SkipTask ? originApiMap[e].call(this, i, o) : this._addTask(e, i, o)
    }
}, initTask = function(a) {
    var e = []
      , i = {}
      , o = 0
      , s = 0
      , c = function($) {
        var _e = {
            id: $.id,
            Bucket: $.Bucket,
            Region: $.Region,
            Key: $.Key,
            FilePath: $.FilePath,
            state: $.state,
            loaded: $.loaded,
            size: $.size,
            speed: $.speed,
            percent: $.percent,
            hashPercent: $.hashPercent,
            error: $.error
        };
        return $.FilePath && (_e.FilePath = $.FilePath),
        $._custom && (_e._custom = $._custom),
        _e
    }
      , d = function() {
        var $, _e = function() {
            $ = 0,
            a.emit("task-list-update", {
                list: util$3.map(e, c)
            }),
            a.emit("list-update", {
                list: util$3.map(e, c)
            })
        };
        return function() {
            $ || ($ = setTimeout(_e))
        }
    }()
      , _ = function() {
        if (!(e.length <= a.options.UploadQueueSize)) {
            for (var $ = 0; $ < s && $ < e.length && e.length > a.options.UploadQueueSize; ) {
                var _e = e[$].state === "waiting" || e[$].state === "checking" || e[$].state === "uploading";
                !e[$] || !_e ? (i[e[$].id] && delete i[e[$].id],
                e.splice($, 1),
                s--) : $++
            }
            d()
        }
    }
      , b = function() {
        if (!(o >= a.options.FileParallelLimit)) {
            for (; e[s] && e[s].state !== "waiting"; )
                s++;
            if (!(s >= e.length)) {
                var $ = e[s];
                s++,
                o++,
                $.state = "checking",
                $.params.onTaskStart && $.params.onTaskStart(c($)),
                !$.params.UploadData && ($.params.UploadData = {});
                var _e = util$3.formatParams($.api, $.params);
                originApiMap[$.api].call(a, _e, function(et, tt) {
                    !a._isRunningTask($.id) || (($.state === "checking" || $.state === "uploading") && ($.state = et ? "error" : "success",
                    et && ($.error = et),
                    o--,
                    d(),
                    b(),
                    $.callback && $.callback(et, tt),
                    $.state === "success" && ($.params && (delete $.params.UploadData,
                    delete $.params.Body,
                    delete $.params),
                    delete $.callback)),
                    _())
                }),
                d(),
                setTimeout(b)
            }
        }
    }
      , k = function($, _e) {
        var et = i[$];
        if (!!et) {
            var tt = et && et.state === "waiting"
              , rt = et && (et.state === "checking" || et.state === "uploading");
            if (_e === "canceled" && et.state !== "canceled" || _e === "paused" && tt || _e === "paused" && rt) {
                if (_e === "paused" && et.params.Body && typeof et.params.Body.pipe == "function") {
                    console.error("stream not support pause");
                    return
                }
                et.state = _e,
                a.emit("inner-kill-task", {
                    TaskId: $,
                    toState: _e
                });
                try {
                    var it = et && et.params && et.params.UploadData.UploadId
                } catch {}
                _e === "canceled" && it && session$1.removeUsing(it),
                d(),
                rt && (o--,
                b()),
                _e === "canceled" && (et.params && (delete et.params.UploadData,
                delete et.params.Body,
                delete et.params),
                delete et.callback)
            }
            _()
        }
    };
    a._addTasks = function($) {
        util$3.each($, function(_e) {
            a._addTask(_e.api, _e.params, _e.callback, !0)
        }),
        d()
    }
    ;
    var j = !0;
    a._addTask = function($, _e, et, tt) {
        _e = util$3.formatParams($, _e);
        var rt = util$3.uuid();
        _e.TaskId = rt,
        _e.onTaskReady && _e.onTaskReady(rt),
        _e.TaskReady && (_e.TaskReady(rt),
        j && console.warn('warning: Param "TaskReady" has been deprecated. Please use "onTaskReady" instead.'),
        j = !1);
        var it = {
            params: _e,
            callback: et,
            api: $,
            index: e.length,
            id: rt,
            Bucket: _e.Bucket,
            Region: _e.Region,
            Key: _e.Key,
            FilePath: _e.FilePath || "",
            state: "waiting",
            loaded: 0,
            size: 0,
            speed: 0,
            percent: 0,
            hashPercent: 0,
            error: null,
            _custom: _e._custom
        }
          , nt = _e.onHashProgress;
        _e.onHashProgress = function(at) {
            !a._isRunningTask(it.id) || (it.hashPercent = at.percent,
            nt && nt(at),
            d())
        }
        ;
        var ot = _e.onProgress;
        return _e.onProgress = function(at) {
            !a._isRunningTask(it.id) || (it.state === "checking" && (it.state = "uploading"),
            it.loaded = at.loaded,
            it.speed = at.speed,
            it.percent = at.percent,
            ot && ot(at),
            d())
        }
        ,
        util$3.getFileSize($, _e, function(at, st) {
            if (at)
                return et(util$3.error(at));
            i[rt] = it,
            e.push(it),
            it.size = st,
            !tt && d(),
            b(),
            _()
        }),
        rt
    }
    ,
    a._isRunningTask = function($) {
        var _e = i[$];
        return !!(_e && (_e.state === "checking" || _e.state === "uploading"))
    }
    ,
    a.getTaskList = function() {
        return util$3.map(e, c)
    }
    ,
    a.cancelTask = function($) {
        k($, "canceled")
    }
    ,
    a.pauseTask = function($) {
        k($, "paused")
    }
    ,
    a.restartTask = function($) {
        var _e = i[$];
        _e && (_e.state === "paused" || _e.state === "error") && (_e.state = "waiting",
        d(),
        s = Math.min(s, _e.index),
        b())
    }
    ,
    a.isUploadRunning = function() {
        return o || s < e.length
    }
};
task$1.transferToTaskMethod = transferToTaskMethod;
task$1.init = initTask;
var base$1 = {}
  , stringifyPrimitive = function(a) {
    switch (typeof a) {
    case "string":
        return a;
    case "boolean":
        return a ? "true" : "false";
    case "number":
        return isFinite(a) ? a : "";
    default:
        return ""
    }
}
  , queryStringify = function(a, e, i, o) {
    return e = e || "&",
    i = i || "=",
    a === null && (a = void 0),
    typeof a == "object" ? Object.keys(a).map(function(s) {
        var c = encodeURIComponent(stringifyPrimitive(s)) + i;
        return Array.isArray(a[s]) ? a[s].map(function(d) {
            return c + encodeURIComponent(stringifyPrimitive(d))
        }).join(e) : c + encodeURIComponent(stringifyPrimitive(a[s]))
    }).filter(Boolean).join(e) : o ? encodeURIComponent(stringifyPrimitive(o)) + i + encodeURIComponent(stringifyPrimitive(a)) : ""
}
  , xhrRes = function(a, e, i) {
    var o = {};
    return e.getAllResponseHeaders().trim().split(`
`).forEach(function(s) {
        if (s) {
            var c = s.indexOf(":")
              , d = s.substr(0, c).trim().toLowerCase()
              , _ = s.substr(c + 1).trim();
            o[d] = _
        }
    }),
    {
        error: a,
        statusCode: e.status,
        statusMessage: e.statusText,
        headers: o,
        body: i
    }
}
  , xhrBody = function(a, e) {
    return !e && e === "text" ? a.responseText : a.response
}
  , request$1 = function(a, e) {
    var i = (a.method || "GET").toUpperCase()
      , o = a.url;
    if (a.qs) {
        var s = queryStringify(a.qs);
        s && (o += (o.indexOf("?") === -1 ? "?" : "&") + s)
    }
    var c = new XMLHttpRequest;
    if (c.open(i, o, !0),
    c.responseType = a.dataType || "text",
    a.xhrFields)
        for (var d in a.xhrFields)
            c[d] = a.xhrFields[d];
    var _ = a.headers;
    if (_)
        for (var b in _)
            _.hasOwnProperty(b) && b.toLowerCase() !== "content-length" && b.toLowerCase() !== "user-agent" && b.toLowerCase() !== "origin" && b.toLowerCase() !== "host" && c.setRequestHeader(b, _[b]);
    return a.onProgress && c.upload && (c.upload.onprogress = a.onProgress),
    a.onDownloadProgress && (c.onprogress = a.onDownloadProgress),
    a.timeout && (c.timeout = a.timeout),
    c.ontimeout = function(k) {
        var j = new Error("timeout");
        e(xhrRes(j, c))
    }
    ,
    c.onload = function() {
        e(xhrRes(null, c, xhrBody(c, a.dataType)))
    }
    ,
    c.onerror = function(k) {
        var j = xhrBody(c, a.dataType);
        if (j)
            e(xhrRes(null, c, j));
        else {
            var $ = c.statusText;
            !$ && c.status === 0 && ($ = new Error("CORS blocked or network error")),
            e(xhrRes($, c, j))
        }
    }
    ,
    c.send(a.body || ""),
    c
}
  , request_1 = request$1
  , REQUEST = request_1
  , util$2 = util_1;
function getService(a, e) {
    typeof a == "function" && (e = a,
    a = {});
    var i = this.options.Protocol || (util$2.isBrowser && location.protocol === "http:" ? "http:" : "https:")
      , o = this.options.ServiceDomain
      , s = a.AppId || this.options.appId
      , c = a.Region;
    o ? (o = o.replace(/\{\{AppId\}\}/ig, s || "").replace(/\{\{Region\}\}/ig, c || "").replace(/\{\{.*?\}\}/ig, ""),
    /^[a-zA-Z]+:\/\//.test(o) || (o = i + "//" + o),
    o.slice(-1) === "/" && (o = o.slice(0, -1))) : c ? o = i + "//cos." + c + ".myqcloud.com" : o = i + "//service.cos.myqcloud.com";
    var d = ""
      , _ = c ? "cos." + c + ".myqcloud.com" : "service.cos.myqcloud.com"
      , b = o.replace(/^https?:\/\/([^/]+)(\/.*)?$/, "$1");
    _ === b && (d = _),
    submitRequest.call(this, {
        Action: "name/cos:GetService",
        url: o,
        method: "GET",
        headers: a.Headers,
        SignHost: d
    }, function(k, j) {
        if (k)
            return e(k);
        var $ = j && j.ListAllMyBucketsResult && j.ListAllMyBucketsResult.Buckets && j.ListAllMyBucketsResult.Buckets.Bucket || [];
        $ = util$2.isArray($) ? $ : [$];
        var _e = j && j.ListAllMyBucketsResult && j.ListAllMyBucketsResult.Owner || {};
        e(null, {
            Buckets: $,
            Owner: _e,
            statusCode: j.statusCode,
            headers: j.headers
        })
    })
}
function putBucket(a, e) {
    var i = this
      , o = "";
    if (a.BucketAZConfig) {
        var s = {
            BucketAZConfig: a.BucketAZConfig
        };
        o = util$2.json2xml({
            CreateBucketConfiguration: s
        })
    }
    submitRequest.call(this, {
        Action: "name/cos:PutBucket",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        body: o
    }, function(c, d) {
        if (c)
            return e(c);
        var _ = getUrl({
            protocol: i.options.Protocol,
            domain: i.options.Domain,
            bucket: a.Bucket,
            region: a.Region,
            isLocation: !0
        });
        e(null, {
            Location: _,
            statusCode: d.statusCode,
            headers: d.headers
        })
    })
}
function headBucket(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:HeadBucket",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        method: "HEAD"
    }, e)
}
function getBucket(a, e) {
    var i = {};
    i.prefix = a.Prefix || "",
    i.delimiter = a.Delimiter,
    i.marker = a.Marker,
    i["max-keys"] = a.MaxKeys,
    i["encoding-type"] = a.EncodingType,
    submitRequest.call(this, {
        Action: "name/cos:GetBucket",
        ResourceKey: i.prefix,
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        qs: i
    }, function(o, s) {
        if (o)
            return e(o);
        var c = s.ListBucketResult || {}
          , d = c.Contents || []
          , _ = c.CommonPrefixes || [];
        d = util$2.isArray(d) ? d : [d],
        _ = util$2.isArray(_) ? _ : [_];
        var b = util$2.clone(c);
        util$2.extend(b, {
            Contents: d,
            CommonPrefixes: _,
            statusCode: s.statusCode,
            headers: s.headers
        }),
        e(null, b)
    })
}
function deleteBucket(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucket",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        method: "DELETE"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketAcl(a, e) {
    var i = a.Headers
      , o = "";
    if (a.AccessControlPolicy) {
        var s = util$2.clone(a.AccessControlPolicy || {})
          , c = s.Grants || s.Grant;
        c = util$2.isArray(c) ? c : [c],
        delete s.Grant,
        delete s.Grants,
        s.AccessControlList = {
            Grant: c
        },
        o = util$2.json2xml({
            AccessControlPolicy: s
        }),
        i["Content-Type"] = "application/xml",
        i["Content-MD5"] = util$2.binaryBase64(util$2.md5(o))
    }
    util$2.each(i, function(d, _) {
        _.indexOf("x-cos-grant-") === 0 && (i[_] = uniqGrant(i[_]))
    }),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketACL",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: i,
        action: "acl",
        body: o
    }, function(d, _) {
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getBucketAcl(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketACL",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "acl"
    }, function(i, o) {
        if (i)
            return e(i);
        var s = o.AccessControlPolicy || {}
          , c = s.Owner || {}
          , d = s.AccessControlList.Grant || [];
        d = util$2.isArray(d) ? d : [d];
        var _ = decodeAcl(s);
        o.headers && o.headers["x-cos-acl"] && (_.ACL = o.headers["x-cos-acl"]),
        _ = util$2.extend(_, {
            Owner: c,
            Grants: d,
            statusCode: o.statusCode,
            headers: o.headers
        }),
        e(null, _)
    })
}
function putBucketCors(a, e) {
    var i = a.CORSConfiguration || {}
      , o = i.CORSRules || a.CORSRules || [];
    o = util$2.clone(util$2.isArray(o) ? o : [o]),
    util$2.each(o, function(d) {
        util$2.each(["AllowedOrigin", "AllowedHeader", "AllowedMethod", "ExposeHeader"], function(_) {
            var b = _ + "s"
              , k = d[b] || d[_] || [];
            delete d[b],
            d[_] = util$2.isArray(k) ? k : [k]
        })
    });
    var s = util$2.json2xml({
        CORSConfiguration: {
            CORSRule: o
        }
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketCORS",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: s,
        action: "cors",
        headers: c
    }, function(d, _) {
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getBucketCors(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketCORS",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "cors"
    }, function(i, o) {
        if (i) {
            if (i.statusCode === 404 && i.error && i.error.Code === "NoSuchCORSConfiguration") {
                var s = {
                    CORSRules: [],
                    statusCode: i.statusCode
                };
                i.headers && (s.headers = i.headers),
                e(null, s)
            } else
                e(i);
            return
        }
        var c = o.CORSConfiguration || {}
          , d = c.CORSRules || c.CORSRule || [];
        d = util$2.clone(util$2.isArray(d) ? d : [d]),
        util$2.each(d, function(_) {
            util$2.each(["AllowedOrigin", "AllowedHeader", "AllowedMethod", "ExposeHeader"], function(b) {
                var k = b + "s"
                  , j = _[k] || _[b] || [];
                delete _[b],
                _[k] = util$2.isArray(j) ? j : [j]
            })
        }),
        e(null, {
            CORSRules: d,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function deleteBucketCors(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketCORS",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "cors"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode || i.statusCode,
            headers: o.headers
        })
    })
}
function getBucketLocation(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketLocation",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "location"
    }, e)
}
function putBucketPolicy(a, e) {
    var i = a.Policy;
    try {
        typeof i == "string" && (i = JSON.parse(i))
    } catch {}
    if (!i || typeof i == "string")
        return e(util$2.error(new Error("Policy format error")));
    var o = JSON.stringify(i);
    i.version || (i.version = "2.0");
    var s = a.Headers;
    s["Content-Type"] = "application/json",
    s["Content-MD5"] = util$2.binaryBase64(util$2.md5(o)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketPolicy",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        action: "policy",
        body: o,
        headers: s
    }, function(c, d) {
        if (c && c.statusCode === 204)
            return e(null, {
                statusCode: c.statusCode
            });
        if (c)
            return e(c);
        e(null, {
            statusCode: d.statusCode,
            headers: d.headers
        })
    })
}
function getBucketPolicy(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketPolicy",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "policy",
        rawBody: !0
    }, function(i, o) {
        if (i)
            return i.statusCode && i.statusCode === 403 ? e(util$2.error(i, {
                ErrorStatus: "Access Denied"
            })) : i.statusCode && i.statusCode === 405 ? e(util$2.error(i, {
                ErrorStatus: "Method Not Allowed"
            })) : i.statusCode && i.statusCode === 404 ? e(util$2.error(i, {
                ErrorStatus: "Policy Not Found"
            })) : e(i);
        var s = {};
        try {
            s = JSON.parse(o.body)
        } catch {}
        e(null, {
            Policy: s,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function deleteBucketPolicy(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketPolicy",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "policy"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode || i.statusCode,
            headers: o.headers
        })
    })
}
function putBucketTagging(a, e) {
    var i = a.Tagging || {}
      , o = i.TagSet || i.Tags || a.Tags || [];
    o = util$2.clone(util$2.isArray(o) ? o : [o]);
    var s = util$2.json2xml({
        Tagging: {
            TagSet: {
                Tag: o
            }
        }
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketTagging",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: s,
        action: "tagging",
        headers: c
    }, function(d, _) {
        if (d && d.statusCode === 204)
            return e(null, {
                statusCode: d.statusCode
            });
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getBucketTagging(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketTagging",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "tagging"
    }, function(i, o) {
        if (i) {
            if (i.statusCode === 404 && i.error && (i.error === "Not Found" || i.error.Code === "NoSuchTagSet")) {
                var s = {
                    Tags: [],
                    statusCode: i.statusCode
                };
                i.headers && (s.headers = i.headers),
                e(null, s)
            } else
                e(i);
            return
        }
        var c = [];
        try {
            c = o.Tagging.TagSet.Tag || []
        } catch {}
        c = util$2.clone(util$2.isArray(c) ? c : [c]),
        e(null, {
            Tags: c,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function deleteBucketTagging(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketTagging",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "tagging"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketLifecycle(a, e) {
    var i = a.LifecycleConfiguration || {}
      , o = i.Rules || a.Rules || [];
    o = util$2.clone(o);
    var s = util$2.json2xml({
        LifecycleConfiguration: {
            Rule: o
        }
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketLifecycle",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: s,
        action: "lifecycle",
        headers: c
    }, function(d, _) {
        if (d && d.statusCode === 204)
            return e(null, {
                statusCode: d.statusCode
            });
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getBucketLifecycle(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketLifecycle",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "lifecycle"
    }, function(i, o) {
        if (i) {
            if (i.statusCode === 404 && i.error && i.error.Code === "NoSuchLifecycleConfiguration") {
                var s = {
                    Rules: [],
                    statusCode: i.statusCode
                };
                i.headers && (s.headers = i.headers),
                e(null, s)
            } else
                e(i);
            return
        }
        var c = [];
        try {
            c = o.LifecycleConfiguration.Rule || []
        } catch {}
        c = util$2.clone(util$2.isArray(c) ? c : [c]),
        e(null, {
            Rules: c,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function deleteBucketLifecycle(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketLifecycle",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "lifecycle"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketVersioning(a, e) {
    if (!a.VersioningConfiguration) {
        e(util$2.error(new Error("missing param VersioningConfiguration")));
        return
    }
    var i = a.VersioningConfiguration || {}
      , o = util$2.json2xml({
        VersioningConfiguration: i
    })
      , s = a.Headers;
    s["Content-Type"] = "application/xml",
    s["Content-MD5"] = util$2.binaryBase64(util$2.md5(o)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketVersioning",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: o,
        action: "versioning",
        headers: s
    }, function(c, d) {
        if (c && c.statusCode === 204)
            return e(null, {
                statusCode: c.statusCode
            });
        if (c)
            return e(c);
        e(null, {
            statusCode: d.statusCode,
            headers: d.headers
        })
    })
}
function getBucketVersioning(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketVersioning",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "versioning"
    }, function(i, o) {
        i || !o.VersioningConfiguration && (o.VersioningConfiguration = {}),
        e(i, o)
    })
}
function putBucketReplication(a, e) {
    var i = util$2.clone(a.ReplicationConfiguration)
      , o = util$2.json2xml({
        ReplicationConfiguration: i
    });
    o = o.replace(/<(\/?)Rules>/ig, "<$1Rule>"),
    o = o.replace(/<(\/?)Tags>/ig, "<$1Tag>");
    var s = a.Headers;
    s["Content-Type"] = "application/xml",
    s["Content-MD5"] = util$2.binaryBase64(util$2.md5(o)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketReplication",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: o,
        action: "replication",
        headers: s
    }, function(c, d) {
        if (c && c.statusCode === 204)
            return e(null, {
                statusCode: c.statusCode
            });
        if (c)
            return e(c);
        e(null, {
            statusCode: d.statusCode,
            headers: d.headers
        })
    })
}
function getBucketReplication(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketReplication",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "replication"
    }, function(i, o) {
        if (i) {
            if (i.statusCode === 404 && i.error && (i.error === "Not Found" || i.error.Code === "ReplicationConfigurationnotFoundError")) {
                var s = {
                    ReplicationConfiguration: {
                        Rules: []
                    },
                    statusCode: i.statusCode
                };
                i.headers && (s.headers = i.headers),
                e(null, s)
            } else
                e(i);
            return
        }
        !o.ReplicationConfiguration && (o.ReplicationConfiguration = {}),
        o.ReplicationConfiguration.Rule && (o.ReplicationConfiguration.Rules = util$2.makeArray(o.ReplicationConfiguration.Rule),
        delete o.ReplicationConfiguration.Rule),
        e(i, o)
    })
}
function deleteBucketReplication(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketReplication",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "replication"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketWebsite(a, e) {
    if (!a.WebsiteConfiguration) {
        e(util$2.error(new Error("missing param WebsiteConfiguration")));
        return
    }
    var i = util$2.clone(a.WebsiteConfiguration || {})
      , o = i.RoutingRules || i.RoutingRule || [];
    o = util$2.isArray(o) ? o : [o],
    delete i.RoutingRule,
    delete i.RoutingRules,
    o.length && (i.RoutingRules = {
        RoutingRule: o
    });
    var s = util$2.json2xml({
        WebsiteConfiguration: i
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketWebsite",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: s,
        action: "website",
        headers: c
    }, function(d, _) {
        if (d && d.statusCode === 204)
            return e(null, {
                statusCode: d.statusCode
            });
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getBucketWebsite(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketWebsite",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: a.Headers,
        action: "website"
    }, function(i, o) {
        if (i) {
            if (i.statusCode === 404 && i.error.Code === "NoSuchWebsiteConfiguration") {
                var s = {
                    WebsiteConfiguration: {},
                    statusCode: i.statusCode
                };
                i.headers && (s.headers = i.headers),
                e(null, s)
            } else
                e(i);
            return
        }
        var c = o.WebsiteConfiguration || {};
        if (c.RoutingRules) {
            var d = util$2.clone(c.RoutingRules.RoutingRule || []);
            d = util$2.makeArray(d),
            c.RoutingRules = d
        }
        e(null, {
            WebsiteConfiguration: c,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function deleteBucketWebsite(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketWebsite",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "website"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketReferer(a, e) {
    if (!a.RefererConfiguration) {
        e(util$2.error(new Error("missing param RefererConfiguration")));
        return
    }
    var i = util$2.clone(a.RefererConfiguration || {})
      , o = i.DomainList || {}
      , s = o.Domains || o.Domain || [];
    s = util$2.isArray(s) ? s : [s],
    s.length && (i.DomainList = {
        Domain: s
    });
    var c = util$2.json2xml({
        RefererConfiguration: i
    })
      , d = a.Headers;
    d["Content-Type"] = "application/xml",
    d["Content-MD5"] = util$2.binaryBase64(util$2.md5(c)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketReferer",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: c,
        action: "referer",
        headers: d
    }, function(_, b) {
        if (_ && _.statusCode === 204)
            return e(null, {
                statusCode: _.statusCode
            });
        if (_)
            return e(_);
        e(null, {
            statusCode: b.statusCode,
            headers: b.headers
        })
    })
}
function getBucketReferer(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketReferer",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: a.Headers,
        action: "referer"
    }, function(i, o) {
        if (i) {
            if (i.statusCode === 404 && i.error.Code === "NoSuchRefererConfiguration") {
                var s = {
                    WebsiteConfiguration: {},
                    statusCode: i.statusCode
                };
                i.headers && (s.headers = i.headers),
                e(null, s)
            } else
                e(i);
            return
        }
        var c = o.RefererConfiguration || {};
        if (c.DomainList) {
            var d = util$2.makeArray(c.DomainList.Domain || []);
            c.DomainList = {
                Domains: d
            }
        }
        e(null, {
            RefererConfiguration: c,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketDomain(a, e) {
    var i = a.DomainConfiguration || {}
      , o = i.DomainRule || a.DomainRule || [];
    o = util$2.clone(o);
    var s = util$2.json2xml({
        DomainConfiguration: {
            DomainRule: o
        }
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketDomain",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: s,
        action: "domain",
        headers: c
    }, function(d, _) {
        if (d && d.statusCode === 204)
            return e(null, {
                statusCode: d.statusCode
            });
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getBucketDomain(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketDomain",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "domain"
    }, function(i, o) {
        if (i)
            return e(i);
        var s = [];
        try {
            s = o.DomainConfiguration.DomainRule || []
        } catch {}
        s = util$2.clone(util$2.isArray(s) ? s : [s]),
        e(null, {
            DomainRule: s,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function deleteBucketDomain(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketDomain",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "domain"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketOrigin(a, e) {
    var i = a.OriginConfiguration || {}
      , o = i.OriginRule || a.OriginRule || [];
    o = util$2.clone(o);
    var s = util$2.json2xml({
        OriginConfiguration: {
            OriginRule: o
        }
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketOrigin",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: s,
        action: "origin",
        headers: c
    }, function(d, _) {
        if (d && d.statusCode === 204)
            return e(null, {
                statusCode: d.statusCode
            });
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getBucketOrigin(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketOrigin",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "origin"
    }, function(i, o) {
        if (i)
            return e(i);
        var s = [];
        try {
            s = o.OriginConfiguration.OriginRule || []
        } catch {}
        s = util$2.clone(util$2.isArray(s) ? s : [s]),
        e(null, {
            OriginRule: s,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function deleteBucketOrigin(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketOrigin",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "origin"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketLogging(a, e) {
    var i = util$2.json2xml({
        BucketLoggingStatus: a.BucketLoggingStatus || ""
    })
      , o = a.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(i)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketLogging",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: i,
        action: "logging",
        headers: o
    }, function(s, c) {
        if (s && s.statusCode === 204)
            return e(null, {
                statusCode: s.statusCode
            });
        if (s)
            return e(s);
        e(null, {
            statusCode: c.statusCode,
            headers: c.headers
        })
    })
}
function getBucketLogging(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketLogging",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "logging"
    }, function(i, o) {
        if (i)
            return e(i);
        e(null, {
            BucketLoggingStatus: o.BucketLoggingStatus,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketInventory(a, e) {
    var i = util$2.clone(a.InventoryConfiguration);
    if (i.OptionalFields) {
        var o = i.OptionalFields || [];
        i.OptionalFields = {
            Field: o
        }
    }
    if (i.Destination && i.Destination.COSBucketDestination && i.Destination.COSBucketDestination.Encryption) {
        var s = i.Destination.COSBucketDestination.Encryption;
        Object.keys(s).indexOf("SSECOS") > -1 && (s["SSE-COS"] = s.SSECOS,
        delete s.SSECOS)
    }
    var c = util$2.json2xml({
        InventoryConfiguration: i
    })
      , d = a.Headers;
    d["Content-Type"] = "application/xml",
    d["Content-MD5"] = util$2.binaryBase64(util$2.md5(c)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketInventory",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: c,
        action: "inventory",
        qs: {
            id: a.Id
        },
        headers: d
    }, function(_, b) {
        if (_ && _.statusCode === 204)
            return e(null, {
                statusCode: _.statusCode
            });
        if (_)
            return e(_);
        e(null, {
            statusCode: b.statusCode,
            headers: b.headers
        })
    })
}
function getBucketInventory(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketInventory",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "inventory",
        qs: {
            id: a.Id
        }
    }, function(i, o) {
        if (i)
            return e(i);
        var s = o.InventoryConfiguration;
        if (s && s.OptionalFields && s.OptionalFields.Field) {
            var c = s.OptionalFields.Field;
            util$2.isArray(c) || (c = [c]),
            s.OptionalFields = c
        }
        if (s.Destination && s.Destination.COSBucketDestination && s.Destination.COSBucketDestination.Encryption) {
            var d = s.Destination.COSBucketDestination.Encryption;
            Object.keys(d).indexOf("SSE-COS") > -1 && (d.SSECOS = d["SSE-COS"],
            delete d["SSE-COS"])
        }
        e(null, {
            InventoryConfiguration: s,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function listBucketInventory(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:ListBucketInventory",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "inventory",
        qs: {
            "continuation-token": a.ContinuationToken
        }
    }, function(i, o) {
        if (i)
            return e(i);
        var s = o.ListInventoryConfigurationResult
          , c = s.InventoryConfiguration || [];
        c = util$2.isArray(c) ? c : [c],
        delete s.InventoryConfiguration,
        util$2.each(c, function(d) {
            if (d && d.OptionalFields && d.OptionalFields.Field) {
                var _ = d.OptionalFields.Field;
                util$2.isArray(_) || (_ = [_]),
                d.OptionalFields = _
            }
            if (d.Destination && d.Destination.COSBucketDestination && d.Destination.COSBucketDestination.Encryption) {
                var b = d.Destination.COSBucketDestination.Encryption;
                Object.keys(b).indexOf("SSE-COS") > -1 && (b.SSECOS = b["SSE-COS"],
                delete b["SSE-COS"])
            }
        }),
        s.InventoryConfigurations = c,
        util$2.extend(s, {
            statusCode: o.statusCode,
            headers: o.headers
        }),
        e(null, s)
    })
}
function deleteBucketInventory(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketInventory",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "inventory",
        qs: {
            id: a.Id
        }
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function putBucketAccelerate(a, e) {
    if (!a.AccelerateConfiguration) {
        e(util$2.error(new Error("missing param AccelerateConfiguration")));
        return
    }
    var i = {
        AccelerateConfiguration: a.AccelerateConfiguration || {}
    }
      , o = util$2.json2xml(i)
      , s = {};
    s["Content-Type"] = "application/xml",
    s["Content-MD5"] = util$2.binaryBase64(util$2.md5(o)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketAccelerate",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: o,
        action: "accelerate",
        headers: s
    }, function(c, d) {
        if (c)
            return e(c);
        e(null, {
            statusCode: d.statusCode,
            headers: d.headers
        })
    })
}
function getBucketAccelerate(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketAccelerate",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        action: "accelerate"
    }, function(i, o) {
        i || !o.AccelerateConfiguration && (o.AccelerateConfiguration = {}),
        e(i, o)
    })
}
function putBucketEncryption(a, e) {
    var i = a.ServerSideEncryptionConfiguration || {}
      , o = i.Rule || i.Rules || []
      , s = util$2.json2xml({
        ServerSideEncryptionConfiguration: {
            Rule: o
        }
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketEncryption",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        body: s,
        action: "encryption",
        headers: c
    }, function(d, _) {
        if (d && d.statusCode === 204)
            return e(null, {
                statusCode: d.statusCode
            });
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getBucketEncryption(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketEncryption",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "encryption"
    }, function(i, o) {
        if (i) {
            if (i.statusCode === 404 && i.code === "NoSuchEncryptionConfiguration") {
                var s = {
                    EncryptionConfiguration: {
                        Rules: []
                    },
                    statusCode: i.statusCode
                };
                i.headers && (s.headers = i.headers),
                e(null, s)
            } else
                e(i);
            return
        }
        var c = util$2.makeArray(o.EncryptionConfiguration && o.EncryptionConfiguration.Rule || []);
        o.EncryptionConfiguration = {
            Rules: c
        },
        e(i, o)
    })
}
function deleteBucketEncryption(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketReplication",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "encryption"
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function headObject(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:HeadObject",
        method: "HEAD",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        VersionId: a.VersionId,
        headers: a.Headers
    }, function(i, o) {
        if (i) {
            var s = i.statusCode;
            return a.Headers["If-Modified-Since"] && s && s === 304 ? e(null, {
                NotModified: !0,
                statusCode: s
            }) : e(i)
        }
        o.ETag = util$2.attr(o.headers, "etag", ""),
        e(null, o)
    })
}
function listObjectVersions(a, e) {
    var i = {};
    i.prefix = a.Prefix || "",
    i.delimiter = a.Delimiter,
    i["key-marker"] = a.KeyMarker,
    i["version-id-marker"] = a.VersionIdMarker,
    i["max-keys"] = a.MaxKeys,
    i["encoding-type"] = a.EncodingType,
    submitRequest.call(this, {
        Action: "name/cos:GetBucketObjectVersions",
        ResourceKey: i.prefix,
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        qs: i,
        action: "versions"
    }, function(o, s) {
        if (o)
            return e(o);
        var c = s.ListVersionsResult || {}
          , d = c.DeleteMarker || [];
        d = util$2.isArray(d) ? d : [d];
        var _ = c.Version || [];
        _ = util$2.isArray(_) ? _ : [_];
        var b = util$2.clone(c);
        delete b.DeleteMarker,
        delete b.Version,
        util$2.extend(b, {
            DeleteMarkers: d,
            Versions: _,
            statusCode: s.statusCode,
            headers: s.headers
        }),
        e(null, b)
    })
}
function getObject(a, e) {
    var i = a.Query || {}
      , o = a.QueryString || ""
      , s = util$2.throttleOnProgress.call(this, 0, a.onProgress);
    i["response-content-type"] = a.ResponseContentType,
    i["response-content-language"] = a.ResponseContentLanguage,
    i["response-expires"] = a.ResponseExpires,
    i["response-cache-control"] = a.ResponseCacheControl,
    i["response-content-disposition"] = a.ResponseContentDisposition,
    i["response-content-encoding"] = a.ResponseContentEncoding,
    submitRequest.call(this, {
        Action: "name/cos:GetObject",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        VersionId: a.VersionId,
        DataType: a.DataType,
        headers: a.Headers,
        qs: i,
        qsStr: o,
        rawBody: !0,
        onDownloadProgress: s
    }, function(c, d) {
        if (s(null, !0),
        c) {
            var _ = c.statusCode;
            return a.Headers["If-Modified-Since"] && _ && _ === 304 ? e(null, {
                NotModified: !0
            }) : e(c)
        }
        e(null, {
            Body: d.body,
            ETag: util$2.attr(d.headers, "etag", ""),
            statusCode: d.statusCode,
            headers: d.headers
        })
    })
}
function putObject(a, e) {
    var i = this
      , o = a.ContentLength
      , s = util$2.throttleOnProgress.call(i, o, a.onProgress)
      , c = a.Headers;
    !c["Cache-Control"] && !c["cache-control"] && (c["Cache-Control"] = ""),
    !c["Content-Type"] && !c["content-type"] && (c["Content-Type"] = a.Body && a.Body.type || "");
    var d = a.UploadAddMetaMd5 || i.options.UploadAddMetaMd5 || i.options.UploadCheckContentMd5;
    util$2.getBodyMd5(d, a.Body, function(_) {
        _ && (i.options.UploadCheckContentMd5 && (c["Content-MD5"] = util$2.binaryBase64(_)),
        (a.UploadAddMetaMd5 || i.options.UploadAddMetaMd5) && (c["x-cos-meta-md5"] = _)),
        a.ContentLength !== void 0 && (c["Content-Length"] = a.ContentLength),
        s(null, !0),
        submitRequest.call(i, {
            Action: "name/cos:PutObject",
            TaskId: a.TaskId,
            method: "PUT",
            Bucket: a.Bucket,
            Region: a.Region,
            Key: a.Key,
            headers: a.Headers,
            qs: a.Query,
            body: a.Body,
            onProgress: s
        }, function(b, k) {
            if (b)
                return s(null, !0),
                e(b);
            s({
                loaded: o,
                total: o
            }, !0);
            var j = getUrl({
                ForcePathStyle: i.options.ForcePathStyle,
                protocol: i.options.Protocol,
                domain: i.options.Domain,
                bucket: a.Bucket,
                region: i.options.UseAccelerate ? "accelerate" : a.Region,
                object: a.Key
            });
            j = j.substr(j.indexOf("://") + 3),
            k.Location = j,
            k.ETag = util$2.attr(k.headers, "etag", ""),
            e(null, k)
        })
    }, a.onHashProgress)
}
function deleteObject(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteObject",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: a.Headers,
        VersionId: a.VersionId,
        action: a.Recursive ? "recursive" : ""
    }, function(i, o) {
        if (i) {
            var s = i.statusCode;
            return s && s === 404 ? e(null, {
                BucketNotFound: !0,
                statusCode: s
            }) : e(i)
        }
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function getObjectAcl(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetObjectACL",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: a.Headers,
        action: "acl"
    }, function(i, o) {
        if (i)
            return e(i);
        var s = o.AccessControlPolicy || {}
          , c = s.Owner || {}
          , d = s.AccessControlList && s.AccessControlList.Grant || [];
        d = util$2.isArray(d) ? d : [d];
        var _ = decodeAcl(s);
        delete _.GrantWrite,
        o.headers && o.headers["x-cos-acl"] && (_.ACL = o.headers["x-cos-acl"]),
        _ = util$2.extend(_, {
            Owner: c,
            Grants: d,
            statusCode: o.statusCode,
            headers: o.headers
        }),
        e(null, _)
    })
}
function putObjectAcl(a, e) {
    var i = a.Headers
      , o = "";
    if (a.AccessControlPolicy) {
        var s = util$2.clone(a.AccessControlPolicy || {})
          , c = s.Grants || s.Grant;
        c = util$2.isArray(c) ? c : [c],
        delete s.Grant,
        delete s.Grants,
        s.AccessControlList = {
            Grant: c
        },
        o = util$2.json2xml({
            AccessControlPolicy: s
        }),
        i["Content-Type"] = "application/xml",
        i["Content-MD5"] = util$2.binaryBase64(util$2.md5(o))
    }
    util$2.each(i, function(d, _) {
        _.indexOf("x-cos-grant-") === 0 && (i[_] = uniqGrant(i[_]))
    }),
    submitRequest.call(this, {
        Action: "name/cos:PutObjectACL",
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        action: "acl",
        headers: i,
        body: o
    }, function(d, _) {
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function optionsObject(a, e) {
    var i = a.Headers;
    i.Origin = a.Origin,
    i["Access-Control-Request-Method"] = a.AccessControlRequestMethod,
    i["Access-Control-Request-Headers"] = a.AccessControlRequestHeaders,
    submitRequest.call(this, {
        Action: "name/cos:OptionsObject",
        method: "OPTIONS",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: i
    }, function(o, s) {
        if (o)
            return o.statusCode && o.statusCode === 403 ? e(null, {
                OptionsForbidden: !0,
                statusCode: o.statusCode
            }) : e(o);
        var c = s.headers || {};
        e(null, {
            AccessControlAllowOrigin: c["access-control-allow-origin"],
            AccessControlAllowMethods: c["access-control-allow-methods"],
            AccessControlAllowHeaders: c["access-control-allow-headers"],
            AccessControlExposeHeaders: c["access-control-expose-headers"],
            AccessControlMaxAge: c["access-control-max-age"],
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function putObjectCopy(a, e) {
    var i = this
      , o = a.Headers;
    !o["Cache-Control"] && !o["cache-control"] && (o["Cache-Control"] = "");
    var s = a.CopySource || ""
      , c = util$2.getSourceParams.call(this, s);
    if (!c) {
        e(util$2.error(new Error("CopySource format error")));
        return
    }
    var d = c[1]
      , _ = c[3]
      , b = decodeURIComponent(c[4]);
    submitRequest.call(this, {
        Scope: [{
            action: "name/cos:GetObject",
            bucket: d,
            region: _,
            prefix: b
        }, {
            action: "name/cos:PutObject",
            bucket: a.Bucket,
            region: a.Region,
            prefix: a.Key
        }],
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        VersionId: a.VersionId,
        headers: a.Headers
    }, function(k, j) {
        if (k)
            return e(k);
        var $ = util$2.clone(j.CopyObjectResult || {})
          , _e = getUrl({
            ForcePathStyle: i.options.ForcePathStyle,
            protocol: i.options.Protocol,
            domain: i.options.Domain,
            bucket: a.Bucket,
            region: a.Region,
            object: a.Key,
            isLocation: !0
        });
        util$2.extend($, {
            Location: _e,
            statusCode: j.statusCode,
            headers: j.headers
        }),
        e(null, $)
    })
}
function uploadPartCopy(a, e) {
    var i = a.CopySource || ""
      , o = util$2.getSourceParams.call(this, i);
    if (!o) {
        e(util$2.error(new Error("CopySource format error")));
        return
    }
    var s = o[1]
      , c = o[3]
      , d = decodeURIComponent(o[4]);
    submitRequest.call(this, {
        Scope: [{
            action: "name/cos:GetObject",
            bucket: s,
            region: c,
            prefix: d
        }, {
            action: "name/cos:PutObject",
            bucket: a.Bucket,
            region: a.Region,
            prefix: a.Key
        }],
        method: "PUT",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        VersionId: a.VersionId,
        qs: {
            partNumber: a.PartNumber,
            uploadId: a.UploadId
        },
        headers: a.Headers
    }, function(_, b) {
        if (_)
            return e(_);
        var k = util$2.clone(b.CopyPartResult || {});
        util$2.extend(k, {
            statusCode: b.statusCode,
            headers: b.headers
        }),
        e(null, k)
    })
}
function deleteMultipleObject(a, e) {
    var i = a.Objects || []
      , o = a.Quiet;
    i = util$2.isArray(i) ? i : [i];
    var s = util$2.json2xml({
        Delete: {
            Object: i,
            Quiet: o || !1
        }
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s));
    var d = util$2.map(i, function(_) {
        return {
            action: "name/cos:DeleteObject",
            bucket: a.Bucket,
            region: a.Region,
            prefix: _.Key
        }
    });
    submitRequest.call(this, {
        Scope: d,
        method: "POST",
        Bucket: a.Bucket,
        Region: a.Region,
        body: s,
        action: "delete",
        headers: c
    }, function(_, b) {
        if (_)
            return e(_);
        var k = b.DeleteResult || {}
          , j = k.Deleted || []
          , $ = k.Error || [];
        j = util$2.isArray(j) ? j : [j],
        $ = util$2.isArray($) ? $ : [$];
        var _e = util$2.clone(k);
        util$2.extend(_e, {
            Error: $,
            Deleted: j,
            statusCode: b.statusCode,
            headers: b.headers
        }),
        e(null, _e)
    })
}
function restoreObject(a, e) {
    var i = a.Headers;
    if (!a.RestoreRequest) {
        e(util$2.error(new Error("missing param RestoreRequest")));
        return
    }
    var o = a.RestoreRequest || {}
      , s = util$2.json2xml({
        RestoreRequest: o
    });
    i["Content-Type"] = "application/xml",
    i["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:RestoreObject",
        method: "POST",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        VersionId: a.VersionId,
        body: s,
        action: "restore",
        headers: i
    }, e)
}
function putObjectTagging(a, e) {
    var i = a.Tagging || {}
      , o = i.TagSet || i.Tags || a.Tags || [];
    o = util$2.clone(util$2.isArray(o) ? o : [o]);
    var s = util$2.json2xml({
        Tagging: {
            TagSet: {
                Tag: o
            }
        }
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:PutObjectTagging",
        method: "PUT",
        Bucket: a.Bucket,
        Key: a.Key,
        Region: a.Region,
        body: s,
        action: "tagging",
        headers: c,
        VersionId: a.VersionId
    }, function(d, _) {
        if (d && d.statusCode === 204)
            return e(null, {
                statusCode: d.statusCode
            });
        if (d)
            return e(d);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers
        })
    })
}
function getObjectTagging(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetObjectTagging",
        method: "GET",
        Key: a.Key,
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        action: "tagging",
        VersionId: a.VersionId
    }, function(i, o) {
        if (i) {
            if (i.statusCode === 404 && i.error && (i.error === "Not Found" || i.error.Code === "NoSuchTagSet")) {
                var s = {
                    Tags: [],
                    statusCode: i.statusCode
                };
                i.headers && (s.headers = i.headers),
                e(null, s)
            } else
                e(i);
            return
        }
        var c = [];
        try {
            c = o.Tagging.TagSet.Tag || []
        } catch {}
        c = util$2.clone(util$2.isArray(c) ? c : [c]),
        e(null, {
            Tags: c,
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function deleteObjectTagging(a, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteObjectTagging",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: a.Headers,
        action: "tagging",
        VersionId: a.VersionId
    }, function(i, o) {
        if (i && i.statusCode === 204)
            return e(null, {
                statusCode: i.statusCode
            });
        if (i)
            return e(i);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function selectObjectContent(a, e) {
    var i = a.SelectType;
    if (!i)
        return e(util$2.error(new Error("missing param SelectType")));
    var o = a.SelectRequest || {}
      , s = util$2.json2xml({
        SelectRequest: o
    })
      , c = a.Headers;
    c["Content-Type"] = "application/xml",
    c["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:GetObject",
        method: "POST",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: a.Headers,
        action: "select",
        qs: {
            "select-type": a.SelectType
        },
        VersionId: a.VersionId,
        body: s,
        DataType: "arraybuffer",
        rawBody: !0
    }, function(d, _) {
        if (d && d.statusCode === 204)
            return e(null, {
                statusCode: d.statusCode
            });
        if (d)
            return e(d);
        var b = util$2.parseSelectPayload(_.body);
        e(null, {
            statusCode: _.statusCode,
            headers: _.headers,
            Body: b.body,
            Payload: b.payload
        })
    })
}
function multipartInit(a, e) {
    var i = this
      , o = a.Headers;
    !o["Cache-Control"] && !o["cache-control"] && (o["Cache-Control"] = ""),
    !o["Content-Type"] && !o["content-type"] && (o["Content-Type"] = a.Body && a.Body.type || ""),
    util$2.getBodyMd5(a.Body && (a.UploadAddMetaMd5 || i.options.UploadAddMetaMd5), a.Body, function(s) {
        s && (a.Headers["x-cos-meta-md5"] = s),
        submitRequest.call(i, {
            Action: "name/cos:InitiateMultipartUpload",
            method: "POST",
            Bucket: a.Bucket,
            Region: a.Region,
            Key: a.Key,
            action: "uploads",
            headers: a.Headers,
            qs: a.Query
        }, function(c, d) {
            if (c)
                return e(c);
            if (d = util$2.clone(d || {}),
            d && d.InitiateMultipartUploadResult)
                return e(null, util$2.extend(d.InitiateMultipartUploadResult, {
                    statusCode: d.statusCode,
                    headers: d.headers
                }));
            e(null, d)
        })
    }, a.onHashProgress)
}
function multipartUpload(a, e) {
    var i = this;
    util$2.getFileSize("multipartUpload", a, function() {
        util$2.getBodyMd5(i.options.UploadCheckContentMd5, a.Body, function(o) {
            o && (a.Headers["Content-MD5"] = util$2.binaryBase64(o)),
            submitRequest.call(i, {
                Action: "name/cos:UploadPart",
                TaskId: a.TaskId,
                method: "PUT",
                Bucket: a.Bucket,
                Region: a.Region,
                Key: a.Key,
                qs: {
                    partNumber: a.PartNumber,
                    uploadId: a.UploadId
                },
                headers: a.Headers,
                onProgress: a.onProgress,
                body: a.Body || null
            }, function(s, c) {
                if (s)
                    return e(s);
                e(null, {
                    ETag: util$2.attr(c.headers, "etag", ""),
                    statusCode: c.statusCode,
                    headers: c.headers
                })
            })
        })
    })
}
function multipartComplete(a, e) {
    for (var i = this, o = a.UploadId, s = a.Parts, c = 0, d = s.length; c < d; c++)
        s[c].ETag && s[c].ETag.indexOf('"') === 0 || (s[c].ETag = '"' + s[c].ETag + '"');
    var _ = util$2.json2xml({
        CompleteMultipartUpload: {
            Part: s
        }
    });
    _ = _.replace(/\n\s*/g, "");
    var b = a.Headers;
    b["Content-Type"] = "application/xml",
    b["Content-MD5"] = util$2.binaryBase64(util$2.md5(_)),
    submitRequest.call(this, {
        Action: "name/cos:CompleteMultipartUpload",
        method: "POST",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        qs: {
            uploadId: o
        },
        body: _,
        headers: b
    }, function(k, j) {
        if (k)
            return e(k);
        var $ = getUrl({
            ForcePathStyle: i.options.ForcePathStyle,
            protocol: i.options.Protocol,
            domain: i.options.Domain,
            bucket: a.Bucket,
            region: a.Region,
            object: a.Key,
            isLocation: !0
        })
          , _e = j.CompleteMultipartUploadResult || {};
        _e.ProcessResults && _e && _e.ProcessResults && (_e.UploadResult = {
            OriginalInfo: {
                Key: _e.Key,
                Location: $,
                ETag: _e.ETag,
                ImageInfo: _e.ImageInfo
            },
            ProcessResults: _e.ProcessResults
        },
        delete _e.ImageInfo,
        delete _e.ProcessResults);
        var et = util$2.extend(_e, {
            Location: $,
            statusCode: j.statusCode,
            headers: j.headers
        });
        e(null, et)
    })
}
function multipartList(a, e) {
    var i = {};
    i.delimiter = a.Delimiter,
    i["encoding-type"] = a.EncodingType,
    i.prefix = a.Prefix || "",
    i["max-uploads"] = a.MaxUploads,
    i["key-marker"] = a.KeyMarker,
    i["upload-id-marker"] = a.UploadIdMarker,
    i = util$2.clearKey(i),
    submitRequest.call(this, {
        Action: "name/cos:ListMultipartUploads",
        ResourceKey: i.prefix,
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        headers: a.Headers,
        qs: i,
        action: "uploads"
    }, function(o, s) {
        if (o)
            return e(o);
        if (s && s.ListMultipartUploadsResult) {
            var c = s.ListMultipartUploadsResult.Upload || [];
            c = util$2.isArray(c) ? c : [c],
            s.ListMultipartUploadsResult.Upload = c
        }
        var d = util$2.clone(s.ListMultipartUploadsResult || {});
        util$2.extend(d, {
            statusCode: s.statusCode,
            headers: s.headers
        }),
        e(null, d)
    })
}
function multipartListPart(a, e) {
    var i = {};
    i.uploadId = a.UploadId,
    i["encoding-type"] = a.EncodingType,
    i["max-parts"] = a.MaxParts,
    i["part-number-marker"] = a.PartNumberMarker,
    submitRequest.call(this, {
        Action: "name/cos:ListParts",
        method: "GET",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: a.Headers,
        qs: i
    }, function(o, s) {
        if (o)
            return e(o);
        var c = s.ListPartsResult || {}
          , d = c.Part || [];
        d = util$2.isArray(d) ? d : [d],
        c.Part = d;
        var _ = util$2.clone(c);
        util$2.extend(_, {
            statusCode: s.statusCode,
            headers: s.headers
        }),
        e(null, _)
    })
}
function multipartAbort(a, e) {
    var i = {};
    i.uploadId = a.UploadId,
    submitRequest.call(this, {
        Action: "name/cos:AbortMultipartUpload",
        method: "DELETE",
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        headers: a.Headers,
        qs: i
    }, function(o, s) {
        if (o)
            return e(o);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function request(a, e) {
    submitRequest.call(this, {
        method: a.Method,
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        action: a.Action,
        headers: a.Headers,
        qs: a.Query,
        body: a.Body,
        Url: a.Url,
        rawBody: a.RawBody,
        DataType: a.DataType
    }, function(i, o) {
        if (i)
            return e(i);
        o && o.body && (o.Body = o.body,
        delete o.body),
        e(i, o)
    })
}
function appendObject(a, e) {
    var i = a.Headers;
    !i["Cache-Control"] && !i["cache-control"] && (i["Cache-Control"] = ""),
    !i["Content-Type"] && !i["content-type"] && (i["Content-Type"] = a.Body && a.Body.type || ""),
    submitRequest.call(this, {
        Action: "name/cos:AppendObject",
        method: "POST",
        Bucket: a.Bucket,
        Region: a.Region,
        action: "append",
        Key: a.Key,
        body: a.Body,
        qs: {
            position: a.Position
        },
        headers: a.Headers
    }, function(o, s) {
        if (o)
            return e(o);
        e(null, s)
    })
}
function getAuth(a) {
    var e = this;
    return util$2.getAuth({
        SecretId: a.SecretId || this.options.SecretId || "",
        SecretKey: a.SecretKey || this.options.SecretKey || "",
        Bucket: a.Bucket,
        Region: a.Region,
        Method: a.Method,
        Key: a.Key,
        Query: a.Query,
        Headers: a.Headers,
        Expires: a.Expires,
        UseRawKey: e.options.UseRawKey,
        SystemClockOffset: e.options.SystemClockOffset
    })
}
function getObjectUrl(a, e) {
    var i = this
      , o = a.UseAccelerate === void 0 ? i.options.UseAccelerate : a.UseAccelerate
      , s = getUrl({
        ForcePathStyle: i.options.ForcePathStyle,
        protocol: a.Protocol || i.options.Protocol,
        domain: a.Domain || i.options.Domain,
        bucket: a.Bucket,
        region: o ? "accelerate" : a.Region,
        object: a.Key
    })
      , c = "";
    a.Query && (c += util$2.obj2str(a.Query)),
    a.QueryString && (c += (c ? "&" : "") + a.QueryString);
    var d = s;
    if (a.Sign !== void 0 && !a.Sign)
        return c && (d += "?" + c),
        e(null, {
            Url: d
        }),
        d;
    var _ = getSignHost.call(this, {
        Bucket: a.Bucket,
        Region: a.Region,
        UseAccelerate: a.UseAccelerate,
        Url: s
    })
      , b = getAuthorizationAsync.call(this, {
        Action: (a.Method || "").toUpperCase() === "PUT" ? "name/cos:PutObject" : "name/cos:GetObject",
        Bucket: a.Bucket || "",
        Region: a.Region || "",
        Method: a.Method || "get",
        Key: a.Key,
        Expires: a.Expires,
        Headers: a.Headers,
        Query: a.Query,
        SignHost: _,
        ForceSignHost: a.ForceSignHost === !1 ? !1 : i.options.ForceSignHost
    }, function(k, j) {
        if (!!e) {
            if (k) {
                e(k);
                return
            }
            var $ = function(et) {
                var tt = et.match(/q-url-param-list.*?(?=&)/g)[0]
                  , rt = "q-url-param-list=" + encodeURIComponent(tt.replace(/q-url-param-list=/, "")).toLowerCase()
                  , it = new RegExp(tt,"g")
                  , nt = et.replace(it, rt);
                return nt
            }
              , _e = s;
            _e += "?" + (j.Authorization.indexOf("q-signature") > -1 ? $(j.Authorization) : "sign=" + encodeURIComponent(j.Authorization)),
            j.SecurityToken && (_e += "&x-cos-security-token=" + j.SecurityToken),
            j.ClientIP && (_e += "&clientIP=" + j.ClientIP),
            j.ClientUA && (_e += "&clientUA=" + j.ClientUA),
            j.Token && (_e += "&token=" + j.Token),
            c && (_e += "&" + c),
            setTimeout(function() {
                e(null, {
                    Url: _e
                })
            })
        }
    });
    return b ? (d += "?" + b.Authorization + (b.SecurityToken ? "&x-cos-security-token=" + b.SecurityToken : ""),
    c && (d += "&" + c)) : c && (d += "?" + c),
    d
}
function decodeAcl(a) {
    var e = {
        GrantFullControl: [],
        GrantWrite: [],
        GrantRead: [],
        GrantReadAcp: [],
        GrantWriteAcp: [],
        ACL: ""
    }
      , i = {
        FULL_CONTROL: "GrantFullControl",
        WRITE: "GrantWrite",
        READ: "GrantRead",
        READ_ACP: "GrantReadAcp",
        WRITE_ACP: "GrantWriteAcp"
    }
      , o = a && a.AccessControlList || {}
      , s = o.Grant;
    s && (s = util$2.isArray(s) ? s : [s]);
    var c = {
        READ: 0,
        WRITE: 0,
        FULL_CONTROL: 0
    };
    return s && s.length && util$2.each(s, function(d) {
        d.Grantee.ID === "qcs::cam::anyone:anyone" || d.Grantee.URI === "http://cam.qcloud.com/groups/global/AllUsers" ? c[d.Permission] = 1 : d.Grantee.ID !== a.Owner.ID && e[i[d.Permission]].push('id="' + d.Grantee.ID + '"')
    }),
    c.FULL_CONTROL || c.WRITE && c.READ ? e.ACL = "public-read-write" : c.READ ? e.ACL = "public-read" : e.ACL = "private",
    util$2.each(i, function(d) {
        e[d] = uniqGrant(e[d].join(","))
    }),
    e
}
function uniqGrant(a) {
    var e = a.split(","), i = {}, o, s;
    for (o = 0; o < e.length; )
        s = e[o].trim(),
        i[s] ? e.splice(o, 1) : (i[s] = !0,
        e[o] = s,
        o++);
    return e.join(",")
}
function getUrl(a) {
    var e = a.region || ""
      , i = a.bucket || ""
      , o = i.substr(0, i.lastIndexOf("-"))
      , s = i.substr(i.lastIndexOf("-") + 1)
      , c = a.domain
      , d = a.object;
    typeof c == "function" && (c = c({
        Bucket: i,
        Region: e
    }));
    var _ = a.protocol || (util$2.isBrowser && location.protocol === "http:" ? "http:" : "https:");
    c || (["cn-south", "cn-south-2", "cn-north", "cn-east", "cn-southwest", "sg"].indexOf(e) > -1 ? c = "{Region}.myqcloud.com" : c = "cos.{Region}.myqcloud.com",
    a.ForcePathStyle || (c = "{Bucket}." + c)),
    c = c.replace(/\{\{AppId\}\}/ig, s).replace(/\{\{Bucket\}\}/ig, o).replace(/\{\{Region\}\}/ig, e).replace(/\{\{.*?\}\}/ig, ""),
    c = c.replace(/\{AppId\}/ig, s).replace(/\{BucketName\}/ig, o).replace(/\{Bucket\}/ig, i).replace(/\{Region\}/ig, e).replace(/\{.*?\}/ig, ""),
    /^[a-zA-Z]+:\/\//.test(c) || (c = _ + "//" + c),
    c.slice(-1) === "/" && (c = c.slice(0, -1));
    var b = c;
    return a.ForcePathStyle && (b += "/" + i),
    b += "/",
    d && (b += util$2.camSafeUrlEncode(d).replace(/%2F/g, "/")),
    a.isLocation && (b = b.replace(/^https?:\/\//, "")),
    b
}
var getSignHost = function(a) {
    if (!a.Bucket || !a.Region)
        return "";
    var e = a.UseAccelerate === void 0 ? this.options.UseAccelerate : a.UseAccelerate
      , i = a.Url || getUrl({
        ForcePathStyle: this.options.ForcePathStyle,
        protocol: this.options.Protocol,
        domain: this.options.Domain,
        bucket: a.Bucket,
        region: e ? "accelerate" : a.Region
    })
      , o = i.replace(/^https?:\/\/([^/]+)(\/.*)?$/, "$1")
      , s = new RegExp("^([a-z\\d-]+-\\d+\\.)?(cos|cosv6|ci|pic)\\.([a-z\\d-]+)\\.myqcloud\\.com$");
    return s.test(o) ? o : ""
};
function getAuthorizationAsync(a, e) {
    var i = util$2.clone(a.Headers)
      , o = "";
    util$2.each(i, function(at, st) {
        (at === "" || ["content-type", "cache-control", "expires"].indexOf(st.toLowerCase()) > -1) && delete i[st],
        st.toLowerCase() === "host" && (o = at)
    });
    var s = a.ForceSignHost !== !1;
    !o && a.SignHost && s && (i.Host = a.SignHost);
    var c = !1
      , d = function(at, st) {
        c || (c = !0,
        st && st.XCosSecurityToken && !st.SecurityToken && (st = util$2.clone(st),
        st.SecurityToken = st.XCosSecurityToken,
        delete st.XCosSecurityToken),
        e && e(at, st))
    }
      , _ = this
      , b = a.Bucket || ""
      , k = a.Region || ""
      , j = a.Key || "";
    _.options.ForcePathStyle && b && (j = b + "/" + j);
    var $ = "/" + j
      , _e = {}
      , et = a.Scope;
    if (!et) {
        var tt = a.Action || ""
          , rt = a.ResourceKey || a.Key || "";
        et = a.Scope || [{
            action: tt,
            bucket: b,
            region: k,
            prefix: rt
        }]
    }
    var it = util$2.md5(JSON.stringify(et));
    _._StsCache = _._StsCache || [],
    function() {
        var at, st;
        for (at = _._StsCache.length - 1; at >= 0; at--) {
            st = _._StsCache[at];
            var ut = Math.round(util$2.getSkewTime(_.options.SystemClockOffset) / 1e3) + 30;
            if (st.StartTime && ut < st.StartTime || ut >= st.ExpiredTime) {
                _._StsCache.splice(at, 1);
                continue
            }
            if (!st.ScopeLimit || st.ScopeLimit && st.ScopeKey === it) {
                _e = st;
                break
            }
        }
    }();
    var nt = function() {
        var at = _e.StartTime && _e.ExpiredTime ? _e.StartTime + ";" + _e.ExpiredTime : ""
          , st = util$2.getAuth({
            SecretId: _e.TmpSecretId,
            SecretKey: _e.TmpSecretKey,
            Method: a.Method,
            Pathname: $,
            Query: a.Query,
            Headers: i,
            Expires: a.Expires,
            UseRawKey: _.options.UseRawKey,
            SystemClockOffset: _.options.SystemClockOffset,
            KeyTime: at,
            ForceSignHost: _.options.ForceSignHost
        })
          , ut = {
            Authorization: st,
            SecurityToken: _e.SecurityToken || _e.XCosSecurityToken || "",
            Token: _e.Token || "",
            ClientIP: _e.ClientIP || "",
            ClientUA: _e.ClientUA || ""
        };
        d(null, ut)
    }
      , ot = function(at) {
        if (at.Authorization) {
            var st = !1
              , ut = at.Authorization;
            if (ut)
                if (ut.indexOf(" ") > -1)
                    st = !1;
                else if (ut.indexOf("q-sign-algorithm=") > -1 && ut.indexOf("q-ak=") > -1 && ut.indexOf("q-sign-time=") > -1 && ut.indexOf("q-key-time=") > -1 && ut.indexOf("q-url-param-list=") > -1)
                    st = !0;
                else
                    try {
                        ut = atob(ut),
                        ut.indexOf("a=") > -1 && ut.indexOf("k=") > -1 && ut.indexOf("t=") > -1 && ut.indexOf("r=") > -1 && ut.indexOf("b=") > -1 && (st = !0)
                    } catch {}
            if (!st)
                return util$2.error(new Error("getAuthorization callback params format error"))
        } else {
            if (!at.TmpSecretId)
                return util$2.error(new Error('getAuthorization callback params missing "TmpSecretId"'));
            if (!at.TmpSecretKey)
                return util$2.error(new Error('getAuthorization callback params missing "TmpSecretKey"'));
            if (!at.SecurityToken && !at.XCosSecurityToken)
                return util$2.error(new Error('getAuthorization callback params missing "SecurityToken"'));
            if (!at.ExpiredTime)
                return util$2.error(new Error('getAuthorization callback params missing "ExpiredTime"'));
            if (at.ExpiredTime && at.ExpiredTime.toString().length !== 10)
                return util$2.error(new Error('getAuthorization callback params "ExpiredTime" should be 10 digits'));
            if (at.StartTime && at.StartTime.toString().length !== 10)
                return util$2.error(new Error('getAuthorization callback params "StartTime" should be 10 StartTime'))
        }
        return !1
    };
    if (_e.ExpiredTime && _e.ExpiredTime - util$2.getSkewTime(_.options.SystemClockOffset) / 1e3 > 60)
        nt();
    else if (_.options.getAuthorization)
        _.options.getAuthorization.call(_, {
            Bucket: b,
            Region: k,
            Method: a.Method,
            Key: j,
            Pathname: $,
            Query: a.Query,
            Headers: i,
            Scope: et,
            SystemClockOffset: _.options.SystemClockOffset,
            ForceSignHost: _.options.ForceSignHost
        }, function(at) {
            typeof at == "string" && (at = {
                Authorization: at
            });
            var st = ot(at);
            if (st)
                return d(st);
            at.Authorization ? d(null, at) : (_e = at || {},
            _e.Scope = et,
            _e.ScopeKey = it,
            _._StsCache.push(_e),
            nt())
        });
    else if (_.options.getSTS)
        _.options.getSTS.call(_, {
            Bucket: b,
            Region: k
        }, function(at) {
            _e = at || {},
            _e.Scope = et,
            _e.ScopeKey = it,
            _e.TmpSecretId || (_e.TmpSecretId = _e.SecretId),
            _e.TmpSecretKey || (_e.TmpSecretKey = _e.SecretKey);
            var st = ot(_e);
            if (st)
                return d(st);
            _._StsCache.push(_e),
            nt()
        });
    else
        return function() {
            var at = util$2.getAuth({
                SecretId: a.SecretId || _.options.SecretId,
                SecretKey: a.SecretKey || _.options.SecretKey,
                Method: a.Method,
                Pathname: $,
                Query: a.Query,
                Headers: i,
                Expires: a.Expires,
                UseRawKey: _.options.UseRawKey,
                SystemClockOffset: _.options.SystemClockOffset,
                ForceSignHost: _.options.ForceSignHost
            })
              , st = {
                Authorization: at,
                SecurityToken: _.options.SecurityToken || _.options.XCosSecurityToken
            };
            return d(null, st),
            st
        }();
    return ""
}
function allowRetry(a) {
    var e = !1
      , i = !1
      , o = a.headers && (a.headers.date || a.headers.Date) || a.error && a.error.ServerTime;
    try {
        var s = a.error.Code
          , c = a.error.Message;
        (s === "RequestTimeTooSkewed" || s === "AccessDenied" && c === "Request has expired") && (i = !0)
    } catch {}
    if (a)
        if (i && o) {
            var d = Date.parse(o);
            this.options.CorrectClockSkew && Math.abs(util$2.getSkewTime(this.options.SystemClockOffset) - d) >= 3e4 && (console.error("error: Local time is too skewed."),
            this.options.SystemClockOffset = d - Date.now(),
            e = !0)
        } else
            Math.floor(a.statusCode / 100) === 5 && (e = !0);
    return e
}
function submitRequest(a, e) {
    var i = this;
    !a.headers && (a.headers = {}),
    !a.qs && (a.qs = {}),
    a.VersionId && (a.qs.versionId = a.VersionId),
    a.qs = util$2.clearKey(a.qs),
    a.headers && (a.headers = util$2.clearKey(a.headers)),
    a.qs && (a.qs = util$2.clearKey(a.qs));
    var o = util$2.clone(a.qs);
    a.action && (o[a.action] = "");
    var s = a.url || a.Url
      , c = a.SignHost || getSignHost.call(this, {
        Bucket: a.Bucket,
        Region: a.Region,
        Url: s
    })
      , d = function(_) {
        var b = i.options.SystemClockOffset;
        getAuthorizationAsync.call(i, {
            Bucket: a.Bucket || "",
            Region: a.Region || "",
            Method: a.method,
            Key: a.Key,
            Query: o,
            Headers: a.headers,
            SignHost: c,
            Action: a.Action,
            ResourceKey: a.ResourceKey,
            Scope: a.Scope,
            ForceSignHost: i.options.ForceSignHost
        }, function(k, j) {
            if (k) {
                e(k);
                return
            }
            a.AuthData = j,
            _submitRequest.call(i, a, function($, _e) {
                $ && _ < 2 && (b !== i.options.SystemClockOffset || allowRetry.call(i, $)) ? (a.headers && (delete a.headers.Authorization,
                delete a.headers.token,
                delete a.headers.clientIP,
                delete a.headers.clientUA,
                a.headers["x-cos-security-token"] && delete a.headers["x-cos-security-token"],
                a.headers["x-ci-security-token"] && delete a.headers["x-ci-security-token"]),
                d(_ + 1)) : e($, _e)
            })
        })
    };
    d(1)
}
function _submitRequest(a, e) {
    var i = this
      , o = a.TaskId;
    if (!(o && !i._isRunningTask(o))) {
        var s = a.Bucket
          , c = a.Region
          , d = a.Key
          , _ = a.method || "GET"
          , b = a.Url || a.url
          , k = a.body
          , j = a.rawBody;
        i.options.UseAccelerate && (c = "accelerate"),
        b = b || getUrl({
            ForcePathStyle: i.options.ForcePathStyle,
            protocol: i.options.Protocol,
            domain: i.options.Domain,
            bucket: s,
            region: c,
            object: d
        }),
        a.action && (b = b + "?" + a.action),
        a.qsStr && (b.indexOf("?") > -1 ? b = b + "&" + a.qsStr : b = b + "?" + a.qsStr);
        var $ = {
            method: _,
            url: b,
            headers: a.headers,
            qs: a.qs,
            body: k
        }
          , _e = "x-cos-security-token";
        if (util$2.isCIHost(b) && (_e = "x-ci-security-token"),
        $.headers.Authorization = a.AuthData.Authorization,
        a.AuthData.Token && ($.headers.token = a.AuthData.Token),
        a.AuthData.ClientIP && ($.headers.clientIP = a.AuthData.ClientIP),
        a.AuthData.ClientUA && ($.headers.clientUA = a.AuthData.ClientUA),
        a.AuthData.SecurityToken && ($.headers[_e] = a.AuthData.SecurityToken),
        $.headers && ($.headers = util$2.clearKey($.headers)),
        $ = util$2.clearKey($),
        a.onProgress && typeof a.onProgress == "function") {
            var et = k && (k.size || k.length) || 0;
            $.onProgress = function(it) {
                if (!(o && !i._isRunningTask(o))) {
                    var nt = it ? it.loaded : 0;
                    a.onProgress({
                        loaded: nt,
                        total: et
                    })
                }
            }
        }
        a.onDownloadProgress && ($.onDownloadProgress = a.onDownloadProgress),
        a.DataType && ($.dataType = a.DataType),
        this.options.Timeout && ($.timeout = this.options.Timeout),
        i.options.ForcePathStyle && ($.pathStyle = i.options.ForcePathStyle),
        i.emit("before-send", $);
        var tt = (i.options.Request || REQUEST)($, function(it) {
            if (it.error !== "abort") {
                var nt = {
                    options: $,
                    error: at,
                    statusCode: ot && ot.statusCode || 0,
                    headers: ot && ot.headers || {},
                    body: st
                };
                i.emit("after-receive", nt),
                at = nt.error,
                st = nt.body,
                ot = {
                    statusCode: nt.statusCode,
                    headers: nt.headers
                },
                i.emit("after-receive", it);
                var ot = {
                    statusCode: it.statusCode,
                    statusMessage: it.statusMessage,
                    headers: it.headers
                }, at = it.error, st = it.body, ut, ct = function(dt, _t) {
                    if (o && i.off("inner-kill-task", rt),
                    !ut) {
                        ut = !0;
                        var mt = {};
                        ot && ot.statusCode && (mt.statusCode = ot.statusCode),
                        ot && ot.headers && (mt.headers = ot.headers),
                        dt ? (dt = util$2.extend(dt || {}, mt),
                        e(dt, null)) : (_t = util$2.extend(_t || {}, mt),
                        e(null, _t)),
                        tt = null
                    }
                };
                if (at)
                    return ct(util$2.error(at));
                var lt = ot.statusCode
                  , ft = Math.floor(lt / 100) === 2;
                if (j && ft)
                    return ct(null, {
                        body: st
                    });
                var ht;
                try {
                    ht = st && st.indexOf("<") > -1 && st.indexOf(">") > -1 && util$2.xml2json(st) || {}
                } catch {
                    ht = {}
                }
                var pt = ht && ht.Error;
                ft ? ct(null, ht) : pt ? ct(util$2.error(new Error(pt.Message), {
                    code: pt.Code,
                    error: pt
                })) : lt ? ct(util$2.error(new Error(ot.statusMessage), {
                    code: "" + lt
                })) : lt && ct(util$2.error(new Error("statusCode error")))
            }
        })
          , rt = function(it) {
            it.TaskId === o && (tt && tt.abort && tt.abort(),
            i.off("inner-kill-task", rt))
        };
        o && i.on("inner-kill-task", rt)
    }
}
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(a, e, i) {
    util$2.each(["Cors", "Acl"], function(o) {
        if (a.slice(-o.length) === o) {
            var s = a.slice(0, -o.length) + o.toUpperCase()
              , c = util$2.apiWrapper(a, e)
              , d = !1;
            i[s] = function() {
                !d && console.warn("warning: cos." + s + " has been deprecated. Please Use cos." + a + " instead."),
                d = !0,
                c.apply(this, arguments)
            }
        }
    })
}
base$1.init = function(a, e) {
    e.transferToTaskMethod(API_MAP$1, "putObject"),
    util$2.each(API_MAP$1, function(i, o) {
        a.prototype[o] = util$2.apiWrapper(o, i),
        warnOldApi(o, i, a.prototype)
    })
}
;
var advance$1 = {}
  , eachLimit = function(a, e, i, o) {
    if (o = o || function() {}
    ,
    !a.length || e <= 0)
        return o();
    var s = 0
      , c = 0
      , d = 0;
    (function _() {
        if (s >= a.length)
            return o();
        for (; d < e && c < a.length; )
            c += 1,
            d += 1,
            i(a[c - 1], function(b) {
                b ? (o(b),
                o = function() {}
                ) : (s += 1,
                d -= 1,
                s >= a.length ? o() : _())
            })
    }
    )()
}
  , retry = function(a, e, i) {
    var o = function(s) {
        e(function(c, d) {
            c && s < a ? o(s + 1) : i(c, d)
        })
    };
    a < 1 ? i() : o(1)
}
  , async = {
    eachLimit,
    retry
}
  , async_1 = async
  , session = session$2
  , Async = async_1
  , EventProxy = event$1.EventProxy
  , util$1 = util_1;
function sliceUploadFile(a, e) {
    var i = this, o = new EventProxy, s = a.TaskId, c = a.Bucket, d = a.Region, _ = a.Key, b = a.Body, k = a.ChunkSize || a.SliceSize || i.options.ChunkSize, j = a.AsyncLimit, $ = a.StorageClass, _e = a.ServerSideEncryption, et, tt, rt = a.onHashProgress;
    o.on("error", function(it) {
        if (!!i._isRunningTask(s))
            return it.UploadId = a.UploadData.UploadId || "",
            e(it)
    }),
    o.on("upload_complete", function(it) {
        var nt = util$1.extend({
            UploadId: a.UploadData.UploadId || ""
        }, it);
        e(null, nt)
    }),
    o.on("upload_slice_complete", function(it) {
        var nt = {};
        util$1.each(a.Headers, function(ot, at) {
            var st = at.toLowerCase();
            (st.indexOf("x-cos-meta-") === 0 || st === "pic-operations") && (nt[at] = ot)
        }),
        uploadSliceComplete.call(i, {
            Bucket: c,
            Region: d,
            Key: _,
            UploadId: it.UploadId,
            SliceList: it.SliceList,
            Headers: nt
        }, function(ot, at) {
            if (!!i._isRunningTask(s)) {
                if (session.removeUsing(it.UploadId),
                ot)
                    return tt(null, !0),
                    o.emit("error", ot);
                session.removeUploadId.call(i, it.UploadId),
                tt({
                    loaded: et,
                    total: et
                }, !0),
                o.emit("upload_complete", at)
            }
        })
    }),
    o.on("get_upload_data_finish", function(it) {
        var nt = session.getFileId(b, a.ChunkSize, c, _);
        nt && session.saveUploadId.call(i, nt, it.UploadId, i.options.UploadIdCacheLimit),
        session.setUsing(it.UploadId),
        tt(null, !0),
        uploadSliceList.call(i, {
            TaskId: s,
            Bucket: c,
            Region: d,
            Key: _,
            Body: b,
            FileSize: et,
            SliceSize: k,
            AsyncLimit: j,
            ServerSideEncryption: _e,
            UploadData: it,
            Headers: a.Headers,
            onProgress: tt
        }, function(ot, at) {
            if (!!i._isRunningTask(s)) {
                if (ot)
                    return tt(null, !0),
                    o.emit("error", ot);
                o.emit("upload_slice_complete", at)
            }
        })
    }),
    o.on("get_file_size_finish", function() {
        if (tt = util$1.throttleOnProgress.call(i, et, a.onProgress),
        a.UploadData.UploadId)
            o.emit("get_upload_data_finish", a.UploadData);
        else {
            var it = util$1.extend({
                TaskId: s,
                Bucket: c,
                Region: d,
                Key: _,
                Headers: a.Headers,
                StorageClass: $,
                Body: b,
                FileSize: et,
                SliceSize: k,
                onHashProgress: rt
            }, a);
            getUploadIdAndPartList.call(i, it, function(nt, ot) {
                if (!!i._isRunningTask(s)) {
                    if (nt)
                        return o.emit("error", nt);
                    a.UploadData.UploadId = ot.UploadId,
                    a.UploadData.PartList = ot.PartList,
                    o.emit("get_upload_data_finish", a.UploadData)
                }
            })
        }
    }),
    et = a.ContentLength,
    delete a.ContentLength,
    !a.Headers && (a.Headers = {}),
    util$1.each(a.Headers, function(it, nt) {
        nt.toLowerCase() === "content-length" && delete a.Headers[nt]
    }),
    function() {
        for (var it = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 5120], nt = 1024 * 1024, ot = 0; ot < it.length && (nt = it[ot] * 1024 * 1024,
        !(et / nt <= i.options.MaxPartNumber)); ot++)
            ;
        a.ChunkSize = a.SliceSize = k = Math.max(k, nt)
    }(),
    et === 0 ? (a.Body = "",
    a.ContentLength = 0,
    a.SkipTask = !0,
    i.putObject(a, e)) : o.emit("get_file_size_finish")
}
function getUploadIdAndPartList(a, e) {
    var i = a.TaskId
      , o = a.Bucket
      , s = a.Region
      , c = a.Key
      , d = a.StorageClass
      , _ = this
      , b = {}
      , k = a.FileSize
      , j = a.SliceSize
      , $ = Math.ceil(k / j)
      , _e = 0
      , et = util$1.throttleOnProgress.call(_, k, a.onHashProgress)
      , tt = function(nt, ot) {
        var at = j * (nt - 1)
          , st = Math.min(at + j, k)
          , ut = st - at;
        b[nt] ? ot(null, {
            PartNumber: nt,
            ETag: b[nt],
            Size: ut
        }) : util$1.fileSlice(a.Body, at, st, !1, function(ct) {
            util$1.getFileMd5(ct, function(lt, ft) {
                if (lt)
                    return ot(util$1.error(lt));
                var ht = '"' + ft + '"';
                b[nt] = ht,
                _e += ut,
                et({
                    loaded: _e,
                    total: k
                }),
                ot(null, {
                    PartNumber: nt,
                    ETag: ht,
                    Size: ut
                })
            })
        })
    }
      , rt = function(nt, ot) {
        var at = nt.length;
        if (at === 0)
            return ot(null, !0);
        if (at > $)
            return ot(null, !1);
        if (at > 1) {
            var st = Math.max(nt[0].Size, nt[1].Size);
            if (st !== j)
                return ot(null, !1)
        }
        var ut = function(ct) {
            if (ct < at) {
                var lt = nt[ct];
                tt(lt.PartNumber, function(ft, ht) {
                    ht && ht.ETag === lt.ETag && ht.Size === lt.Size ? ut(ct + 1) : ot(null, !1)
                })
            } else
                ot(null, !0)
        };
        ut(0)
    }
      , it = new EventProxy;
    it.on("error", function(nt) {
        if (!!_._isRunningTask(i))
            return e(nt)
    }),
    it.on("upload_id_available", function(nt) {
        var ot = {}
          , at = [];
        util$1.each(nt.PartList, function(ct) {
            ot[ct.PartNumber] = ct
        });
        for (var st = 1; st <= $; st++) {
            var ut = ot[st];
            ut ? (ut.PartNumber = st,
            ut.Uploaded = !0) : ut = {
                PartNumber: st,
                ETag: null,
                Uploaded: !1
            },
            at.push(ut)
        }
        nt.PartList = at,
        e(null, nt)
    }),
    it.on("no_available_upload_id", function() {
        if (!!_._isRunningTask(i)) {
            var nt = util$1.extend({
                Bucket: o,
                Region: s,
                Key: c,
                Query: util$1.clone(a.Query),
                StorageClass: d,
                Body: a.Body
            }, a)
              , ot = util$1.clone(a.Headers);
            delete ot["x-cos-mime-limit"],
            nt.Headers = ot,
            _.multipartInit(nt, function(at, st) {
                if (!!_._isRunningTask(i)) {
                    if (at)
                        return it.emit("error", at);
                    var ut = st.UploadId;
                    if (!ut)
                        return e(util$1.error(new Error("no such upload id")));
                    it.emit("upload_id_available", {
                        UploadId: ut,
                        PartList: []
                    })
                }
            })
        }
    }),
    it.on("has_and_check_upload_id", function(nt) {
        nt = nt.reverse(),
        Async.eachLimit(nt, 1, function(ot, at) {
            if (!!_._isRunningTask(i)) {
                if (session.using[ot]) {
                    at();
                    return
                }
                wholeMultipartListPart.call(_, {
                    Bucket: o,
                    Region: s,
                    Key: c,
                    UploadId: ot
                }, function(st, ut) {
                    if (!!_._isRunningTask(i)) {
                        if (st)
                            return session.removeUsing(ot),
                            it.emit("error", st);
                        var ct = ut.PartList;
                        ct.forEach(function(lt) {
                            lt.PartNumber *= 1,
                            lt.Size *= 1,
                            lt.ETag = lt.ETag || ""
                        }),
                        rt(ct, function(lt, ft) {
                            if (!!_._isRunningTask(i)) {
                                if (lt)
                                    return it.emit("error", lt);
                                ft ? at({
                                    UploadId: ot,
                                    PartList: ct
                                }) : at()
                            }
                        })
                    }
                })
            }
        }, function(ot) {
            !_._isRunningTask(i) || (et(null, !0),
            ot && ot.UploadId ? it.emit("upload_id_available", ot) : it.emit("no_available_upload_id"))
        })
    }),
    it.on("seek_local_avail_upload_id", function(nt) {
        var ot = session.getFileId(a.Body, a.ChunkSize, o, c)
          , at = session.getUploadIdList.call(_, ot);
        if (!ot || !at) {
            it.emit("has_and_check_upload_id", nt);
            return
        }
        var st = function(ut) {
            if (ut >= at.length) {
                it.emit("has_and_check_upload_id", nt);
                return
            }
            var ct = at[ut];
            if (!util$1.isInArray(nt, ct)) {
                session.removeUploadId.call(_, ct),
                st(ut + 1);
                return
            }
            if (session.using[ct]) {
                st(ut + 1);
                return
            }
            wholeMultipartListPart.call(_, {
                Bucket: o,
                Region: s,
                Key: c,
                UploadId: ct
            }, function(lt, ft) {
                !_._isRunningTask(i) || (lt ? (session.removeUploadId.call(_, ct),
                st(ut + 1)) : it.emit("upload_id_available", {
                    UploadId: ct,
                    PartList: ft.PartList
                }))
            })
        };
        st(0)
    }),
    it.on("get_remote_upload_id_list", function() {
        wholeMultipartList.call(_, {
            Bucket: o,
            Region: s,
            Key: c
        }, function(nt, ot) {
            if (!!_._isRunningTask(i)) {
                if (nt)
                    return it.emit("error", nt);
                var at = util$1.filter(ot.UploadList, function(ct) {
                    return ct.Key === c && (!d || ct.StorageClass.toUpperCase() === d.toUpperCase())
                }).reverse().map(function(ct) {
                    return ct.UploadId || ct.UploadID
                });
                if (at.length)
                    it.emit("seek_local_avail_upload_id", at);
                else {
                    var st = session.getFileId(a.Body, a.ChunkSize, o, c), ut;
                    st && (ut = session.getUploadIdList.call(_, st)) && util$1.each(ut, function(ct) {
                        session.removeUploadId.call(_, ct)
                    }),
                    it.emit("no_available_upload_id")
                }
            }
        })
    }),
    it.emit("get_remote_upload_id_list")
}
function wholeMultipartList(a, e) {
    var i = this
      , o = []
      , s = {
        Bucket: a.Bucket,
        Region: a.Region,
        Prefix: a.Key
    }
      , c = function() {
        i.multipartList(s, function(d, _) {
            if (d)
                return e(d);
            o.push.apply(o, _.Upload || []),
            _.IsTruncated === "true" ? (s.KeyMarker = _.NextKeyMarker,
            s.UploadIdMarker = _.NextUploadIdMarker,
            c()) : e(null, {
                UploadList: o
            })
        })
    };
    c()
}
function wholeMultipartListPart(a, e) {
    var i = this
      , o = []
      , s = {
        Bucket: a.Bucket,
        Region: a.Region,
        Key: a.Key,
        UploadId: a.UploadId
    }
      , c = function() {
        i.multipartListPart(s, function(d, _) {
            if (d)
                return e(d);
            o.push.apply(o, _.Part || []),
            _.IsTruncated === "true" ? (s.PartNumberMarker = _.NextPartNumberMarker,
            c()) : e(null, {
                PartList: o
            })
        })
    };
    c()
}
function uploadSliceList(a, e) {
    var i = this
      , o = a.TaskId
      , s = a.Bucket
      , c = a.Region
      , d = a.Key
      , _ = a.UploadData
      , b = a.FileSize
      , k = a.SliceSize
      , j = Math.min(a.AsyncLimit || i.options.ChunkParallelLimit || 1, 256)
      , $ = a.Body
      , _e = Math.ceil(b / k)
      , et = 0
      , tt = a.ServerSideEncryption
      , rt = a.Headers
      , it = util$1.filter(_.PartList, function(ot) {
        return ot.Uploaded && (et += ot.PartNumber >= _e && b % k || k),
        !ot.Uploaded
    })
      , nt = a.onProgress;
    Async.eachLimit(it, j, function(ot, at) {
        if (!!i._isRunningTask(o)) {
            var st = ot.PartNumber
              , ut = Math.min(b, ot.PartNumber * k) - (ot.PartNumber - 1) * k
              , ct = 0;
            uploadSliceItem.call(i, {
                TaskId: o,
                Bucket: s,
                Region: c,
                Key: d,
                SliceSize: k,
                FileSize: b,
                PartNumber: st,
                ServerSideEncryption: tt,
                Body: $,
                UploadData: _,
                Headers: rt,
                onProgress: function(lt) {
                    et += lt.loaded - ct,
                    ct = lt.loaded,
                    nt({
                        loaded: et,
                        total: b
                    })
                }
            }, function(lt, ft) {
                !i._isRunningTask(o) || (!lt && !ft.ETag && (lt = '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 )'),
                lt ? et -= ct : (et += ut - ct,
                ot.ETag = ft.ETag),
                nt({
                    loaded: et,
                    total: b
                }),
                at(lt || null, ft))
            })
        }
    }, function(ot) {
        if (!!i._isRunningTask(o)) {
            if (ot)
                return e(ot);
            e(null, {
                UploadId: _.UploadId,
                SliceList: _.PartList
            })
        }
    })
}
function uploadSliceItem(a, e) {
    var i = this
      , o = a.TaskId
      , s = a.Bucket
      , c = a.Region
      , d = a.Key
      , _ = a.FileSize
      , b = a.Body
      , k = a.PartNumber * 1
      , j = a.SliceSize
      , $ = a.ServerSideEncryption
      , _e = a.UploadData
      , et = a.Headers || {}
      , tt = i.options.ChunkRetryTimes + 1
      , rt = j * (k - 1)
      , it = j
      , nt = rt + j;
    nt > _ && (nt = _,
    it = nt - rt);
    var ot = ["x-cos-traffic-limit", "x-cos-mime-limit"]
      , at = {};
    util$1.each(et, function(ut, ct) {
        ot.indexOf(ct) > -1 && (at[ct] = ut)
    });
    var st = _e.PartList[k - 1];
    Async.retry(tt, function(ut) {
        !i._isRunningTask(o) || util$1.fileSlice(b, rt, nt, !0, function(ct) {
            i.multipartUpload({
                TaskId: o,
                Bucket: s,
                Region: c,
                Key: d,
                ContentLength: it,
                PartNumber: k,
                UploadId: _e.UploadId,
                ServerSideEncryption: $,
                Body: ct,
                Headers: at,
                onProgress: a.onProgress
            }, function(lt, ft) {
                if (!!i._isRunningTask(o))
                    return lt ? ut(lt) : (st.Uploaded = !0,
                    ut(null, ft))
            })
        })
    }, function(ut, ct) {
        if (!!i._isRunningTask(o))
            return e(ut, ct)
    })
}
function uploadSliceComplete(a, e) {
    var i = a.Bucket
      , o = a.Region
      , s = a.Key
      , c = a.UploadId
      , d = a.SliceList
      , _ = this
      , b = this.options.ChunkRetryTimes + 1
      , k = a.Headers
      , j = d.map(function($) {
        return {
            PartNumber: $.PartNumber,
            ETag: $.ETag
        }
    });
    Async.retry(b, function($) {
        _.multipartComplete({
            Bucket: i,
            Region: o,
            Key: s,
            UploadId: c,
            Parts: j,
            Headers: k
        }, $)
    }, function($, _e) {
        e($, _e)
    })
}
function abortUploadTask(a, e) {
    var i = a.Bucket
      , o = a.Region
      , s = a.Key
      , c = a.UploadId
      , d = a.Level || "task"
      , _ = a.AsyncLimit
      , b = this
      , k = new EventProxy;
    if (k.on("error", function(j) {
        return e(j)
    }),
    k.on("get_abort_array", function(j) {
        abortUploadTaskArray.call(b, {
            Bucket: i,
            Region: o,
            Key: s,
            Headers: a.Headers,
            AsyncLimit: _,
            AbortArray: j
        }, e)
    }),
    d === "bucket")
        wholeMultipartList.call(b, {
            Bucket: i,
            Region: o
        }, function(j, $) {
            if (j)
                return e(j);
            k.emit("get_abort_array", $.UploadList || [])
        });
    else if (d === "file") {
        if (!s)
            return e(util$1.error(new Error("abort_upload_task_no_key")));
        wholeMultipartList.call(b, {
            Bucket: i,
            Region: o,
            Key: s
        }, function(j, $) {
            if (j)
                return e(j);
            k.emit("get_abort_array", $.UploadList || [])
        })
    } else if (d === "task") {
        if (!c)
            return e(util$1.error(new Error("abort_upload_task_no_id")));
        if (!s)
            return e(util$1.error(new Error("abort_upload_task_no_key")));
        k.emit("get_abort_array", [{
            Key: s,
            UploadId: c
        }])
    } else
        return e(util$1.error(new Error("abort_unknown_level")))
}
function abortUploadTaskArray(a, e) {
    var i = a.Bucket
      , o = a.Region
      , s = a.Key
      , c = a.AbortArray
      , d = a.AsyncLimit || 1
      , _ = this
      , b = 0
      , k = new Array(c.length);
    Async.eachLimit(c, d, function(j, $) {
        var _e = b;
        if (s && s !== j.Key) {
            k[_e] = {
                error: {
                    KeyNotMatch: !0
                }
            },
            $(null);
            return
        }
        var et = j.UploadId || j.UploadID;
        _.multipartAbort({
            Bucket: i,
            Region: o,
            Key: j.Key,
            Headers: a.Headers,
            UploadId: et
        }, function(tt) {
            var rt = {
                Bucket: i,
                Region: o,
                Key: j.Key,
                UploadId: et
            };
            k[_e] = {
                error: tt,
                task: rt
            },
            $(null)
        }),
        b++
    }, function(j) {
        if (j)
            return e(j);
        for (var $ = [], _e = [], et = 0, tt = k.length; et < tt; et++) {
            var rt = k[et];
            rt.task && (rt.error ? _e.push(rt.task) : $.push(rt.task))
        }
        return e(null, {
            successList: $,
            errorList: _e
        })
    })
}
function uploadFile(a, e) {
    var i = this
      , o = a.SliceSize === void 0 ? i.options.SliceSize : a.SliceSize
      , s = []
      , c = a.Body
      , d = c.size || c.length || 0
      , _ = {
        TaskId: ""
    };
    util$1.each(a, function(et, tt) {
        typeof et != "object" && typeof et != "function" && (_[tt] = et)
    });
    var b = a.onTaskReady
      , k = function(et) {
        _.TaskId = et,
        b && b(et)
    };
    a.onTaskReady = k;
    var j = a.onFileFinish
      , $ = function(et, tt) {
        j && j(et, tt, _),
        e && e(et, tt)
    }
      , _e = d > o ? "sliceUploadFile" : "putObject";
    s.push({
        api: _e,
        params: a,
        callback: $
    }),
    i._addTasks(s)
}
function uploadFiles(a, e) {
    var i = this
      , o = a.SliceSize === void 0 ? i.options.SliceSize : a.SliceSize
      , s = 0
      , c = 0
      , d = util$1.throttleOnProgress.call(i, c, a.onProgress)
      , _ = a.files.length
      , b = a.onFileFinish
      , k = Array(_)
      , j = function(_e, et, tt) {
        d(null, !0),
        b && b(_e, et, tt),
        k[tt.Index] = {
            options: tt,
            error: _e,
            data: et
        },
        --_ <= 0 && e && e(null, {
            files: k
        })
    }
      , $ = [];
    util$1.each(a.files, function(_e, et) {
        (function() {
            var tt = _e.Body
              , rt = tt.size || tt.length || 0
              , it = {
                Index: et,
                TaskId: ""
            };
            s += rt,
            util$1.each(_e, function(ht, pt) {
                typeof ht != "object" && typeof ht != "function" && (it[pt] = ht)
            });
            var nt = _e.onTaskReady
              , ot = function(ht) {
                it.TaskId = ht,
                nt && nt(ht)
            };
            _e.onTaskReady = ot;
            var at = 0
              , st = _e.onProgress
              , ut = function(ht) {
                c = c - at + ht.loaded,
                at = ht.loaded,
                st && st(ht),
                d({
                    loaded: c,
                    total: s
                })
            };
            _e.onProgress = ut;
            var ct = _e.onFileFinish
              , lt = function(ht, pt) {
                ct && ct(ht, pt),
                j && j(ht, pt, it)
            }
              , ft = rt > o ? "sliceUploadFile" : "putObject";
            $.push({
                api: ft,
                params: _e,
                callback: lt
            })
        }
        )()
    }),
    i._addTasks($)
}
function sliceCopyFile(a, e) {
    var i = new EventProxy
      , o = this
      , s = a.Bucket
      , c = a.Region
      , d = a.Key
      , _ = a.CopySource
      , b = util$1.getSourceParams.call(this, _);
    if (!b) {
        e(util$1.error(new Error("CopySource format error")));
        return
    }
    var k = b.Bucket
      , j = b.Region
      , $ = decodeURIComponent(b.Key)
      , _e = a.CopySliceSize === void 0 ? o.options.CopySliceSize : a.CopySliceSize;
    _e = Math.max(0, _e);
    var et = a.CopyChunkSize || this.options.CopyChunkSize, tt = this.options.CopyChunkParallelLimit, rt = 0, it, nt;
    i.on("copy_slice_complete", function(ot) {
        var at = {};
        util$1.each(a.Headers, function(ut, ct) {
            ct.toLowerCase().indexOf("x-cos-meta-") === 0 && (at[ct] = ut)
        });
        var st = util$1.map(ot.PartList, function(ut) {
            return {
                PartNumber: ut.PartNumber,
                ETag: ut.ETag
            }
        });
        o.multipartComplete({
            Bucket: s,
            Region: c,
            Key: d,
            UploadId: ot.UploadId,
            Parts: st
        }, function(ut, ct) {
            if (ut)
                return nt(null, !0),
                e(ut);
            nt({
                loaded: it,
                total: it
            }, !0),
            e(null, ct)
        })
    }),
    i.on("get_copy_data_finish", function(ot) {
        Async.eachLimit(ot.PartList, tt, function(at, st) {
            var ut = at.PartNumber
              , ct = at.CopySourceRange
              , lt = at.end - at.start;
            copySliceItem.call(o, {
                Bucket: s,
                Region: c,
                Key: d,
                CopySource: _,
                UploadId: ot.UploadId,
                PartNumber: ut,
                CopySourceRange: ct
            }, function(ft, ht) {
                if (ft)
                    return st(ft);
                rt += lt,
                nt({
                    loaded: rt,
                    total: it
                }),
                at.ETag = ht.ETag,
                st(ft || null, ht)
            })
        }, function(at) {
            if (at)
                return nt(null, !0),
                e(at);
            i.emit("copy_slice_complete", ot)
        })
    }),
    i.on("get_file_size_finish", function(ot) {
        (function() {
            for (var ut = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 5120], ct = 1024 * 1024, lt = 0; lt < ut.length && (ct = ut[lt] * 1024 * 1024,
            !(it / ct <= o.options.MaxPartNumber)); lt++)
                ;
            a.ChunkSize = et = Math.max(et, ct);
            for (var ft = Math.ceil(it / et), ht = [], pt = 1; pt <= ft; pt++) {
                var dt = (pt - 1) * et
                  , _t = pt * et < it ? pt * et - 1 : it - 1
                  , mt = {
                    PartNumber: pt,
                    start: dt,
                    end: _t,
                    CopySourceRange: "bytes=" + dt + "-" + _t
                };
                ht.push(mt)
            }
            a.PartList = ht
        }
        )();
        var at;
        if (a.Headers["x-cos-metadata-directive"] === "Replaced" ? at = a.Headers : at = ot,
        at["x-cos-storage-class"] = a.Headers["x-cos-storage-class"] || ot["x-cos-storage-class"],
        at = util$1.clearKey(at),
        ot["x-cos-storage-class"] === "ARCHIVE" || ot["x-cos-storage-class"] === "DEEP_ARCHIVE") {
            var st = ot["x-cos-restore"];
            if (!st || st === 'ongoing-request="true"') {
                e(util$1.error(new Error("Unrestored archive object is not allowed to be copied")));
                return
            }
        }
        delete at["x-cos-copy-source"],
        delete at["x-cos-metadata-directive"],
        delete at["x-cos-copy-source-If-Modified-Since"],
        delete at["x-cos-copy-source-If-Unmodified-Since"],
        delete at["x-cos-copy-source-If-Match"],
        delete at["x-cos-copy-source-If-None-Match"],
        o.multipartInit({
            Bucket: s,
            Region: c,
            Key: d,
            Headers: at
        }, function(ut, ct) {
            if (ut)
                return e(ut);
            a.UploadId = ct.UploadId,
            i.emit("get_copy_data_finish", a)
        })
    }),
    o.headObject({
        Bucket: k,
        Region: j,
        Key: $
    }, function(ot, at) {
        if (ot) {
            ot.statusCode && ot.statusCode === 404 ? e(util$1.error(ot, {
                ErrorStatus: $ + " Not Exist"
            })) : e(ot);
            return
        }
        if (it = a.FileSize = at.headers["content-length"],
        it === void 0 || !it) {
            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 (nt = util$1.throttleOnProgress.call(o, it, a.onProgress),
        it <= _e)
            a.Headers["x-cos-metadata-directive"] || (a.Headers["x-cos-metadata-directive"] = "Copy"),
            o.putObjectCopy(a, function(ct, lt) {
                if (ct)
                    return nt(null, !0),
                    e(ct);
                nt({
                    loaded: it,
                    total: it
                }, !0),
                e(ct, lt)
            });
        else {
            var st = at.headers
              , ut = {
                "Cache-Control": st["cache-control"],
                "Content-Disposition": st["content-disposition"],
                "Content-Encoding": st["content-encoding"],
                "Content-Type": st["content-type"],
                Expires: st.expires,
                "x-cos-storage-class": st["x-cos-storage-class"]
            };
            util$1.each(st, function(ct, lt) {
                var ft = "x-cos-meta-";
                lt.indexOf(ft) === 0 && lt.length > ft.length && (ut[lt] = ct)
            }),
            i.emit("get_file_size_finish", ut)
        }
    })
}
function copySliceItem(a, e) {
    var i = a.TaskId
      , o = a.Bucket
      , s = a.Region
      , c = a.Key
      , d = a.CopySource
      , _ = a.UploadId
      , b = a.PartNumber * 1
      , k = a.CopySourceRange
      , j = this.options.ChunkRetryTimes + 1
      , $ = this;
    Async.retry(j, function(_e) {
        $.uploadPartCopy({
            TaskId: i,
            Bucket: o,
            Region: s,
            Key: c,
            CopySource: d,
            UploadId: _,
            PartNumber: b,
            CopySourceRange: k
        }, function(et, tt) {
            _e(et || null, tt)
        })
    }, function(_e, et) {
        return e(_e, et)
    })
}
var API_MAP = {
    sliceUploadFile,
    abortUploadTask,
    uploadFile,
    uploadFiles,
    sliceCopyFile
};
advance$1.init = function(a, e) {
    e.transferToTaskMethod(API_MAP, "sliceUploadFile"),
    util$1.each(API_MAP, function(i, o) {
        a.prototype[o] = util$1.apiWrapper(o, i)
    })
}
;
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,
    ForceSignHost: !0
}
  , COS$1 = function(a) {
    this.options = util.extend(util.clone(defaultOptions), a || {}),
    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.6";
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(a, e) {
        var i = SERVER_URL
          , o = new XMLHttpRequest;
        o.open("GET", i, !0),
        o.onload = function(s) {
            try {
                var c = JSON.parse(s.target.responseText)
                  , d = c.credentials
            } catch (_) {
                console.error(_)
            }
            if (!c || !d)
                return console.error(`credentials invalid:
` + JSON.stringify(c, null, 2));
            e({
                TmpSecretId: d.tmpSecretId,
                TmpSecretKey: d.tmpSecretKey,
                SecurityToken: d.sessionToken,
                StartTime: c.startTime,
                ExpiredTime: c.expiredTime
            })
        }
        ,
        o.send()
    }
});
function uploadStream(a, e) {
    myCos.putObject({
        Bucket: COS_BUCKET,
        Region: COS_REGION,
        Key: a,
        StorageClass: "STANDARD",
        Body: e,
        onProgress: function(i) {
            console.log(JSON.stringify(i))
        }
    }, function(i, o) {
        console.log(i || o)
    })
}
const defaultLogger = {
    info: console.log,
    debug: console.log,
    error: console.error,
    infoAndReportMeasurement: (...a)=>{}
};
let log$l = defaultLogger
  , USER_ID = "987412365"
  , PAGE_SESSION = "aaabbbccc"
  , SERVER_SESSION = "cccbbbaaa";
const COS_PREFIX = "error-bitstreams-auto-uploaded-from-application/"
  , FRAME_COMPOSE_LENGTH = 5;
class Workers {
    constructor(e, i) {
        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.joyStickTraceIdMap = new Map,
        this.joyStickResponseTimeArray = [],
        this.joyStickProcessTimeArray = [],
        this.joyStickDisplayTimeArray = [],
        this.joyStickOverallTimeArray = [],
        this.joyStickResponseMiss = 0,
        this.joyStickProcessMiss = 0,
        this.joyStickDisplayMiss = 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.unmarshalStreamExecutionArray = new SecondArray,
        this.receiveYUVExecutionArray = new SecondArray,
        this.postMessageWaitArray = new SecondArray,
        this.firstUpdateYUV = !0,
        this.functionMap = new Map,
        this.WASM_VERSION = "WASM-1.1",
        this.frameHistory = [],
        this.getVersion = function() {
            return DECODER_VERSION
        }
        ,
        this.downloadBlob = (o,s,c)=>{
            const d = new Blob([o],{
                type: c
            })
              , _ = window.URL.createObjectURL(d);
            this.downloadURL(_, s),
            setTimeout(function() {
                return window.URL.revokeObjectURL(_)
            }, 1e3)
        }
        ,
        this.downloadURL = function(o, s) {
            const c = document.createElement("a");
            c.href = o,
            c.download = s,
            document.body.appendChild(c),
            c.style.display = "none",
            c.click(),
            c.remove()
        }
        ,
        this.Stringify = function(o) {
            let s = "";
            for (let d = 0; d < o.length / 8192; d++)
                s += String.fromCharCode.apply(null, o.slice(d * 8192, (d + 1) * 8192));
            return s
        }
        ,
        this._rtcp = e
    }
    registerLogger(e) {
        log$l = e
    }
    registerFunction(e, i) {
        this.functionMap.set(e, i)
    }
    hasFrmCntInCache(e) {
        let i = -1;
        for (let o = 0; o < this.cacheFrameComposes.length; o++)
            this.cacheFrameComposes[o].frameCnt == e && (i = o);
        return i
    }
    requestPanoramaTest(e, i, o, s, c) {
        const d = c
          , _ = {
            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: i,
                        z: o
                    },
                    angle: {
                        yaw: 0,
                        pitch: 0,
                        roll: 0
                    }
                },
                client_pano_titles_bitmap: s
            },
            trace_id: d,
            user_id: this.userId_test,
            packet_id: d
        };
        log$l.debug("send data: ", _),
        this._rtcp.sendData(_)
    }
    onRotateInPanoMode(e) {
        const i = e.traceId
          , o = {};
        o.width = 1280,
        o.height = 720,
        o.horz_fov = 92,
        o.angle = {
            yaw: 100,
            pitch: 30
        };
        const s = new ArrayBuffer(8)
          , c = new DataView(s);
        getTilesInView(o, s);
        const d = s.slice(0);
        this.PendingMasks.unshift({
            buffer: d,
            angle: o.angle
        }),
        MaskSetToOne(18, this.PanoView),
        operateForDataView(c, this.PanoView, c, (_,b)=>_ ^ _ & b),
        this.requestPanoramaTest(0, 0, 0, [c.getUint8(0), c.getUint8(1), c.getUint8(2), c.getUint8(3), c.getUint8(4), c.getUint8(5), c.getUint8(6), c.getUint8(7)], i)
    }
    processMetaWithTraceId(e) {
        for (const i of e.traceIds) {
            if (this.traceIdMap.has(i)) {
                const o = this.traceIdMap.get(i);
                o != null && (o.receiveTime = Date.now(),
                o.status = 1)
            }
            if (this.joyStickTraceIdMap.has(i)) {
                const o = this.joyStickTraceIdMap.get(i);
                o != null && (o.receiveTime = Date.now(),
                o.status = 1)
            }
            if (i == this.PendingMovingTraceId) {
                this.inMovingMode = !0,
                this.MovingTraceId = this.PendingMovingTraceId,
                this.StartMovingTs = this.PendingStartMovingTs,
                this.PendingMovingTraceId = "",
                this.PendingStartMovingTs = 0,
                log$l.info("MoveTo TraceId match", this.StartMovingTs, Date.now());
                const o = Date.now();
                this.lastMoveResponseTime = o,
                this.lastMoveProcessTime = o,
                this.lastMoveDisplayTime = o,
                this.frameServerCircular.clear(),
                this.frameClientCircular.clear()
            }
        }
    }
    onTraceId(e, i=this) {
        const o = e.traceId
          , s = e.timestamp
          , c = e.event;
        if (c === "Rotation") {
            const d = {
                traceId: o,
                pts: 0,
                startTime: s,
                receiveTime: 0,
                readyTime: 0,
                displayTime: 0,
                status: 0
            };
            this.traceIdMap.set(o, d);
            const _ = setTimeout(()=>{
                if (_ && clearTimeout(_),
                this.traceIdMap.has(o)) {
                    const b = this.traceIdMap.get(o);
                    switch (b == null ? void 0 : b.status) {
                    case 0:
                        {
                            this.responseMiss += 1;
                            break
                        }
                    case 1:
                        {
                            this.processMiss += 1;
                            const k = b.receiveTime - b.startTime;
                            this.responseTimeArray.push(k);
                            break
                        }
                    case 2:
                        {
                            this.displayMiss += 1;
                            const k = b.receiveTime - b.startTime
                              , j = b.readyTime - b.receiveTime;
                            this.responseTimeArray.push(k),
                            this.processTimeArray.push(j);
                            break
                        }
                    case 3:
                        log$l.debug("status is 3")
                    }
                }
            }
            , 1e3)
        } else if (c === "Joystick") {
            const d = {
                traceId: o,
                pts: 0,
                startTime: s,
                receiveTime: 0,
                readyTime: 0,
                displayTime: 0,
                status: 0
            };
            this.joyStickTraceIdMap.set(o, d);
            const _ = setTimeout(()=>{
                if (_ && clearTimeout(_),
                this.joyStickTraceIdMap.has(o)) {
                    const b = this.joyStickTraceIdMap.get(o);
                    switch (b == null ? void 0 : b.status) {
                    case 0:
                        {
                            this.joyStickResponseMiss += 1;
                            break
                        }
                    case 1:
                        {
                            this.joyStickProcessMiss += 1;
                            const k = b.receiveTime - b.startTime;
                            this.joyStickResponseTimeArray.push(k);
                            break
                        }
                    case 2:
                        {
                            this.joyStickDisplayMiss += 1;
                            const k = b.receiveTime - b.startTime
                              , j = b.readyTime - b.receiveTime;
                            this.joyStickResponseTimeArray.push(k),
                            this.joyStickProcessTimeArray.push(j);
                            break
                        }
                    case 3:
                        log$l.debug("status is 3")
                    }
                }
            }
            , 1e3)
        } else
            c === "MoveTo" ? (log$l.info("receive moveto traceId ", o, " at timestamp", s),
            this.PendingMovingTraceId = o,
            this.PendingStartMovingTs = s,
            this.moveEvent = c,
            this.frameServerCircular.clear()) : c === "GetOnAirship" || c === "GetOnVehicle" ? (log$l.info("receive airship traceId ", o, " at timestamp ", s),
            this.PendingMovingTraceId = o,
            this.PendingStartMovingTs = s,
            this.moveEvent = c,
            this.frameServerCircular.clear()) : (c === "GetOffAirship" || c === "GetOffVehicle") && this.clearMoveArray()
    }
    executeFunction(e, i) {
        if (this.functionMap.has(e)) {
            const o = this.functionMap.get(e);
            o != null && o(i)
        }
    }
    UpdateStats(e) {
        var i;
        (i = this._rtcp.connection) == null || i.getStats(null).then(o=>{
            o.forEach(s=>{
                s.type == "data-channel" && (this.rtcMessageReceived = s.messagesReceived - s.messagesSent,
                this.rtcBytesReceived = s.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 b;
        const i = Date.now()
          , o = i - e.data.postTs;
        if (this.postMessageWaitArray.add(o),
        !this.firstYUVReceived) {
            this.firstYUVDecoded = e.data.yuv_ts;
            const k = this.firstYUVDecoded - this.rtcp.network.room._startTime;
            log$l.infoAndReportMeasurement({
                metric: "firstYUVDecodedAt",
                value: k,
                group: "joinRoom"
            }),
            this.firstRender = Date.now();
            const j = this.firstYUVDecoded - this.rtcp.network.room._startTime;
            log$l.infoAndReportMeasurement({
                metric: "firstRenderAt",
                value: j,
                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 s = e.data.metadata;
        if ((b = s == null ? void 0 : s.traceIds) != null && b.length)
            for (const k of s.traceIds) {
                if (this.traceIdMap.has(k)) {
                    const j = this.traceIdMap.get(k);
                    j != null && (j.readyTime = Date.now(),
                    j.status = 2)
                }
                if (this.joyStickTraceIdMap.has(k)) {
                    const j = this.joyStickTraceIdMap.get(k);
                    j != null && (j.readyTime = Date.now(),
                    j.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 k = Date.now()
              , j = k - this.lastMoveProcessTime;
            this.moveProcessCircular.add(j),
            this.lastMoveProcessTime = k
        }
        const c = this.setPtr;
        this.cachedStreams[c] = e.data.data,
        this.cachedMetas[c] = e.data.metadata,
        this.cachedPtss[c] = e.data.pts,
        this.cachedRender[c] = !1,
        this.cachedResolution[c] = {
            width: e.data.width,
            height: e.data.height
        },
        this.setPtr = (this.setPtr + 1) % this.cachedLength;
        const _ = Date.now() - i;
        this.receiveYUVExecutionArray.add(_)
    }
    SendCacheFrameInfo(e) {
        var $, _e, et, tt, rt, it, nt;
        const i = e.data.cachedKey
          , o = e.data.metadata
          , s = i
          , c = o
          , d = (et = (_e = ($ = c.newUserStates) == null ? void 0 : $.find(ot=>ot.userId === this.rtcp.network.room.userId)) == null ? void 0 : _e.playerState) == null ? void 0 : et.roomTypeId
          , _ = this.rtcp.network.room.skinId
          , b = (nt = (it = (rt = (tt = c.newUserStates) == null ? void 0 : tt.find(ot=>ot.userId === this._rtcp.network.room.userId)) == null ? void 0 : rt.playerState) == null ? void 0 : it.player) == null ? void 0 : nt.position
          , k = {
            MsgType: 1,
            FrameCacheMsg: {
                FrameIndex: s,
                RoomTypeId: d,
                SkinID: _,
                Position: b
            }
        };
        let j = "";
        try {
            j = JSON.stringify(k)
        } catch (ot) {
            log$l.error(ot);
            return
        }
    }
    ReceivePanoramaDecodeMessage(e) {
        log$l.info("Receive Panorama Image in Workers.ts"),
        MaskSetToOne(e.data.tileId, this.PanoView);
        let i = 0, o;
        const s = this.PendingMasks.length;
        for (i = 0; i < s; i++) {
            const c = this.PendingMasks[i].buffer
              , d = new DataView(c)
              , _ = new ArrayBuffer(8)
              , b = new DataView(_);
            if (operateForDataView(this.PanoView, d, b, (k,j)=>j ^ k & j),
            IsAll0(b)) {
                o = this.PendingMasks[i].angle;
                break
            }
        }
        for (let c = i; c < s; c++)
            this.PendingMasks.pop();
        this.executeFunction("panorama", {
            data: e.data.data,
            metadata: e.data.metadata,
            tileId: e.data.tileId,
            finished: !0,
            matchAngle: o
        })
    }
    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,
        userID: "testUserId",
        pageSession: "pagesession1",
        serverSession: "serversession1"
    }) {
        for (let o = 0; o < FRAME_COMPOSE_LENGTH; o++) {
            const s = {
                buffer: new Uint8Array(262144),
                size: 0,
                startReceiveTime: 0,
                serverTime: 0,
                frameCnt: -1
            };
            this.cacheFrameComposes.push(s)
        }
        USER_ID = e.userID,
        PAGE_SESSION = e.pageSession,
        SERVER_SESSION = e.serverSession;
        const i = new Blob([decoder],{
            type: "application/javascript"
        });
        return this.decoderWorker = new Worker(URL.createObjectURL(i)),
        this.decoderWorker.postMessage({
            t: 9,
            url: WASM_URLS[WASM_Version],
            jitterLength: DECODER_PASSIVE_JITTER
        }),
        this.decoderWorker.postMessage({
            t: 1,
            config: e
        }),
        new Promise(o=>{
            this.decoderWorker.onmessage = s=>{
                switch (s.data.t) {
                case 0:
                    this.ReceiveDecodeMessage(s);
                    break;
                case 1:
                    this.UpdateStats(s);
                    break;
                case 2:
                    o();
                    break;
                case 3:
                    this.SendCacheFrameInfo(s);
                    break;
                case 4:
                    {
                        const c = new Date().toISOString()
                          , d = USER_ID + "-" + PAGE_SESSION + "-" + SERVER_SESSION + "-" + c + ".264";
                        uploadStream(COS_PREFIX + d, s.data.fileObj);
                        break
                    }
                case 5:
                    this.executeFunction("signal", {
                        signal: s.data.metadata,
                        pts: -1,
                        alreadyUpdateYUV: !1
                    });
                    break;
                case 6:
                    log$l.infoAndReportMeasurement(s.data.data),
                    log$l.debug("WASM Ready Cost");
                    break;
                case 7:
                    this.ReceivePanoramaDecodeMessage(s);
                    break;
                case 8:
                    {
                        const c = {
                            MstType: 0
                        };
                        let d = "";
                        try {
                            d = JSON.stringify(c)
                        } catch (b) {
                            log$l.error(b);
                            return
                        }
                        const _ = "wasm:" + d;
                        this._rtcp.sendStringData(_);
                        break
                    }
                case 9:
                    {
                        log$l.info(s.data.printMsg);
                        break
                    }
                case 10:
                    {
                        log$l.error(s.data.printMsg),
                        this.executeFunction("error", {
                            code: s.data.code,
                            message: s.data.printMsg
                        });
                        break
                    }
                default:
                    log$l.error("Receive unknown message event from decoder"),
                    log$l.debug(s.data);
                    break
                }
            }
        }
        )
    }
    setPageSession(e) {
        PAGE_SESSION = e
    }
    UpdateYUV() {
        var i, o;
        const e = this.getPtr;
        if (this.cachedMetas[e] != null && !this.cachedRender[e]) {
            const s = Date.now();
            if (this.firstUpdateYUV) {
                const $ = ((i = this.cachedStreams[e]) == null ? void 0 : i.byteLength) || 0;
                log$l.infoAndReportMeasurement({
                    metric: "firstUpdateStreamLength",
                    value: $,
                    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 c = Date.now();
            this.cachedStreams[e] != null && this.decoderWorker.postMessage({
                t: 2,
                frameCnt: this.cachedPtss[e],
                buffer: this.cachedStreams[e]
            }, [this.cachedStreams[e].buffer]);
            const d = Date.now()
              , _ = c - s
              , b = d - c;
            (_ > 33 || b > 10) && log$l.debug("[wwwarning] updateYUV takes ", _, " ms, postMessage takes ", b, " ms for index ", this.cachedPtss[e]),
            c - this.lastRenderTs > 84 && this.JankTimes++,
            c - this.lastRenderTs > 125 && this.bigJankTimes++,
            this.lastRenderTs = c;
            const k = c - s;
            this.updateYUVCircular.add(k);
            const j = this.cachedMetas[e];
            if ((o = j == null ? void 0 : j.traceIds) != null && o.length)
                for (const $ of j.traceIds) {
                    if (this.traceIdMap.has($)) {
                        const _e = this.traceIdMap.get($);
                        if (_e != null) {
                            _e.displayTime = Date.now(),
                            _e.status = 3;
                            const et = _e.receiveTime - _e.startTime
                              , tt = _e.readyTime - _e.receiveTime
                              , rt = _e.displayTime - _e.readyTime
                              , it = _e.displayTime - _e.startTime;
                            this.responseTimeArray.push(et),
                            this.processTimeArray.push(tt),
                            this.displayTimeArray.push(rt),
                            this.overallTimeArray.push(it),
                            this.traceIdMap.delete($)
                        }
                    }
                    if (this.joyStickTraceIdMap.has($)) {
                        const _e = this.joyStickTraceIdMap.get($);
                        if (_e != null) {
                            _e.displayTime = Date.now(),
                            _e.status = 3;
                            const et = _e.receiveTime - _e.startTime
                              , tt = _e.readyTime - _e.receiveTime
                              , rt = _e.displayTime - _e.readyTime
                              , it = _e.displayTime - _e.startTime;
                            this.joyStickResponseTimeArray.push(et),
                            this.joyStickProcessTimeArray.push(tt),
                            this.joyStickDisplayTimeArray.push(rt),
                            this.joyStickOverallTimeArray.push(it),
                            this.joyStickTraceIdMap.delete($)
                        }
                    }
                }
            if (this.cachedPtss[e] == this.moveStartPts && (this.MoveDisplayDelay = Date.now() - this.StartMovingTs),
            this.inMovingMode) {
                const $ = Date.now()
                  , _e = $ - this.lastMoveDisplayTime;
                this.moveDisplayCircular.add(_e),
                this.lastMoveDisplayTime = $
            }
            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 i = new DataView(e)
          , o = i.getUint32(0);
        if (o == 1723558763)
            return !0;
        if (o != 2296221069)
            return !1;
        console.log("Receive Pano Message"),
        i.getUint16(4);
        const s = i.getUint16(6)
          , c = i.getUint32(8)
          , d = i.getUint32(12)
          , _ = i.getUint32(16)
          , b = i.getUint32(20)
          , k = e.byteLength - s;
        if (k == d) {
            const j = new Uint8Array(e).subarray(s).slice(0, _)
              , _e = {
                data: new Uint8Array(e).subarray(s).slice(_, d),
                mediaLen: d - _,
                metadata: j,
                metaLen: _,
                tileId: c
            };
            this.decoderWorker.postMessage({
                t: 8,
                data: _e
            })
        } else {
            const j = new Uint8Array(e,s,k);
            if (this.cachePanoTileID == c) {
                if (this.panoCacheBuffer.set(j, b),
                this.panoCacheSize += k,
                this.panoCacheSize === d) {
                    const $ = new Uint8Array(this.panoCacheBuffer).slice(0, _)
                      , et = {
                        data: new Uint8Array(this.panoCacheBuffer).slice(_, d),
                        mediaLen: d - _,
                        metadata: $,
                        metaLen: _,
                        tileId: c
                    };
                    this.decoderWorker.postMessage({
                        t: 8,
                        data: et
                    }),
                    this.panoCacheSize = 0
                }
            } else
                this.panoCacheBuffer.set(j, b),
                this.panoCacheSize = k,
                this.cachePanoTileID = c
        }
        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 i;
        if (typeof e.newUserStates != "undefined")
            for (let o = 0; o < e.newUserStates.length; o++) {
                const s = e.newUserStates[o];
                if (s.userId == this.rtcp.network.room.userId) {
                    i = s.renderInfo.isMoving;
                    break
                }
            }
        return i
    }
    isHeartBeatPacket(e, i) {
        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 i = e - this.prevSenderTs;
        this.serverSendTimeArray.add(i),
        this.prevSenderTs = e
    }
    unmarshalStream(e) {
        var lt, ft, ht, pt, dt, _t, mt, vt, yt, Et;
        const i = Date.now()
          , o = new DataView(e);
        if (o.getUint32(0) != 1437227610)
            return !1;
        o.getUint16(4);
        const c = o.getUint16(6)
          , d = o.getUint16(8)
          , _ = d
          , b = o.getUint16(10);
        let k = !1;
        b == 1 && (k = !0);
        const j = o.getUint32(12)
          , $ = o.getUint32(16)
          , _e = o.getUint32(20)
          , et = o.getUint16(24)
          , tt = o.getUint16(26)
          , rt = o.getUint32(28)
          , it = o.getUint32(c - 4)
          , nt = j + $
          , ot = e.byteLength - c
          , at = new Uint8Array(e,c,ot);
        this.calcSendTimeDiff(_e);
        let st;
        if (this.inPanoMode && ($ > 0 || et))
            return log$l.error("Stream Protocal Violation: receive illegal stream in Pano mode"),
            !0;
        if (ot === nt) {
            this.receivedMedia++;
            const At = new Uint8Array(e).subarray(c);
            _e - this.lastServerTS > 60 ? this.serverFrameSlow++ : _e - this.lastServerTS < 16 && this.serverFrameFast++;
            const gt = Date.now();
            gt - this.lastClientTS > 60 ? this.clientFrameSlow++ : gt - this.lastClientTS < 16 && this.clientFrameFast++;
            const St = $ === 0
              , xt = _e - this.lastServerTS;
            this.lastServerTS != 0 && ((d + 65536 - this.lastSeq) % 65536 === 1 && this.lastIsPureMeta == St && (St ? this.srvMetaIntervalCircular.add(xt) : this.srvMediaIntervalCircular.add(xt)),
            this.frameServerCircular.add(xt),
            this.frameClientCircular.add(gt - this.lastClientTS)),
            this.lastSeq = d,
            this.lastIsPureMeta = St,
            this.lastServerTS = _e,
            this.lastClientTS = gt;
            const bt = At.subarray(0, j)
              , Rt = Date.now()
              , Mt = JSON.parse(this.Stringify(bt))
              , Pt = Date.now();
            this.showAllReceivedMetadata && console.log(_e, gt, Mt),
            this.metaParseAraay.push(Pt - Rt),
            (lt = Mt.traceIds) != null && lt.length && this.processMetaWithTraceId(Mt),
            $ != 0 && this.moveStartPts == -1 && this.inMovingMode && (this.moveStartPts = d),
            this.moveStartPts == d && (this.MoveResponseDelay = Date.now() - this.StartMovingTs,
            console.log("move response delay: ", d, this.moveStartPts, this.MoveResponseDelay));
            const It = this.getIsMoving(Mt);
            if (this.inMovingMode && It == 0 && this.lastIsMoving == 1 && this.clearMoveArray(),
            typeof It != "undefined" && (this.lastIsMoving = It),
            this.inMovingMode) {
                const Ct = Date.now()
                  , Ot = Ct - this.lastMoveResponseTime;
                this.moveResponseCircular.add(Ot),
                this.lastMoveResponseTime = Ct
            }
            (et || tt) && (st = (dt = (pt = (ht = (ft = Mt.newUserStates) == null ? void 0 : ft.find(Ct=>Ct.userId === this._rtcp.network.room.userId)) == null ? void 0 : ht.playerState) == null ? void 0 : pt.player) == null ? void 0 : dt.position);
            const Dt = {
                t: 0,
                data: At,
                mediaLen: $,
                metaLen: j,
                metadata: Mt,
                frameCnt: _,
                server_ts: _e,
                isIDR: k,
                cacheRequest: tt,
                cached: et,
                cachedKey: rt,
                position: st
            };
            if (this.inPanoMode)
                return this.executeFunction("signal", {
                    signal: Mt,
                    pts: -1,
                    alreadyUpdateYUV: !0
                }),
                !0;
            if (this.decoderWorker.postMessage(Dt, [At.buffer]),
            !this.firstMediaReceived) {
                this.firstMediaArraval = Date.now();
                const Ct = this.firstMediaArraval - this.rtcp.network.room._startTime;
                log$l.infoAndReportMeasurement({
                    metric: "firstMediaArravalAt",
                    value: Ct,
                    group: "joinRoom"
                }),
                this.firstMediaReceived = !0
            }
        } else {
            const At = this.hasFrmCntInCache(_);
            if (At != -1)
                if (this.cacheFrameComposes[At].buffer.set(at, it),
                this.cacheFrameComposes[At].size += ot,
                this.cacheFrameComposes[At].size === nt) {
                    const gt = new Uint8Array(this.cacheFrameComposes[At].buffer).slice(0, nt);
                    this.cacheFrameComposes[At].frameCnt = -1,
                    this.cacheFrameComposes[At].size = 0,
                    this.cacheFrameComposes[At].startReceiveTime = 0,
                    this.cacheFrameComposes[At].serverTime = 0,
                    this.receivedMedia++,
                    _e - this.lastServerTS > 60 ? this.serverFrameSlow++ : _e - this.lastServerTS < 16 && this.serverFrameFast++;
                    const St = Date.now();
                    St - this.lastClientTS > 60 ? this.clientFrameSlow++ : St - this.lastClientTS < 16 && this.clientFrameFast++,
                    this.lastServerTS != 0 && (this.frameServerCircular.add(_e - this.lastServerTS),
                    this.frameClientCircular.add(St - this.lastClientTS)),
                    this.lastServerTS = _e,
                    this.lastClientTS = St;
                    const xt = gt.subarray(0, j)
                      , bt = Date.now()
                      , Rt = JSON.parse(this.Stringify(xt))
                      , Mt = Date.now();
                    this.showAllReceivedMetadata && console.log(_e, St, Rt),
                    this.metaParseAraay.push(Mt - bt),
                    (_t = Rt.traceIds) != null && _t.length && this.processMetaWithTraceId(Rt),
                    $ != 0 && this.moveStartPts == -1 && this.inMovingMode && (this.moveStartPts = d),
                    this.moveStartPts == d && (this.MoveResponseDelay = Date.now() - this.StartMovingTs);
                    const Pt = this.getIsMoving(Rt);
                    if (this.inMovingMode && Pt == 0 && this.lastIsMoving == 1 && this.clearMoveArray(),
                    typeof Pt != "undefined" && (this.lastIsMoving = Pt),
                    this.inMovingMode) {
                        const Dt = Date.now()
                          , Ct = Dt - this.lastMoveResponseTime;
                        this.moveResponseCircular.add(Ct),
                        this.lastMoveResponseTime = Dt
                    }
                    (et || tt) && (st = (Et = (yt = (vt = (mt = Rt.newUserStates) == null ? void 0 : mt.find(Dt=>Dt.userId === this._rtcp.network.room.userId)) == null ? void 0 : vt.playerState) == null ? void 0 : yt.player) == null ? void 0 : Et.position);
                    const It = {
                        t: 0,
                        data: gt,
                        mediaLen: $,
                        metaLen: j,
                        metadata: Rt,
                        frameCnt: _,
                        server_ts: _e,
                        isIDR: k,
                        cacheRequest: tt,
                        cached: et,
                        cachedKey: rt,
                        position: st
                    };
                    if (this.inPanoMode)
                        return this.executeFunction("signal", {
                            signal: Rt,
                            pts: -1,
                            alreadyUpdateYUV: !0
                        }),
                        !0;
                    if (this.decoderWorker.postMessage(It, [gt.buffer]),
                    !this.firstMediaReceived) {
                        this.firstMediaArraval = Date.now();
                        const Dt = this.firstMediaArraval - this.rtcp.network.room._startTime;
                        log$l.infoAndReportMeasurement({
                            metric: "firstMediaArravalAt",
                            value: Dt,
                            group: "joinRoom"
                        }),
                        this.firstMediaReceived = !0
                    }
                } else
                    this.cacheFrameComposes[At].size > nt && log$l.debug("I frame exceed, cache size is ", this.cacheSize, ", total size is ", nt);
            else if (At == -1) {
                let gt = this.hasFrmCntInCache(-1);
                if (gt == -1) {
                    let St = Date.now() + 1e18
                      , xt = -1;
                    for (let bt = 0; bt < this.cacheFrameComposes.length; bt++)
                        this.cacheFrameComposes[bt].serverTime < St && (St = this.cacheFrameComposes[bt].serverTime,
                        xt = bt);
                    gt = xt
                }
                this.cacheFrameComposes[gt].buffer.set(at, it),
                this.cacheFrameComposes[gt].size = ot,
                this.cacheFrameComposes[gt].frameCnt = _,
                this.cacheFrameComposes[gt].startReceiveTime = Date.now(),
                this.cacheFrameComposes[gt].serverTime = _e
            }
        }
        const ct = Date.now() - i;
        return this.unmarshalStreamExecutionArray.add(ct),
        !0
    }
    reset() {
        log$l.debug("Worker reset is called"),
        this.cacheFrameCnt = 0,
        this.receivedMedia = 0,
        this.reconnectSignal = !0,
        this.decoderWorker.postMessage({
            t: 4
        })
    }
    dataHandleOff(e) {
        log$l.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 i = new Uint8Array(e);
        if (i.length >= 4 && this.isHeartBeatPacket(i.buffer, i.length) == !0)
            return;
        if (i.length > 36 && this.unmarshalStream(i.buffer) == !0) {
            this.reconnectSignal && (this.executeFunction("reconnectedFrame", {}),
            this.reconnectSignal = !1);
            return
        }
        if (i.length > 20 && this.unmarshalPano(i.buffer) == !0)
            return;
        this.noWasmBytesReceived += e.byteLength;
        const o = JSON.parse(this.Stringify(i));
        this.executeFunction("signal", {
            signal: o,
            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(ar, rr) {
            return rr == -1 && (rr = 0),
            ar + rr
        }
        function i(ar, rr) {
            return Math.max(ar, rr)
        }
        const o = this.responseTimeArray.reduce(e, 0) / this.responseTimeArray.length || 0
          , s = this.processTimeArray.reduce(e, 0) / this.processTimeArray.length || 0
          , c = this.displayTimeArray.reduce(e, 0) / this.displayTimeArray.length || 0
          , d = this.overallTimeArray.reduce(e, 0) / this.overallTimeArray.length || 0
          , _ = this.overallTimeArray.length;
        this.responseTimeArray = [],
        this.processTimeArray = [],
        this.displayTimeArray = [],
        this.overallTimeArray = [];
        const b = this.joyStickResponseTimeArray.reduce(e, 0) / this.joyStickResponseTimeArray.length || 0
          , k = this.joyStickProcessTimeArray.reduce(e, 0) / this.joyStickProcessTimeArray.length || 0
          , j = this.joyStickDisplayTimeArray.reduce(e, 0) / this.joyStickDisplayTimeArray.length || 0
          , $ = this.joyStickOverallTimeArray.reduce(e, 0) / this.joyStickOverallTimeArray.length || 0
          , _e = this.joyStickResponseTimeArray.reduce(i, 0)
          , et = this.joyStickProcessTimeArray.reduce(i, 0)
          , tt = this.joyStickDisplayTimeArray.reduce(i, 0)
          , rt = this.joyStickOverallTimeArray.reduce(i, 0);
        this.joyStickResponseTimeArray = [],
        this.joyStickProcessTimeArray = [],
        this.joyStickDisplayTimeArray = [],
        this.joyStickOverallTimeArray = [];
        const it = this.moveResponseCircular.getThreshPercent()
          , nt = it[0]
          , ot = it[1]
          , at = it[2]
          , st = it[3]
          , ut = it[4]
          , ct = ut - st
          , lt = 1 - ot / ut || 0
          , ft = [nt, ot - nt, at - ot, st - at, ct]
          , ht = this.moveProcessCircular.getThreshPercent()
          , pt = ht[0]
          , dt = ht[1]
          , _t = ht[2]
          , mt = ht[3]
          , vt = ht[4]
          , yt = vt - mt
          , Et = 1 - dt / vt || 0
          , At = [pt, dt - pt, _t - dt, mt - _t, yt]
          , gt = this.moveDisplayCircular.getThreshPercent()
          , St = gt[0]
          , xt = gt[1]
          , bt = gt[2]
          , Rt = gt[3]
          , Mt = gt[4]
          , Pt = Mt - Rt
          , It = 1 - xt / Mt || 0
          , Dt = [St, xt - St, bt - xt, Rt - bt, Pt]
          , Ct = St
          , Ot = xt - St
          , wt = bt - xt
          , Nt = Rt - bt
          , Ft = Pt
          , Vt = this.moveResponseCircular.getAvg()
          , Lt = this.moveProcessCircular.getAvg()
          , kt = this.moveDisplayCircular.getAvg()
          , Bt = this.moveResponseCircular.getMax()
          , Ut = this.moveProcessCircular.getMax()
          , Gt = this.moveDisplayCircular.getMax()
          , Ht = this.moveResponseCircular.getStandardDeviation()
          , zt = this.moveProcessCircular.getStandardDeviation()
          , Wt = 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 Kt = this.frameServerCircular.getAvg()
          , Qt = this.frameServerCircular.getMax();
        this.frameClientCircular.getAvg(),
        this.frameClientCircular.getMax();
        const qt = this.metaParseAraay.reduce(e, 0) / this.metaParseAraay.length || 0
          , Yt = this.metaParseAraay.reduce(i, 0);
        this.metaParseAraay = [];
        const Jt = this.unmarshalStreamExecutionArray.getStat()
          , jt = this.receiveYUVExecutionArray.getStat()
          , Xt = this.postMessageWaitArray.getStat().max
          , nr = {
            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,
            noWasmBytesReceived: this.noWasmBytesReceived,
            receiveIframes: this.receiveIframes,
            decodeIframes: this.decodeIframes,
            avgResponseTime: o,
            avgProcessTime: s,
            avgDisplayTime: c,
            avgOverallTime: d,
            overallTimeCount: _,
            responseMiss: this.responseMiss,
            processMiss: this.processMiss,
            displayMiss: this.displayMiss,
            updateDropFrame: this.updateDropFrame,
            moveEvent: this.moveEvent,
            avgResponseMoveDiff: this.moveEvent == "MoveTo" ? Vt : 0,
            avgProcessMoveDiff: this.moveEvent == "MoveTo" ? Lt : 0,
            avgDisplayMoveDiff: this.moveEvent == "MoveTo" ? kt : 0,
            maxResponseMoveDiff: this.moveEvent == "MoveTo" ? Bt : 0,
            maxProcessMoveDiff: this.moveEvent == "MoveTo" ? Ut : 0,
            maxDisplayMoveDiff: this.moveEvent == "MoveTo" ? Gt : 0,
            moveResponseJank: this.moveEvent == "MoveTo" ? lt : 0,
            moveProcessJank: this.moveEvent == "MoveTo" ? Et : 0,
            moveDisplayJank: this.moveEvent == "MoveTo" ? It : 0,
            moveResponseCounts: this.moveEvent == "MoveTo" ? ft.toString() : "0,0,0,0,0",
            moveProcessCounts: this.moveEvent == "MoveTo" ? At.toString() : "0,0,0,0,0",
            moveDisplayCounts: this.moveEvent == "MoveTo" ? Dt.toString() : "0,0,0,0,0",
            MoveDisplayCountGood: this.moveEvent == "MoveTo" ? Ct.toString() : "0",
            MoveDisplayCountWell: this.moveEvent == "MoveTo" ? Ot.toString() : "0",
            MoveDisplayCountFair: this.moveEvent == "MoveTo" ? wt.toString() : "0",
            MoveDisplayCountBad: this.moveEvent == "MoveTo" ? Nt.toString() : "0",
            MoveDisplayCountRest: this.moveEvent == "MoveTo" ? Ft.toString() : "0",
            moveResponseDelay: this.moveEvent == "MoveTo" ? this.MoveResponseDelay : 0,
            moveProcessDelay: this.moveEvent == "MoveTo" ? this.MoveProcessDelay : 0,
            moveDisplayDelay: this.moveEvent == "MoveTo" ? this.MoveDisplayDelay : 0,
            sdMoveResponseLongTime: Ht,
            sdMoveProcessLongTime: zt,
            sdMoveDisplayLongTime: Wt,
            avgResponseFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? Vt : 0,
            avgProcessFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? Lt : 0,
            avgDisplayFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? kt : 0,
            maxResponseFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? Bt : 0,
            maxProcessFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? Ut : 0,
            maxDisplayFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? Gt : 0,
            flyResponseJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? lt : 0,
            flyProcessJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? Et : 0,
            flyDisplayJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? It : 0,
            flyResponseCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? ft.toString() : "0,0,0,0,0",
            flyProcessCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? At.toString() : "0,0,0,0,0",
            flyDisplayCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? Dt.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: qt,
            maxMetaParseTime: Yt,
            avgServerDiff: Kt,
            maxServerDiff: Qt,
            unmarshalStreamStat: Jt,
            receiveYUVStat: jt,
            maxPostMsgDiff: Xt,
            streamType: WASM_Version,
            avgJoyStickResponseTime: b,
            avgJoyStickProcessTime: k,
            avgJoyStickDisplayTime: j,
            avgJoyStickOverallTime: $,
            maxJoyStickResponseTime: _e,
            maxJoyStickProcessTime: et,
            maxJoyStickDisplayTime: tt,
            maxJoyStickOverallTime: rt
        };
        return this.lastReturnFrames = this.returnFrames,
        this.lastReceivedEmit = this.receivedEmit,
        nr
    }
}
const log$k = new Logger("rtcp");
class Rtcp extends EventEmitter {
    constructor(i) {
        super();
        Tt(this, "connection", null);
        Tt(this, "inputChannel", null);
        Tt(this, "mediaStream");
        Tt(this, "socket");
        Tt(this, "connected", !1);
        Tt(this, "candidates", []);
        Tt(this, "isAnswered", !1);
        Tt(this, "isFlushing", !1);
        Tt(this, "inputReady", !1);
        Tt(this, "workers");
        Tt(this, "actived", !0);
        Tt(this, "heartbeat");
        Tt(this, "onIcecandidate", i=>{
            if (i.candidate != null) {
                const o = JSON.stringify(i.candidate);
                log$k.debug(`Got ice candidate: ${o}`),
                this.network.socket.send({
                    id: "ice_candidate",
                    data: btoa(o)
                })
            }
        }
        );
        Tt(this, "onIcecandidateerror", i=>{
            log$k.error("onicecandidateerror", i.errorCode, i.errorText, i)
        }
        );
        Tt(this, "onIceStateChange", i=>{
            switch (i.target.iceGatheringState) {
            case "gathering":
                log$k.info("ice gathering");
                break;
            case "complete":
                log$k.info("Ice gathering completed")
            }
        }
        );
        Tt(this, "onIceConnectionStateChange", ()=>{
            if (!!this.connection)
                switch (log$k.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
                    }
                }
        }
        );
        Tt(this, "setRemoteDescription", async(i,o)=>{
            var _, b, k;
            if (!this.connection)
                return;
            const s = JSON.parse(atob(i))
              , c = new RTCSessionDescription(s);
            await this.connection.setRemoteDescription(c);
            const d = await this.connection.createAnswer();
            if (d.sdp = (_ = d.sdp) == null ? void 0 : _.replace(/(a=fmtp:111 .*)/g, "$1;stereo=1;sprop-stereo=1"),
            ((k = (b = d.sdp) == null ? void 0 : b.match(/a=mid:1/g)) == null ? void 0 : k.length) == 2) {
                const j = d.sdp.lastIndexOf("a=mid:1");
                d.sdp = d.sdp.slice(0, j) + "a=mid:2" + d.sdp.slice(j + 7)
            }
            try {
                await this.connection.setLocalDescription(d)
            } catch (j) {
                log$k.error("error", j)
            }
            this.isAnswered = !0,
            this.network.rtcp.flushCandidate(),
            this.network.socket.send({
                id: "answer",
                data: btoa(JSON.stringify(d))
            }),
            o.srcObject = this.mediaStream
        }
        );
        Tt(this, "flushCandidate", ()=>{
            this.isFlushing || !this.isAnswered || (this.isFlushing = !0,
            this.candidates.forEach(i=>{
                const o = atob(i)
                  , s = JSON.parse(o);
                if (/172\./.test(s.candidate))
                    return;
                const c = new RTCIceCandidate(s);
                this.connection && this.connection.addIceCandidate(c).then(()=>{}
                , d=>{
                    log$k.info("add candidate failed", d)
                }
                )
            }
            ),
            this.isFlushing = !1)
        }
        );
        Tt(this, "input", i=>{
            var o;
            !this.actived || !this.inputChannel || this.inputChannel.readyState === "open" && ((o = this.inputChannel) == null || o.send(i))
        }
        );
        this.network = i,
        this.workers = new Workers(this,new Logger("decode")),
        this.workers.registerLogger(new Logger("decode")),
        this.workers.registerFunction("data", o=>{
            this.emit("data", o)
        }
        ),
        this.heartbeat = new Heartbeat({
            ping: o=>{
                i.room.actionsHandler.echo(o)
            }
            ,
            pong(o, s) {
                var c;
                s && o > 500 && log$k.warn(`high hb value ${o}, traceId:` + s),
                (c = i.room.stats) == null || c.assign({
                    hb: o
                })
            }
        })
    }
    start() {
        this.connection = new RTCPeerConnection;
        const i = Date.now();
        this.connection.ondatachannel = o=>{
            log$k.info(`ondatachannel: ${o.channel.label}`),
            this.inputChannel = o.channel,
            this.inputChannel.onopen = ()=>{
                var s;
                log$k.info("The input channel has opened, id:", (s = this.inputChannel) == null ? void 0 : s.id),
                this.inputReady = !0,
                this.emit("rtcConnected"),
                this.network.room.currentNetworkOptions.reconnect || (log$k.infoAndReportMeasurement({
                    metric: "datachannelOpenedAt",
                    startTime: this.network.room._startTime,
                    group: "joinRoom"
                }),
                log$k.infoAndReportMeasurement({
                    metric: "datachannelOpenedCost",
                    startTime: i,
                    group: "joinRoom"
                }))
            }
            ,
            this.inputChannel.onclose = ()=>{
                var s;
                return log$k.info("The input channel has closed, id:", (s = this.inputChannel) == null ? void 0 : s.id)
            }
            ,
            this.inputChannel.onmessage = s=>{
                this.workers.dataHandle(s.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(i) {
        i === "" ? this.network.rtcp.flushCandidate() : this.candidates.push(i)
    }
    disconnect() {
        var i, o, s;
        this.heartbeat.stop(),
        log$k.info("ready to close datachannel, id", (i = this.inputChannel) == null ? void 0 : i.id),
        (o = this.inputChannel) == null || o.close(),
        (s = this.connection) == null || s.close(),
        this.connection = null,
        this.inputChannel = null
    }
    sendStringData(i) {
        this.input(i)
    }
    sendData(i) {
        let o = "";
        try {
            o = JSON.stringify(i)
        } catch (s) {
            log$k.error(s);
            return
        }
        this.input(o)
    }
}
class Timeout {
    constructor(e, i, o=!0) {
        Tt(this, "_fn");
        Tt(this, "_delay");
        Tt(this, "_timeout");
        this._fn = e,
        this._delay = i,
        o && 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$j = new Logger("ws");
class Socket extends EventEmitter {
    constructor(i) {
        super();
        Tt(this, "_ws");
        Tt(this, "_openTimer");
        Tt(this, "connected", !1);
        Tt(this, "_hasTimeout", !1);
        Tt(this, "heartbeat");
        Tt(this, "latency", (i,o)=>this.send({
            id: "checkLatency",
            data: JSON.stringify(i),
            packet_id: o
        }));
        Tt(this, "send", i=>{
            if (this.wsNoReady())
                return;
            const o = JSON.stringify(i);
            i.id !== "heartbeat" && log$j.info("send ws frame", o),
            this._ws.send(o)
        }
        );
        Tt(this, "startGame", ()=>{
            const {roomId: i, userId: o, avatarId: s, skinId: c, role: d, avatarComponents: _, versionId: b, rotationRenderType: k, isAllSync: j, nickname: $, avatarScale: _e, appId: et, camera: tt, player: rt, firends: it, syncByEvent: nt, areaName: ot, attitude: at, pathName: st, person: ut, roomTypeId: ct="", syncToOthers: lt, hasAvatar: ft, prioritySync: ht, extra: pt={}, removeWhenDisconnected: dt} = this.network.room.currentNetworkOptions;
            pt.removeWhenDisconnected = dt;
            const _t = {
                id: "start",
                room_id: i,
                user_id: o,
                trace_id: uuid$1(),
                data: JSON.stringify({
                    avatar_components: JSON.stringify(_),
                    avatar_id: s,
                    skin_id: c,
                    is_host: d ? d == "host" : !0,
                    skin_data_version: c !== void 0 && b !== void 0 ? c + b : void 0,
                    rotation_render_type: k,
                    is_all_sync: j,
                    nick_name: encodeURIComponent($ || ""),
                    app_id: et,
                    camera: tt,
                    player: rt,
                    person: ut,
                    firends: JSON.stringify(it),
                    sync_by_event: nt,
                    area_name: ot,
                    path_name: st,
                    attitude: at,
                    room_type_id: ct,
                    syncToOthers: lt,
                    hasAvatar: ft,
                    avatarSize: _e,
                    prioritySync: ht,
                    extra: JSON.stringify(pt)
                })
            };
            this.send(_t);
            const mt = JSON.parse(_t.data);
            delete mt.token,
            log$j.infoAndReportMeasurement({
                metric: "startGame",
                extra: mt,
                startTime: Date.now()
            })
        }
        );
        this.network = i,
        this.heartbeat = new Heartbeat({
            ping: o=>{
                var s;
                if (!this.connected) {
                    this.heartbeat.stop(),
                    (s = i.room.stats) == null || s.assign({
                        rtt: 0
                    });
                    return
                }
                this.send({
                    id: "heartbeat",
                    data: o
                })
            }
            ,
            pong(o) {
                var s;
                (s = i.room.stats) == null || s.assign({
                    rtt: o
                })
            }
        })
    }
    get connection() {
        return this._ws
    }
    start() {
        this._hasTimeout = !1;
        const i = this.getAddress();
        log$j.info(`connecting to ${i}`);
        const o = Date.now();
        this._ws = new WebSocket(i),
        this._openTimer = new Timeout(()=>{
            const s = `Failed to open websocket in ${DEFAULT_OPEN_TIMEOUT_MS} ms`;
            this._hasTimeout = !0,
            this.emit("socketClosed", new InitNetworkTimeoutError(s))
        }
        ,DEFAULT_OPEN_TIMEOUT_MS),
        this._ws.onopen = ()=>{
            var s;
            (s = this._openTimer) == null || s.clear(),
            this.connected = !0,
            this.heartbeat.start(),
            this.network.room.currentNetworkOptions.reconnect || (log$j.infoAndReportMeasurement({
                metric: "wsOpenedAt",
                group: "joinRoom",
                startTime: this.network.room._startTime
            }),
            log$j.infoAndReportMeasurement({
                metric: "wsOpenedCost",
                group: "joinRoom",
                startTime: o
            }))
        }
        ,
        this.handleWSEvent()
    }
    getAddress() {
        const {wsServerUrl: i, reconnect: o, sessionId: s, token: c, roomId: d, userId: _, pageSession: b} = this.network.room.currentNetworkOptions
          , k = this.network.room.skinId;
        let j = i;
        o && (j = j + `?reconnect=true&lastSessionID=${s}`);
        const $ = `userId=${_}&roomId=${d}&pageSession=${b}` + (this.network.room.isHost ? `&skinId=${k}` : "") + (c ? `&token=${c}` : "");
        return j = j.indexOf("?") > -1 ? j + "&" + $ : j + "?" + $,
        j
    }
    handleWSEvent() {
        const i = this._ws;
        i.addEventListener("error", o=>{
            this.connected = !1,
            log$j.error("webscoket error", o),
            this.emit("socketClosed", new InternalError("connect to address error: " + this.network.room.currentNetworkOptions.wsServerUrl))
        }
        ),
        i.addEventListener("close", o=>{
            this.connected = !1,
            this._onClose(o)
        }
        ),
        i.addEventListener("message", o=>{
            if (!o || this._hasTimeout || !this.connected)
                return;
            let s = null;
            try {
                s = JSON.parse(o.data)
            } catch (d) {
                log$j.error(d);
                return
            }
            if (!s)
                return;
            const c = s.id;
            if (!!c)
                switch (c !== "heartbeat" && log$j.info(`receive ws frame: ${o.data}`),
                c) {
                case "fail":
                    break;
                case "init":
                    try {
                        const d = s.data.slice(-37, -1);
                        reporter.updateBody({
                            serverSession: d
                        })
                    } catch (d) {
                        console.error(d)
                    }
                    this.network.rtcp.start();
                    break;
                case "heartbeat":
                    this.heartbeat.pong(s.data);
                    break;
                case "offer":
                    this.network.rtcp.setRemoteDescription(s.data, this.network.stream.el);
                    break;
                case "ice_candidate":
                    this.network.rtcp.addCandidate(s.data);
                    break;
                case "start":
                    this.emit("gameRoomAvailable", s);
                    break;
                case "error":
                    try {
                        const {Code: d, Msg: _} = JSON.parse(s.data);
                        if (d) {
                            if (d == 3003)
                                return this.emit("socketClosed", new TokenExpiredError);
                            if (authenticationErrorCodes.indexOf(d) > -1)
                                return this.emit("socketClosed", new AuthenticationError("\u9274\u6743\u9519\u8BEF:" + _));
                            {
                                const b = getErrorByCode(d);
                                this.emit("socketClosed", new b(_))
                            }
                        }
                    } catch (d) {
                        const _ = new InternalError("JSON.parse websocket data error: " + s.data);
                        log$j.error(d, _),
                        this.emit("socketClosed", _)
                    }
                    break;
                case "checkLatency":
                    {
                        const d = s.packet_id
                          , _ = s.data.split(",");
                        this.onLatencyCheck({
                            packetId: d,
                            addresses: _
                        });
                        break
                    }
                default:
                    log$j.warn("unkown ws message type", c, s)
                }
        }
        )
    }
    onLatencyCheck(i) {
        const o = [...new Set(i.addresses || [])];
        Promise.all(o.map(s=>({
            [s]: 9999
        }))).then(s=>{
            const c = Object.assign({}, ...s);
            this.latency(c, i.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: i, reason: o}) {
        this._openTimer && this._openTimer.clear(),
        log$j.warn(`ws closed: ${i} ` + o),
        [WS_CLOSE_RECONNECT, WS_CLOSE_NORMAL].includes(i) || this.emit("socketClosed", new InternalError("Websocket error"))
    }
    _close({code: i, reason: o}) {
        var s;
        (s = this._ws) == null || s.close(i, o)
    }
    quit() {
        this._close({
            code: WS_CLOSE_NORMAL,
            reason: "quit"
        })
    }
}
const log$i = new Logger("stream");
class Stream {
    constructor(e) {
        Tt(this, "el");
        Tt(this, "_streamPlayTimer", null);
        Tt(this, "play", ()=>new Promise((e,i)=>{
            this._streamPlayTimer = new Timeout(()=>{
                i(new InternalError("Stream play timeout"))
            }
            ,5e3),
            this.el && this.el.play().then(()=>{
                var o;
                e(),
                log$i.info("Media can autoplay"),
                (o = this._streamPlayTimer) == null || o.clear()
            }
            ).catch(o=>{
                var s;
                log$i.error("Media Failed to autoplay"),
                log$i.error(o),
                i(new InternalError("Media Failed to autoplay")),
                (s = this._streamPlayTimer) == null || s.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$h = new Logger("NetworkController")
  , hr = class extends EventEmitter {
    constructor(i) {
        super();
        Tt(this, "socket");
        Tt(this, "rtcp");
        Tt(this, "stream");
        Tt(this, "_state", "connecting");
        Tt(this, "_networkMonitor");
        Tt(this, "reconnectCount", 0);
        Tt(this, "startGame", ()=>new Promise((i,o)=>{
            if (!this.rtcp.connected)
                return o(new InternalError("Game cannot load. Please refresh"));
            if (!this.rtcp.inputReady)
                return o(new InternalError("Game is not ready yet. Please wait"));
            this.socket.on("gameRoomAvailable", s=>{
                this.setState("connected"),
                i(s),
                this.rtcp.heartbeat.start()
            }
            ),
            this.socket.on("socketClosed", s=>{
                o(s)
            }
            ),
            this.socket.startGame()
        }
        ));
        this.room = i,
        this.socket = new Socket(this),
        this.rtcp = new Rtcp(this),
        this.stream = new Stream,
        this._networkMonitor = new NetworkMonitor(()=>{
            log$h.info("network changed, online:", this._networkMonitor.isOnline),
            this._state === "disconnected" && this._networkMonitor.isOnline && (log$h.info("network back to online, try to reconnect"),
            this.reconnect())
        }
        ),
        checkNetworkQuality(this.room.currentNetworkOptions.wsServerUrl),
        this._networkMonitor.start(),
        new VisibilityChangeHandler().subscribe(s=>{
            var c, d;
            s ? ((d = this.room.stats) == null || d.disable(),
            this.room.pageHideHandler(),
            log$h.infoAndReportMeasurement({
                metric: "pageHide",
                startTime: Date.now()
            })) : ((c = this.room.stats) == null || c.enable(),
            this.room.pageShowHandler(),
            log$h.infoAndReportMeasurement({
                metric: "pageShow",
                startTime: Date.now(),
                extra: {
                    state: this._state
                }
            }),
            this._state === "disconnected" && this.reconnect())
        }
        )
    }
    setState(i) {
        this._state !== i && (this._state === "closed" && !hr.ALLOW_RECONNECT_AFTER_QUIT || (log$h.info("Set network state to ", i),
        this._state = i))
    }
    async connectAndStart(i) {
        return this.connect(i).then(this.startGame)
    }
    async connect(i=!1) {
        return this.room.updateCurrentNetworkOptions({
            reconnect: i
        }),
        new Promise((o,s)=>{
            this.rtcp.on("rtcConnected", ()=>{
                this.setState("connected"),
                o()
            }
            ),
            this.rtcp.on("rtcDisconnected", ()=>{
                log$h.info("rtc disconnected"),
                this._state === "connecting" ? (this.setState("disconnected"),
                s(new InternalError("rtc connect failed"))) : (this.setState("disconnected"),
                log$h.info("rtc disconnected, start to reconnect"),
                this.reconnect())
            }
            ),
            this.socket.on("socketQuit", ()=>{
                log$h.info("socket quit success"),
                this.setState("closed")
            }
            ),
            this.socket.on("socketClosed", c=>{
                this._state === "connecting" && (this.setState("disconnected"),
                s(c)),
                s(c)
            }
            ),
            this.socket.start()
        }
        )
    }
    reconnect() {
        const i = Date.now();
        if (this.reconnectCount++,
        this.reconnectCount > MAX_RECONNECT_COUNT) {
            log$h.error("reconnect failed, reached max reconnect count", MAX_RECONNECT_COUNT),
            this.reconnectCount = 0,
            this.emit("stateChanged", {
                state: "disconnected"
            });
            return
        }
        return log$h.info("start reconnect, count:", this.reconnectCount),
        this._reconnect().then(()=>{
            log$h.infoAndReportMeasurement({
                startTime: i,
                metric: "reconnect"
            })
        }
        ).catch(o=>{
            if (log$h.infoAndReportMeasurement({
                startTime: i,
                metric: "reconnect",
                error: o
            }),
            (o == null ? void 0 : o.code) === Codes$1.RepeatLogin) {
                this.room.handleRepetLogin();
                return
            }
            const s = 1e3;
            log$h.info("reconnect failed, wait " + s + " ms for next reconnect"),
            setTimeout(()=>{
                this.reconnect()
            }
            , s)
        }
        )
    }
    _reconnect() {
        return this._state === "closed" ? (log$h.warn("connection closed already"),
        Promise.reject()) : this._state === "connecting" ? (log$h.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: i})=>{
            this.room.updateCurrentNetworkOptions({
                sessionId: i
            }),
            reporter.updateBody({
                serverSession: i
            }),
            log$h.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: i, player: o} = this.room.currentClickingState || {};
        i && o && this.room.updateCurrentNetworkOptions({
            camera: i,
            player: o
        })
    }
    sendRtcData(i) {
        this.rtcp.sendData(i)
    }
    sendSocketData(i) {
        log$h.debug("ws send ->", i),
        this.socket.send(i)
    }
    quit() {
        const i = uuid$1()
          , o = {
            action_type: Actions.Exit,
            trace_id: i,
            exit_action: {},
            user_id: this.room.options.userId,
            packet_id: i
        };
        this.setState("closed"),
        this.socket.quit(),
        this.sendRtcData(o)
    }
}
;
let NetworkController = hr;
Tt(NetworkController, "ALLOW_RECONNECT_AFTER_QUIT", !0);
let DecodeFunctionTimeList = []
  , SDKFunctionTimeList = []
  , EngineFunctionTimeList = []
  , OtherFunctionTimeList = []
  , HeavyFunctionList = [];
function getSum(a) {
    let e = 0;
    for (let i = 0; i < a.length; i++)
        e += a[i];
    return e || 0
}
function getMax(a) {
    let e = 0;
    for (let i = 0; i < a.length; i++)
        e < a[i] && (e = a[i]);
    return e
}
function getFuncStat() {
    const a = {
        sum: getSum(DecodeFunctionTimeList),
        max: getMax(DecodeFunctionTimeList)
    }
      , e = {
        sum: getSum(SDKFunctionTimeList),
        max: getMax(SDKFunctionTimeList)
    }
      , i = {
        sum: getSum(EngineFunctionTimeList),
        max: getMax(EngineFunctionTimeList)
    }
      , o = {
        sum: getSum(OtherFunctionTimeList),
        max: getMax(OtherFunctionTimeList)
    }
      , s = HeavyFunctionList;
    return DecodeFunctionTimeList = [],
    SDKFunctionTimeList = [],
    EngineFunctionTimeList = [],
    OtherFunctionTimeList = [],
    HeavyFunctionList = [],
    {
        function: s,
        decode: a,
        sdk: e,
        engine: i,
        other: o
    }
}
const SAMPLES_LENGTH = 10
  , log$g = new Logger("stats")
  , numberFormat = new Intl.NumberFormat(window.navigator.language,{
    maximumFractionDigits: 0
});
class Stats extends EventEmitter {
    constructor(i) {
        super();
        Tt(this, "_netInterval", null);
        Tt(this, "_disabled", !1);
        Tt(this, "_aggregatedStats", {});
        Tt(this, "isNetworkGood", !0);
        Tt(this, "_displayElements", {});
        Tt(this, "showStatus", {
            default: !1,
            extra: !1
        });
        Tt(this, "_extraStats", {});
        Tt(this, "_networkSamples", []);
        Tt(this, "externalStats");
        Tt(this, "constructedTime");
        Tt(this, "_interval");
        this.room = i,
        this.constructedTime = Date.now(),
        this._interval = window.setInterval(()=>{
            if (this._disabled || !i.joined)
                return;
            this.onStats(i.networkController.rtcp.workers.uploadDataToServer());
            const o = i.signal.getSignalStat()
              , s = i.sceneManager.engineRunTimeStats
              , c = s.timeArray_addAvatarToScene.getStat()
              , d = s.timeArray_loadStaticMesh.getStat()
              , _ = s.timeArray_updateStaticMesh.getStat();
            this._aggregatedStats.engineCPUSum = c.sum + d.sum + _.sum,
            this._aggregatedStats.engineCPUMax = Math.max(c.max, d.max, _.max),
            this._aggregatedStats.sdkSignalPartial = o.partialMax.toString(),
            this._aggregatedStats.sdkCPUAvg = o.sdkAvg,
            this._aggregatedStats.sdkCPUMax = o.sdkMax,
            this._aggregatedStats.sdkBlobSum = o.blobSum,
            this._aggregatedStats.sdkBlobMax = o.blobMax;
            const k = getFuncStat().function;
            let j = "<br />";
            for (let$ = 0; $ < k.length; $++)
                j += k[$].name + ": " + k[$].time.toFixed(0) + "<br />";
            this._aggregatedStats.heavyFunc = j
        }
        , 1e3),
        this._netInterval = window.setInterval(()=>{
            this.checkNetworkQuality()
        }
        , DURATION * 1e3)
    }
    get isShow() {
        return this.showStatus.default || this.showStatus.extra
    }
    isStatsShow(i="default") {
        return this.showStatus[i]
    }
    assign(i) {
        Object.assign(this._extraStats, i),
        ((i == null ? void 0 : i.hb) || (i == null ? void 0 : i.rtt)) && this.startStatsNetSamples()
    }
    appendExternalStats(i) {
        const o = {};
        if (!i || typeof i != "object") {
            console.warn("appendExternalStats should be plain object");
            return
        }
        Object.keys(i).forEach(s=>{
            Object.prototype.hasOwnProperty.call(this._aggregatedStats, s) ? console.warn(`${s} is duplicate with internal stats`) : o[s] = i[s]
        }
        ),
        !(Object.keys(o).length > 10) && (this.externalStats = o)
    }
    getRtt() {
        const i = this._extraStats.rtt;
        return typeof i != "number" ? 0 : i > 999 ? 999 : i
    }
    enable() {
        this._disabled = !1
    }
    disable() {
        this._disabled = !0
    }
    disableNet() {
        this._netInterval && window.clearInterval(this._netInterval)
    }
    show(i="default") {
        this.showStatus[i] = !0,
        this._render(i)
    }
    hide(i="default") {
        this.showStatus[i] = !1;
        const o = this._displayElements[i];
        o && document.body.removeChild(o),
        this._displayElements[i] = null
    }
    checkNetworkQuality() {
        if (this._networkSamples.length < SAMPLES_LENGTH || this.room.networkController._state !== "connected")
            return;
        const o = this._networkSamples.map($=>this.isNetDelay($, "rtt"))
          , s = this._networkSamples.map($=>this.isNetDelay($, "hb"))
          , c = o.reduce(($,_e)=>$ + _e, 0)
          , d = s.reduce(($,_e)=>$ + _e, 0)
          , _ = Math.floor(c / this._networkSamples.length) * 100
          , b = Math.floor(d / this._networkSamples.length) * 100
          , k = 70;
        let j = !0;
        (_ >= k || b >= k) && (j = !1),
        this.isNetworkGood = j,
        this.emit("networkQuality", {
            good: j
        }),
        j || this.emit("weakNetwork"),
        this.isNetworkGood !== j && log$g.infoAndReportMeasurement({
            metric: "networkQualityChange",
            startTime: Date.now(),
            extra: {
                msg: this._networkSamples,
                netDelayRTTValues: c,
                netDelayHBValues: d,
                isNetworkGood: j
            }
        })
    }
    startStatsNetSamples() {
        const {rtt: i, hb: o} = this._extraStats;
        if (i || o) {
            const s = {
                rtt: i,
                hb: o,
                time: Date.now()
            };
            this._networkSamples.unshift(s),
            this._networkSamples.splice(SAMPLES_LENGTH)
        }
    }
    isNetDelay(i, o) {
        return o === "rtt" ? i.rtt > RTT_MAX_VALUE ? 1 : 0 : o === "hb" && i.hb > HB_MAX_VALUE ? 1 : 0
    }
    _render(i) {
        var $, _e, et, tt, rt, it, nt, ot, at, st, ut, ct, lt, ft, ht, pt, dt, _t, mt, vt, yt, Et, At, gt, St, xt, bt, Rt, Mt, Pt, It, Dt, Ct;
        if (!this._aggregatedStats)
            return;
        const o = []
          , s = Date.now() - this.constructedTime
          , c = Math.floor(s / 1e3 % 60)
          , d = Math.floor(s / (1e3 * 60) % 60)
          , _ = Math.floor(s / (1e3 * 60 * 60) % 24)
          , b = _ < 10 ? "0" + _.toString() : _.toString()
          , k = d < 10 ? "0" + d : d
          , j = c < 10 ? "0" + c : c;
        if (o.push({
            key: new Date(Math.floor(this._aggregatedStats.timestamp || 0)).toLocaleString("en-GB"),
            value: b + ":" + k + ":" + j
        }),
        o.push({
            key: "rtt: " + this._extraStats.rtt + " hb: " + this._extraStats.hb,
            value: "FPS: " + this._extraStats.fps + " avatar: " + (($ = this.room._userAvatar) == null ? void 0 : $.state)
        }),
        o.push({
            key: "SDK: " + Xverse$1.SUB_PACKAGE_VERSION,
            value: "ENGINE:" + VERSION$1 + " uid:" + this._extraStats.userId
        }),
        o.push({
            key: "\u540C\u6B65/\u6709\u6548/\u663E\u793A\u73A9\u5BB6",
            value: `${this._extraStats.syncUserNum || 0}/${this._extraStats.userNum || 0}/${this._extraStats.renderedUserNum || 0}`
        }),
        o.push({
            key: "media/meta bitrate(kbps)",
            value: numberFormat.format(this._aggregatedStats.mediaBitrate || 0) + "/" + numberFormat.format(this._aggregatedStats.metaBitrate || 0)
        }),
        o.push({
            key: ":----------------Decoding---------------",
            value: ""
        }),
        o.push({
            key: "-max/avg decodeTime(ms)",
            value: numberFormat.format(this._aggregatedStats.decodeTimeMaxFrame || 0) + "/" + numberFormat.format(this._aggregatedStats.decodeTimePerFrame || 0)
        }),
        o.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
        }),
        o.push({
            key: ":----------------FrameLoop-------------",
            value: ""
        }),
        o.push({
            key: "interval(max/avg/>40)",
            value: (((_e = this._extraStats.maxFrameTime) == null ? void 0 : _e.toFixed(1)) || 0) + "/" + (((et = this._extraStats.avgFrameTime) == null ? void 0 : et.toFixed(0)) || 0) + "/" + this._extraStats.engineSloppyCnt
        }),
        o.push({
            key: "systemStuck",
            value: this._extraStats.systemStuckCnt
        }),
        o.push({
            key: "--update",
            value: (this._aggregatedStats.maxGraphicTime.toFixed(1) || 0) + "/" + (((tt = this._aggregatedStats.averageGraphicTime) == null ? void 0 : tt.toFixed(0)) || 0)
        }),
        o.push({
            key: "--timeout",
            value: (((rt = this._extraStats.maxTimeoutTime) == null ? void 0 : rt.toFixed(1)) || 0) + "/" + ((it = this._extraStats.avgTimeoutTime) == null ? void 0 : it.toFixed(0)) || 0
        }),
        o.push({
            key: "--render",
            value: (((nt = this._extraStats.maxRenderFrameTime) == null ? void 0 : nt.toFixed(1)) || 0) + "/" + (((ot = this._extraStats.renderFrameTime) == null ? void 0 : ot.toFixed(0)) || 0)
        }),
        o.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)
        }),
        o.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)
        }),
        o.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)
        }),
        o.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)
        }),
        o.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)
        }),
        o.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)
        }),
        o.push({
            key: "--registerBF/AF(Num)",
            value: (this._extraStats.registerBeforeCount.toFixed(0) || 0) + " / " + (this._extraStats.registerAfterCount.toFixed(0) || 0)
        }),
        o.push({
            key: ":----------------JoyStick----------------------",
            value: ""
        }),
        o.push({
            key: "Total(avg/max)",
            value: (((at = this._aggregatedStats.avgJoyStickOverallTime) == null ? void 0 : at.toFixed(2)) || 0) + "/" + (((st = this._aggregatedStats.maxJoyStickOverallTime) == null ? void 0 : st.toFixed(2)) || 0)
        }),
        o.push({
            key: "--Rsp(avg/max)",
            value: (((ut = this._aggregatedStats.avgJoyStickResponseTime) == null ? void 0 : ut.toFixed(1)) || 0) + "/" + this._aggregatedStats.maxJoyStickResponseTime
        }),
        o.push({
            key: "--Proc(avg/max)",
            value: (((ct = this._aggregatedStats.avgJoyStickProcessTime) == null ? void 0 : ct.toFixed(1)) || 0) + "/" + this._aggregatedStats.maxJoyStickProcessTime
        }),
        o.push({
            key: "--Show(avg/max)",
            value: (((lt = this._aggregatedStats.avgJoyStickDisplayTime) == null ? void 0 : lt.toFixed(1)) || 0) + "/" + this._aggregatedStats.maxJoyStickDisplayTime
        }),
        o.push({
            key: ":----------------Rotation-------------------",
            value: ""
        }),
        o.push({
            key: "Total(ms/miss)",
            value: (((ft = this._aggregatedStats.avgOverallTime) == null ? void 0 : ft.toFixed(2)) || 0) + "/" + (this._aggregatedStats.responseMissPs + this._aggregatedStats.processMissPs + this._aggregatedStats.displayMissPs)
        }),
        o.push({
            key: "--rotateRsp",
            value: (((ht = this._aggregatedStats.avgResponseTime) == null ? void 0 : ht.toFixed(1)) || 0) + "/" + this._aggregatedStats.responseMissPs
        }),
        o.push({
            key: "--rotateProc",
            value: (((pt = this._aggregatedStats.avgProcessTime) == null ? void 0 : pt.toFixed(1)) || 0) + "/" + this._aggregatedStats.processMissPs
        }),
        o.push({
            key: "--rotateShow",
            value: (((dt = this._aggregatedStats.avgDisplayTime) == null ? void 0 : dt.toFixed(1)) || 0) + "/" + this._aggregatedStats.displayMissPs
        }),
        ((_t = this.room._userAvatar) == null ? void 0 : _t.state) == "moving",
        o.push({
            key: ":----------------Move----------------------",
            value: ""
        }),
        o.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)
        }),
        (((mt = this.room._userAvatar) == null ? void 0 : mt.state) == "moving" || this._aggregatedStats.moveEvent == "GetOnAirship" || this._aggregatedStats.moveEvent == "GetOnVehicle") && o.push({
            key: "-srvInterFrm(max/avg)",
            value: (this._aggregatedStats.maxServerDiff || 0) + "/" + (this._aggregatedStats.avgServerDiff.toFixed(1) || 0)
        }),
        o.push({
            key: "-interFrameDelay",
            value: "(max/avg/jank)"
        }),
        o.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" ? ((vt = this._aggregatedStats.moveDisplayJank) == null ? void 0 : vt.toFixed(3)) || 0 : ((yt = this._aggregatedStats.flyDisplayJank) == null ? void 0 : yt.toFixed(3)) || 0)
        }),
        o.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" ? ((Et = this._aggregatedStats.moveResponseJank) == null ? void 0 : Et.toFixed(3)) || 0 : ((At = this._aggregatedStats.flyResponseJank) == null ? void 0 : At.toFixed(3)) || 0)
        }),
        o.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" ? ((gt = this._aggregatedStats.moveProcessJank) == null ? void 0 : gt.toFixed(3)) || 0 : ((St = this._aggregatedStats.flyProcessJank) == null ? void 0 : St.toFixed(3)) || 0)
        }),
        o.push({
            key: ":----------------DevInfo-----------------",
            value: ""
        }),
        o.push({
            key: "sd",
            value: (this._aggregatedStats.sdMoveResponseLongTime.toFixed(1) || 0) + "/" + (this._aggregatedStats.sdMoveProcessLongTime.toFixed(1) || 0) + "/" + (this._aggregatedStats.sdMoveDisplayLongTime.toFixed(1) || 0)
        }),
        o.push({
            key: "----hardwareInfo",
            value: this._extraStats.hardwareInfo
        }),
        i === "default")
            this.createAndRender(o, i);
        else {
            const Ot = [];
            Ot.push({
                key: "rtt: " + this._extraStats.rtt + " hb: " + this._extraStats.hb,
                value: ""
            }),
            Ot.push({
                key: ":----------------PerFrame-------------",
                value: ""
            }),
            Ot.push({
                key: "render(max/avg)",
                value: (((xt = this._extraStats.maxRenderFrameTime) == null ? void 0 : xt.toFixed(1)) || 0) + "/" + (((bt = this._extraStats.renderFrameTime) == null ? void 0 : bt.toFixed(2)) || 0)
            }),
            Ot.push({
                key: "update(max/avg)",
                value: (this._aggregatedStats.maxGraphicTime.toFixed(1) || 0) + "/" + (((Rt = this._aggregatedStats.averageGraphicTime) == null ? void 0 : Rt.toFixed(2)) || 0)
            }),
            Ot.push({
                key: "receive(max/avg)",
                value: this._aggregatedStats.decodeCPUMax + "/" + ((Mt = this._aggregatedStats.decodeCPUAvg) == null ? void 0 : Mt.toFixed(2))
            }),
            Ot.push({
                key: "handleSignal(max/avg)",
                value: this._aggregatedStats.sdkCPUMax + "/" + ((Pt = this._aggregatedStats.sdkCPUAvg) == null ? void 0 : Pt.toFixed(2))
            }),
            Ot.push({
                key: ":----------------LowFrequent-------------",
                value: ""
            }),
            Ot.push({
                key: "engine(max/sum)",
                value: this._aggregatedStats.engineCPUMax + "/" + this._aggregatedStats.engineCPUSum
            }),
            Ot.push({
                key: "blob(max/sum)",
                value: this._aggregatedStats.sdkBlobMax + "/" + this._aggregatedStats.sdkBlobSum
            }),
            ((It = this.room._userAvatar) == null ? void 0 : It.state) == "moving",
            Ot.push({
                key: ":----------------Move----------------------",
                value: ""
            }),
            (((Dt = this.room._userAvatar) == null ? void 0 : Dt.state) == "moving" || this._aggregatedStats.moveEvent == "GetOnAirship" || this._aggregatedStats.moveEvent == "GetOnVehicle") && Ot.push({
                key: "-srvInterFrm(max/avg)",
                value: (this._aggregatedStats.maxServerDiff || 0) + "/" + (this._aggregatedStats.avgServerDiff.toFixed(1) || 0)
            }),
            Ot.push({
                key: "-interFrameDelay",
                value: "(max/avg)"
            }),
            Ot.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)
            }),
            Ot.push({
                key: "postMsg",
                value: this._aggregatedStats.postMsgMaxTime || 0
            }),
            Ot.push({
                key: "timeoutGap",
                value: ((Ct = this._extraStats.maxTimeoutGap) == null ? void 0 : Ct.toFixed(1)) || 0
            }),
            Ot.push({
                key: ":----------------DevInfo-------------",
                value: ""
            }),
            Ot.push({
                key: "handleSignalPartial",
                value: this._aggregatedStats.sdkSignalPartial || ""
            }),
            Ot.push({
                key: "heavyFunc",
                value: this._aggregatedStats.heavyFunc || ""
            }),
            this.createAndRender(Ot, i)
        }
    }
    createAndRender(i, o="default") {
        if (!this._displayElements[o]) {
            const c = document.createElement("div");
            this._displayElements[o] = c,
            c.style.position = "absolute",
            c.style.top = "10px",
            c.style.left = "120px",
            c.style.width = "200px",
            c.style.backgroundColor = "rgba(0,0,0,.5)",
            c.style.color = "white",
            c.style.textAlign = "left",
            c.style.fontSize = "8px",
            c.style.lineHeight = "10px",
            document.body.appendChild(c)
        }
        let s = "";
        for (const c of i)
            s += `<div><span>${c.key}</span>: <span>${c.value}</span> </div>`;
        this._displayElements[o].innerHTML = s
    }
    onStats(i) {
        var _;
        if (!i)
            return;
        const o = {}
          , s = this;
        s._aggregatedStats || (s._aggregatedStats = {}),
        o.timestamp = i.timestamp,
        o.mediaBytesReceived = i.mediaBytesReceived,
        o.metaBytesReceived = i.metaBytesReceived,
        o.packetsLost = i.packetsLost,
        o.frameHeight = i.frameHeight,
        o.frameWidth = i.frameWidth,
        o.framesReceivedUI = i.framesReceived,
        o.framesReceived = i.framesReceivedWorker,
        o.framesDecoded = i.framesDecoded,
        o.framesEmited = i.framesEmited,
        o.decodeTimePerFrame = i.decodeTimePerFrame,
        o.decodeTimeMaxFrame = i.decodeTimeMaxFrame,
        o.packetsDrop = i.packetsDrop,
        o.framesAwait = i.framesAwait,
        o.updateDropFrame = i.updateDropFrame,
        o.firstMediaArraval = i.firstMediaArraval,
        o.firstYUVDecoded = i.firstYUVDecoded,
        o.firstRender = i.firstRender,
        o.returnFrames = i.returnFrames,
        o.sendOutBuffer = i.sendOutBuffer,
        o.averageGraphicTime = i.averageGraphicTime,
        o.maxGraphicTime = i.maxGraphicTime,
        o.jankTimes = i.jankTimes,
        o.bigJankTimes = i.bigJankTimes,
        o.decodeJankTimes = i.decodeJankTimes,
        o.bigDecodeJankTimes = i.bigDecodeJankTimes,
        o.serverFrameFast = i.serverFrameFast,
        o.serverFrameSlow = i.serverFrameSlow,
        o.clientFrameFast = i.clientFrameFast,
        o.clientFrameSlow = i.clientFrameSlow,
        o.rtcMessageReceived = i.rtcMessageReceived,
        o.rtcBytesReceived = i.rtcBytesReceived,
        o.receiveIframes = i.receiveIframes,
        o.decodeIframes = i.decodeIframes,
        o.avgResponseTime = i.avgResponseTime,
        o.avgProcessTime = i.avgProcessTime,
        o.avgDisplayTime = i.avgDisplayTime,
        o.avgOverallTime = i.avgOverallTime,
        o.overallTimeCount = i.overallTimeCount,
        o.responseMiss = i.responseMiss,
        o.processMiss = i.processMiss,
        o.displayMiss = i.displayMiss,
        o.avgResponseMoveDiff = i.avgResponseMoveDiff,
        o.avgProcessMoveDiff = i.avgProcessMoveDiff,
        o.avgDisplayMoveDiff = i.avgDisplayMoveDiff,
        o.maxResponseMoveDiff = i.maxResponseMoveDiff,
        o.maxProcessMoveDiff = i.maxProcessMoveDiff,
        o.maxDisplayMoveDiff = i.maxDisplayMoveDiff,
        o.moveResponseDelay = i.moveResponseDelay,
        o.moveProcessDelay = i.moveProcessDelay,
        o.moveDisplayDelay = i.moveDisplayDelay,
        o.moveResponseJank = i.moveResponseJank,
        o.moveProcessJank = i.moveProcessJank,
        o.moveDisplayJank = i.moveDisplayJank,
        o.avgMetaParseTime = i.avgMetaParseTime,
        o.maxMetaParseTime = i.maxMetaParseTime,
        o.moveResponseCounts = i.moveResponseCounts,
        o.moveProcessCounts = i.moveProcessCounts,
        o.moveDisplayCounts = i.moveDisplayCounts,
        o.MoveDisplayCountGood = i.MoveDisplayCountGood,
        o.MoveDisplayCountWell = i.MoveDisplayCountWell,
        o.MoveDisplayCountFair = i.MoveDisplayCountFair,
        o.MoveDisplayCountBad = i.MoveDisplayCountBad,
        o.MoveDisplayCountRest = i.MoveDisplayCountRest,
        o.avgServerDiff = i.avgServerDiff,
        o.maxServerDiff = i.maxServerDiff,
        o.avgResponseFlyDiff = i.avgResponseFlyDiff,
        o.avgProcessFlyDiff = i.avgProcessFlyDiff,
        o.avgDisplayFlyDiff = i.avgDisplayFlyDiff,
        o.maxResponseFlyDiff = i.maxResponseFlyDiff,
        o.maxProcessFlyDiff = i.maxProcessFlyDiff,
        o.maxDisplayFlyDiff = i.maxDisplayFlyDiff,
        o.flyResponseCounts = i.flyResponseCounts,
        o.flyProcessCounts = i.flyProcessCounts,
        o.flyDisplayCounts = i.flyDisplayCounts,
        o.flyResponseJank = i.flyResponseJank,
        o.flyProcessJank = i.flyProcessJank,
        o.flyDisplayJank = i.flyDisplayJank,
        o.flyResponseDelay = i.flyResponseDelay,
        o.flyProcessDelay = i.flyProcessDelay,
        o.flyDisplayDelay = i.flyDisplayDelay,
        o.moveEvent = i.moveEvent,
        o.sdMoveResponseLongTime = i.sdMoveResponseLongTime,
        o.sdMoveProcessLongTime = i.sdMoveProcessLongTime,
        o.sdMoveDisplayLongTime = i.sdMoveDisplayLongTime,
        o.avgJoyStickResponseTime = i.avgJoyStickResponseTime,
        o.avgJoyStickProcessTime = i.avgJoyStickProcessTime,
        o.avgJoyStickDisplayTime = i.avgJoyStickDisplayTime,
        o.avgJoyStickOverallTime = i.avgJoyStickOverallTime,
        o.maxJoyStickResponseTime = i.maxJoyStickResponseTime,
        o.maxJoyStickProcessTime = i.maxJoyStickProcessTime,
        o.maxJoyStickDisplayTime = i.maxJoyStickDisplayTime,
        o.maxJoyStickOverallTime = i.maxJoyStickOverallTime;
        const c = i.unmarshalStreamStat
          , d = i.receiveYUVStat;
        o.decodeCPUMax = Math.max(c.max, d.max),
        o.decodeCPUAvg = c.avg + d.avg,
        o.postMsgMaxTime = i.maxPostMsgDiff,
        s._aggregatedStats && s._aggregatedStats.timestamp && (o.mediaBitrate = 8 * (o.mediaBytesReceived - s._aggregatedStats.mediaBytesReceived) / 1e3,
        o.mediaBitrate = Math.round(o.mediaBitrate || 0),
        o.metaBitrate = 8 * (o.metaBytesReceived - s._aggregatedStats.metaBytesReceived) / 1e3,
        o.metaBitrate = Math.round(o.metaBitrate || 0),
        o.rtcMessagePs = o.rtcMessageReceived - s._aggregatedStats.rtcMessageReceived,
        o.rtcBitrate = 8 * (o.rtcBytesReceived - s._aggregatedStats.rtcBytesReceived) / 1e3,
        o.rtcBitrate = Math.round(o.rtcBitrate || 0),
        o.framesEmitedPs = o.framesEmited - s._aggregatedStats.framesEmited,
        o.framesEmitedPs = Math.round(o.framesEmitedPs || 0),
        o.framesReceivedPs = o.framesReceived - s._aggregatedStats.framesReceived,
        o.framesReceivedPs = Math.round(o.framesReceivedPs || 0),
        o.framesDecodedPs = o.framesDecoded - s._aggregatedStats.framesDecoded,
        o.framesDecodedPs = Math.round(o.framesDecodedPs || 0),
        o.returnFramesPs = o.returnFrames - s._aggregatedStats.returnFrames,
        o.returnFramesPs = Math.round(o.returnFramesPs || 0),
        o.responseMissPs = o.responseMiss - s._aggregatedStats.responseMiss,
        o.processMissPs = o.processMiss - s._aggregatedStats.processMiss,
        o.displayMissPs = o.displayMiss - s._aggregatedStats.displayMiss,
        o.returnFrames = i.returnFrames),
        this.showStatus.default ? this._render("default") : this.showStatus.extra && this._render("extra"),
        o.registerBeforeRenderTime = this._extraStats.registerBeforeRenderTime,
        o.registerAfterRenderTime = this._extraStats.registerAfterRenderTime,
        o.renderTargetRenderTime = this._extraStats.renderTargetRenderTime,
        o.renderFrameTime = this._extraStats.renderFrameTime,
        o.maxRenderFrameTime = this._extraStats.maxRenderFrameTime,
        o.interFrameTime = this._extraStats.interFrameTime,
        o.animationTime = this._extraStats.animationTime,
        o.meshSelectTime = this._extraStats.meshSelectTime,
        o.drawcall = this._extraStats.drawcall,
        o.drawcallTime = this._extraStats.drawcallTime,
        o.triangle = this._extraStats.triangle,
        o.registerAfterCount = this._extraStats.registerAfterCount,
        o.registerBeforeCount = this._extraStats.registerBeforeCount,
        o.fps = this._extraStats.fps,
        o.rtt = this._extraStats.rtt,
        o.hb = this._extraStats.hb,
        o.avgFrameTime = this._extraStats.avgFrameTime,
        o.avgTimeoutTime = this._extraStats.avgTimeoutTime,
        o.engineSloppyCnt = this._extraStats.engineSloppyCnt,
        o.systemStuckCnt = this._extraStats.systemStuckCnt,
        o.avatarState = (_ = this.room._userAvatar) == null ? void 0 : _.state,
        o.maxFrameTime = this._extraStats.maxFrameTime,
        o.maxTimeoutTime = this._extraStats.maxTimeoutTime,
        o.activeParticles = this._extraStats.activeParticles,
        o.activeBones = this._extraStats.activeBones,
        o.activeAnimation = this._extraStats.activeAnimation,
        o.totalRootNodes = this._extraStats.totalRootNodes,
        o.totalGeometries = this._extraStats.totalGeometries,
        o.totalMeshes = this._extraStats.totalMeshes,
        o.totalTextures = this._extraStats.totalTextures,
        o.totalMaterials = this._extraStats.totalMaterials,
        o.hardwareInfo = this._extraStats.hardwareInfo,
        o.maxInterFrameTime = this._extraStats.maxInterFrameTime,
        o.maxDrawcallTime = this._extraStats.maxDrawcallTime,
        o.maxMeshSelectTime = this._extraStats.maxMeshSelectTime,
        o.maxAnimationTime = this._extraStats.maxAnimationTime,
        o.maxRegisterBeforeRenderTime = this._extraStats.maxRegisterBeforeRenderTime,
        o.maxRegisterAfterRenderTime = this._extraStats.maxRegisterAfterRenderTime,
        o.maxRenderTargetRenderTime = this._extraStats.maxRenderTargetRenderTime,
        this.externalStats && Object.keys(this.externalStats || {}).forEach(b=>{
            o[b] = this.externalStats[b]
        }
        ),
        s._aggregatedStats = o,
        this.emit("stats", {
            stats: o
        })
    }
}
const isWebAssemblySupported = ()=>{
    try {
        if (typeof WebAssembly == "object" && typeof WebAssembly.instantiate == "function") {
            const a = new WebAssembly.Module(Uint8Array.of(0, 97, 115, 109, 1, 0, 0, 0));
            if (a instanceof WebAssembly.Module)
                return new WebAssembly.Instance(a)instanceof WebAssembly.Instance
        }
    } catch {}
    return console.log("wasm is not supported"),
    !1
}
;
function isSupported() {
    return typeof RTCPeerConnection == "function" && isWebAssemblySupported()
}
const log$f = new Logger("xverse")
  , er = class {
    constructor(e) {
        Tt(this, "debug", !1);
        Tt(this, "pageSession");
        Tt(this, "preload");
        Tt(this, "appId");
        Tt(this, "releaseId");
        e || (e = {});
        const {onLog: i, env: o, appId: s, releaseId: c, subPackageVersion: d} = e;
        er.NO_CACHE = !1,
        er.env = o || "PROD",
        er.SUB_PACKAGE_VERSION = d,
        this.debug && Logger.setLevel(LoggerLevels.Debug);
        const _ = this.pageSession = uuid$1();
        if (reporter.updateHeader({
            pageSession: _
        }),
        reporter.updateReportUrl(REPORT_URL[er.env]),
        d && reporter.updateBody({
            sdkVersion: d,
            appId: s
        }),
        log$f.infoAndReportMeasurement({
            metric: "sdkInit",
            startTime: Date.now(),
            extra: {
                version: d,
                enviroment: o,
                pageSession: _,
                engineVersion: VERSION$1
            }
        }),
        log$f.debug("debug mode:", this.debug),
        reporter.on("report", b=>{
            i && i(b)
        }
        ),
        s) {
            this.appId = s,
            this.releaseId = c;
            const b = ModelManager.getInstance(s, c);
            this.preload = new Preload(b)
        }
    }
    get isSupported() {
        return isSupported()
    }
    disableLogUpload() {
        reporter.disable(),
        log$f.debug("log upload has been disabled")
    }
    async getSkinList() {
        return []
    }
    async getAvatarList() {
        return []
    }
    async getGiftList() {
        return [{
            id: "hack "
        }]
    }
}
;
let Xverse$1 = er;
Tt(Xverse$1, "NO_CACHE"),
Tt(Xverse$1, "USE_TME_CDN"),
Tt(Xverse$1, "env"),
Tt(Xverse$1, "SUB_PACKAGE_VERSION");
const objectParseFloat = a=>{
    const e = {};
    return a && Object.keys(a).forEach(i=>{
        e[i] = parseFloat(a[i])
    }
    ),
    e
}
  , log$e = new Logger("model-manager")
  , tr = class {
    constructor(e, i) {
        Tt(this, "avatarModelList", []);
        Tt(this, "skinList", []);
        Tt(this, "applicationConfig");
        Tt(this, "config");
        Tt(this, "appId");
        Tt(this, "releaseId");
        this.appId = e,
        this.releaseId = i
    }
    static getInstance(e, i) {
        return tr.instance || (tr.instance = new tr(e,i)),
        tr.instance
    }
    static findModels(e, i, o) {
        return e.filter(c=>c.typeName === i && c.className === o)
    }
    static findModel(e, i, o) {
        const s = e.filter(c=>c.typeName === i && c.className === o)[0];
        return s || null
    }
    async findSkinConfig(e) {
        let i = null;
        if (i = (this.skinList = await this.getSkinsList()).find(s=>s.id === e),
        i)
            return i;
        {
            const s = `skin is invalid: skinId: ${e}`;
            return Promise.reject(new ParamError(s))
        }
    }
    async findRoute(e, i) {
        const s = (await this.findSkinConfig(e)).routeList.find(c=>c.pathName === i);
        if (!s) {
            const c = `find path failed: skinId: ${e}, pathName: ${i}`;
            return Promise.reject(new ParamError(c))
        }
        return log$e.debug("find route success", s),
        s
    }
    async findAssetList(e) {
        const o = (await this.findSkinConfig(e)).assetList;
        if (!o) {
            const s = `find path failed: skinId: ${e}`;
            return Promise.reject(new ParamError(s))
        }
        return log$e.debug("find route success", o),
        o
    }
    async findAsset(e, i, o="id") {
        const s = await this.findSkinConfig(e);
        if (Array.isArray(i))
            return i.map(d=>s.models.find(_=>_[o] === d)).filter(Boolean);
        const c = s.models.find(d=>d[o] === i);
        if (!c) {
            const d = `find asset failed: skinId: ${e}, keyValue: ${i}`;
            return Promise.reject(new ParamError(d))
        }
        return log$e.debug("find asset success", c),
        c
    }
    async findPoint(e, i) {
        const s = (await this.findSkinConfig(e)).pointList.find(c=>c.id === i);
        if (!s) {
            const c = `find point failed: skinId: ${e}, id: ${i}`;
            return Promise.reject(new ParamError(c))
        }
        return log$e.debug("find point success", s),
        s
    }
    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 i = Xverse$1.USE_TME_CDN ? "https://static.xverse.cn/tmeland/config/tme_config.json" : e;
        try {
            const o = await http$1.get({
                url: `${i}?t=${Date.now()}`,
                key: "config",
                timeout: 6e3,
                retry: 2
            })
              , {config: s, preload: c} = o.data.data || {};
            if (!s)
                throw new Error("config data parse error" + o.data);
            return this.config = {
                config: s,
                preload: c
            },
            log$e.debug("get config success", this.config),
            this.config
        } catch (o) {
            return Promise.reject(o)
        }
    }
    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(i=>({
                name: i.name,
                id: i.id,
                modelUrl: i.url,
                gender: i.gender,
                components: i.components
            })),
            this.avatarModelList
        } catch (e) {
            return log$e.error(e),
            Promise.reject(new InitConfigTimeoutError(e || "getAvatarModelList error"))
        }
    }
    async getSkinsList() {
        if (this.skinList.length)
            return this.skinList;
        try {
            const {skins: e} = await this.getApplicationConfig();
            return this.skinList = e.map(i=>{
                var o;
                return {
                    name: i.name,
                    dataVersion: i.id + i.versionId,
                    id: i.id,
                    fov: parseInt(i.fov || 90),
                    models: i.assetList.map(s=>{
                        const {assetId: c, url: d, thumbnailUrl: _, typeName: b, className: k} = s;
                        return {
                            id: c,
                            modelUrl: d,
                            name: s.name,
                            thumbnailUrl: _,
                            typeName: b,
                            className: k === "\u4F4E\u6A21" ? "\u7C97\u6A21" : k
                        }
                    }
                    ),
                    routeList: (o = i.routeList) == null ? void 0 : o.map(s=>{
                        const {areaName: c, attitude: d, id: _, pathName: b, step: k, birthPointList: j} = s;
                        return {
                            areaName: c,
                            attitude: d,
                            id: _,
                            pathName: b,
                            step: k,
                            birthPointList: j.map($=>({
                                camera: $.camera && {
                                    position: objectParseFloat($.camera.position),
                                    angle: objectParseFloat($.camera.rotation)
                                },
                                player: $.player && {
                                    position: objectParseFloat($.player.position),
                                    angle: objectParseFloat($.player.rotation)
                                }
                            }))
                        }
                    }
                    ),
                    pointList: i.pointList.map(s=>Zt($t({}, s), {
                        position: objectParseFloat(s.position),
                        rotation: objectParseFloat(s.rotation)
                    })),
                    versionId: i.versionId,
                    isEnable: i.isEnable,
                    assetList: i.assetList,
                    visibleRules: i.visibleRules,
                    animationList: i.animationList,
                    resolution: i.resolution
                }
            }
            ),
            this.skinList
        } catch (e) {
            return log$e.error(e),
            Promise.reject(new InitConfigTimeoutError(e || "getSkinsList error"))
        }
    }
    async getBreathPointTextrueList() {
        return [{
            url: TEXTURE_URL
        }]
    }
    async findEffectList(e) {
        const o = (await this.findSkinConfig(e)).assetList.filter(s=>s.typeName === "EFFECTS");
        if (!o) {
            const s = `find effect failed: skinId: ${e}`;
            return Promise.reject(new ParamError(s))
        }
        return log$e.debug("find asset success", o),
        o
    }
}
;
let ModelManager = tr;
Tt(ModelManager, "instance");
var AssetTypeName = (a=>(a.Config = "CONFIG",
a.Model = "MODEL",
a.Vedio = "VEDIO",
a.Media = "MEDIA",
a.Effects = "EFFECTS",
a.Gift = "GIFT",
a.Textures = "TEXTURES",
a))(AssetTypeName || {})
  , AssetClassName = (a=>(a.Effects = "\u7279\u6548",
a.Tv = "TV",
a.Lpm = "\u7C97\u6A21",
a.Reward = "\u571F\u8C6A\u699C",
a.Env = "\u73AF\u5883\u5149",
a.Gbq = "\u544A\u767D\u5899",
a.BreathPoint = "\u547C\u5438\u70B9",
a.Gifts = "\u9001\u793C",
a.Panorama = "\u5168\u666F\u56FE",
a.GiftBubble = "\u9001\u793C\u6C14\u6CE1",
a.SayBubble = "\u804A\u5929\u6C14\u6CE1",
a))(AssetClassName || {});
function mapLimit(a, e, i) {
    return new Promise((o,s)=>{
        const c = a.length;
        let d = e - 1
          , _ = 0;
        const b = k=>{
            k.forEach(j=>{
                i(j).then(()=>{
                    if (_++,
                    _ === c) {
                        o();
                        return
                    }
                    d++;
                    const $ = a[d];
                    $ && b([$])
                }
                , $=>{
                    s($)
                }
                )
            }
            )
        }
        ;
        b(a.slice(0, e))
    }
    )
}
const log$d = new Logger("preload");
class Preload {
    constructor(e) {
        Tt(this, "config");
        Tt(this, "allKeys", []);
        Tt(this, "oldResourcesDeleted", !1);
        Tt(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: i} = await this.modelManager.requestConfig();
        return i ? (this.config = i,
        Promise.resolve(i)) : Promise.reject("no preload config")
    }
    async getAllKeys() {
        if (this.allKeys.length)
            return this.allKeys;
        try {
            const e = await modelTable.getAllKeys()._timeout(3e3, new TimeoutError("db getAllKeys timeout"));
            return this.allKeys = e,
            e
        } catch {
            const i = "preload getAllKeys error";
            return log$d.error(i),
            Promise.reject(i)
        }
    }
    stop(e) {
        e === "serverless" && (e = "observer"),
        this.requests[e].stopped = !0;
        const i = this.requests[e].requests;
        Object.keys(i).forEach(o=>{
            http$1.canceler.removePending(o),
            delete i[o]
        }
        )
    }
    clearPreload(e) {
        this.requests[e].stopped = !1,
        this.allKeys = []
    }
    async start(e, i, o) {
        let s = Date.now()
          , c = 0;
        try {
            if (e === "serverless" && (e = "observer"),
            !this.requests[e])
                return Promise.reject(new ParamError("invalid stage name: " + e));
            this.clearPreload(e);
            const d = await this.getConfig(e);
            let _ = [];
            const b = d.assetUrls.map(et=>et.url);
            try {
                _ = await this.getAllKeys(),
                await this.deleteOldResources(b, _)
            } catch {
                log$d.error("getAllKeys error, deleting db"),
                await modelTable.clearDataBase()
            }
            const {baseUrls: k, assetUrls: j} = d;
            let$;
            switch (e) {
            case "simple":
                $ = k;
                break;
            case "observer":
                $ = j;
                break;
            case "full":
                $ = j;
                break;
            default:
                $ = j
            }
            let _e = $.filter(et=>!_.includes(et.url));
            o && isFunction(o) && (_e = _e.filter(o)),
            c = _e.length,
            log$d.debug("keysNeedToPreload", _e),
            log$d.warn("preloadStart", _e.length),
            _e.length || i && i($.length, $.length),
            s = Date.now(),
            await this._preload(e, _e, i),
            log$d.infoAndReportMeasurement({
                tag: e,
                startTime: s,
                metric: "assetsPreload",
                extra: {
                    total: c
                }
            });
            return
        } catch (d) {
            let _ = d;
            return (this.requests[e].stopped || axios.isCancel(d)) && (_ = new PreloadCanceledError),
            log$d.infoAndReportMeasurement({
                tag: e,
                startTime: s,
                metric: "assetsPreload",
                extra: {
                    total: c
                },
                error: _,
                reportOptions: {
                    immediate: !0
                }
            }),
            Promise.reject(_)
        }
    }
    async deleteOldResources(e, i) {
        if (!this.oldResourcesDeleted)
            this.oldResourcesDeleted = !0;
        else
            return Promise.resolve();
        const o = i.filter(c=>!e.includes(c));
        log$d.debug("keysNeedToDelete", o),
        log$d.warn("keysNeedToDelete", o.length);
        const s = Promise.all(o.map(c=>modelTable.delete(c)));
        try {
            await s
        } catch (c) {
            log$d.error("deleteOldResources error", c)
        }
    }
    async _preload(e, i, o) {
        const s = i.length;
        if (!s)
            return Promise.resolve();
        let c = 0;
        const d = window.setInterval(()=>{
            o && o(c, s),
            c >= s && window.clearInterval(d)
        }
        , 1e3);
        return mapLimit(i, 10, async _=>{
            const {size: b, url: k} = _;
            return this.requests[e].stopped ? Promise.reject(new PreloadCanceledError) : AssetsStorage.requestAndPut({
                url: k,
                timeout: Preload.getTimeoutBySize(b),
                responseType: "blob",
                retry: 2,
                beforeRequest: ()=>{
                    this.requests[e].requests[k] = !0
                }
            }).then(()=>{
                c++,
                delete this.requests[e].requests[k]
            }
            , j=>(delete this.requests[e].requests[k],
            window.clearInterval(d),
            Promise.reject(j)))
        }
        )
    }
}
let sceneManager;
function getSceneManager(a, e) {
    return sceneManager || (sceneManager = new XSceneManager(a,e)),
    sceneManager
}
const log$c = new Logger("tv");
class TV extends XTelevision {
    constructor(i, o, s, c) {
        super(s.scene, o, s.sceneManager, c);
        Tt(this, "decal");
        Tt(this, "id");
        Tt(this, "imageUrl");
        Tt(this, "mode", "video");
        Tt(this, "room");
        Tt(this, "_isStoped", !1);
        Tt(this, "setVideo", (i,o=!1,s=!0)=>(log$c.warn("setVideo", {
            isLive: o,
            fixElement: s,
            src: i.src
        }),
        super.setVideo(i, o, s).then(()=>(this._isStoped = !1,
        log$c.warn("setVideo Success", {
            isLive: o,
            fixElement: s,
            src: i.src
        }),
        this))));
        this.id = i,
        this.room = s,
        this.decal = new XDecalManager(s.sceneManager)
    }
    get isStoped() {
        return this._isStoped
    }
    get objectFit() {
        return this.tvFitMode
    }
    set objectFit(i) {
        this.objectFit !== i && (this.tvFitMode = i,
        this.getVideoMat() && this.changeTvFitMode())
    }
    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 i = this.imageUrl;
        if (!i)
            return Promise.reject("set poster url before show it");
        if (!this.decal)
            return Promise.reject("decal was not found");
        const o = this.id;
        return this.decal.addDecal({
            id: o,
            meshPath: this.meshPath
        }).then(()=>{
            var s;
            this.mode = "poster",
            (s = this.decal) == null || s.setDecalTexture({
                id: o,
                buffer: i
            }).then(()=>{
                var c;
                (c = this.decal) == null || c.toggle(o, !0)
            }
            )
        }
        )
    }
    setPoster(i) {
        return this.imageUrl = i,
        this.showPoster()
    }
    hidePoster() {
        return this.decal ? this.decal.toggle(this.id, !1) : Promise.reject("decal was not found")
    }
    async setUrl(i) {
        const o = Date.now()
          , {url: s, loop: c=!1, muted: d} = i || {};
        if (log$c.warn("setUrl", {
            url: s,
            loop: c,
            muted: d
        }),
        !s)
            return log$c.error("tv url is required"),
            Promise.reject("tv url is required");
        await super.setUrl({
            url: s,
            bLoop: c,
            bMuted: d
        });
        const _ = this.videoElement;
        if (!_)
            return Promise.reject(new InternalError("video element is not found"));
        _.crossOrigin = "anonymous",
        _.playsInline = !0,
        _.load(),
        this.mode = "video",
        this._isStoped = !1;
        try {
            await new Promise(b=>{
                _.oncanplay = ()=>{
                    log$c.warn(`setUrl success, video oncanplay within ${(Date.now() - o) / 1e3}s`, {
                        url: s,
                        loop: c,
                        muted: d
                    }),
                    this.room.afterSetUrlHook(),
                    _.play(),
                    b(this)
                }
            }
            )._timeout(15e3, new InternalError("video oncanplay timeout in 15s"))
        } catch (b) {
            return log$c.error(b),
            Promise.reject(b)
        }
        return this
    }
    stop() {
        return log$c.warn("tv stop success"),
        this._isStoped = !0,
        this.room.afterTvStopedHook(),
        super.stop()
    }
    play() {
        return this._isStoped = !1,
        this.room.afterTvPlayedHook(),
        super.play().then(()=>{
            log$c.warn("tv play success"),
            !this.videoElement && log$c.error("tv play fake success, videoElement is not found")
        }
        ).catch(i=>(log$c.error("tv play error", i),
        Promise.reject(i)))
    }
    mirrorFrom(i) {
        const o = i.getVideoMat();
        return this.setSameVideo(o).then(()=>{
            this.toggle(!0)
        }
        )
    }
    clean() {
        var i;
        this.cleanTv(!1, !0),
        (i = this.decal) == null || i.deleteDecal(this.id)
    }
}
const log$b = new Logger("xverse-bus")
  , ir = class {
    constructor(e) {
        Tt(this, "_tvs", []);
        Tt(this, "isRenderFirstFrame", !1);
        Tt(this, "_idleTime", 0);
        Tt(this, "renderTimer");
        Tt(this, "lightManager");
        Tt(this, "_checkSceneNotReadyCount", 0);
        Tt(this, "_checkSceneDurationFrameNum", 0);
        Tt(this, "_checkSceneFrameCount", 0);
        Tt(this, "timeoutCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "frameCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "interFrameCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "drawCallCntCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "activeFacesCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "renderTimeCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "drawCallTimeCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "animationCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "meshSelectCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "renderTargetCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "regBeforeRenderCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "regAfterRenderCircularArray", new CircularArray(120,!1,[]));
        Tt(this, "renderCnt", 0);
        Tt(this, "renderErrorCount", 0);
        Tt(this, "engineSloppyCnt", 0);
        Tt(this, "systemStuckCnt", 0);
        Tt(this, "timeoutSecondArray", new SecondArray);
        Tt(this, "frameRenderNumber", 0);
        Tt(this, "_setFPS", (e,i=25)=>{
            log$b.info("Set fps to", i);
            const o = i > 60 ? 60 : i < 24 ? 24 : i;
            e.Engine.stopRenderLoop();
            const s = 1e3 / o;
            let c = Date.now()
              , d = Date.now()
              , _ = s
              , b = 1;
            const k = ()=>{
                var st;
                const j = Date.now()
                  , $ = j - c
                  , _e = j - d;
                d = j,
                this.frameCircularArray.add(_e),
                $ - _ > s && (this.systemStuckCnt += 1),
                this.timeoutSecondArray.add($ - _);
                const et = $ / _;
                b = .9 * b + .1 * et;
                const tt = Date.now();
                let rt = 0
                  , it = 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 > ir._CHECK_DURATION && (this._checkSceneDurationFrameNum = ir._CHECK_DURATION,
                        this._checkSceneFrameCount = 0,
                        this._checkSceneNotReadyCount++,
                        (this._checkSceneNotReadyCount == 1 || this._checkSceneNotReadyCount % 100 == 0) && log$b.error(`[SDK] Scene not ready, skip render. loop: ${this._checkSceneNotReadyCount}`),
                        this._checkSceneNotReadyCount > 10 && (log$b.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$b.infoAndReportMeasurement({
                            value: 0,
                            startTime: Date.now(),
                            metric: "renderError",
                            error: new Error("[SDK] Scene not ready, skip render and reload."),
                            reportOptions: {
                                sampleRate: .1
                            }
                        }));
                    else
                        try {
                            this.room.allowRender && e.render()
                        } catch (ut) {
                            this.renderErrorCount++,
                            this.renderErrorCount > 10 && this.room.proxyEvents("renderError", {
                                error: ut
                            }),
                            this.room.stats.assign({
                                renderErrorCount: this.renderErrorCount
                            }),
                            log$b.infoAndReportMeasurement({
                                value: 0,
                                startTime: Date.now(),
                                metric: "renderError",
                                error: ut,
                                reportOptions: {
                                    sampleRate: .1
                                }
                            })
                        }
                    rt = Date.now() - tt,
                    this.frameRenderNumber < 1e3 && this.frameRenderNumber++,
                    this.room.networkController.rtcp.workers.UpdateYUV(),
                    it = Date.now() - tt - rt
                }
                this.isRenderFirstFrame || this.room.networkController.rtcp.workers.UpdateYUV();
                const ot = Date.now() - tt;
                c = j + ot,
                _ = Math.min(Math.max((s - ot) / b, 5), 200),
                ot > s && (_ = 10,
                this.engineSloppyCnt += 1),
                this._idleTime = _;
                const at = _;
                if (_ > 150 && console.log("lastGap is ", _, ", ratio is ", b, ", usedTimeMs is ", ot, ", cpuRenderTime is ", rt, ", cpuUpdateYUVTime is ", it),
                this.timeoutCircularArray.add(at),
                this.renderCnt % 25 == 0) {
                    const ut = this.frameCircularArray.getAvg()
                      , ct = this.timeoutCircularArray.getAvg()
                      , lt = this.frameCircularArray.getMax()
                      , ft = this.timeoutCircularArray.getMax();
                    (st = this.room.stats) == null || st.assign({
                        avgFrameTime: ut,
                        avgTimeoutTime: ct,
                        maxFrameTime: lt,
                        maxTimeoutTime: ft,
                        systemStuckCnt: this.systemStuckCnt
                    })
                }
                this.renderTimer = window.setTimeout(k, _)
            }
            ;
            this.renderTimer = window.setTimeout(k, s / b)
        }
        );
        Tt(this, "updateStats", ()=>{
            var i;
            const e = this.timeoutSecondArray.getStat();
            (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(),
                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(),
                maxTimeoutGap: e.max
            })
        }
        );
        this.room = e
    }
    async initEngine(e) {
        var d, _;
        await this.updateBillboard(),
        log$b.info("engine version:", VERSION$1);
        const i = new Logger("engine");
        i.setLevel(LoggerLevels.Warn);
        const o = {
            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: i,
            disableWebGL2: this.room.options.disableWebGL2 || !1
        }
          , s = (_ = (d = this.room) == null ? void 0 : d.skin) == null ? void 0 : _.resolution;
        s && (o.videoResOriArray.some(k=>k.width === s.width && k.height === s.height) || o.videoResOriArray.push(s));
        const c = this.room.sceneManager = getSceneManager(this.room.canvas, o);
        this.room.setPictureQualityLevel(this.room.options.pictureQualityLevel || "high"),
        this.room.sceneManager.staticmeshComponent.setRegionLodRule([2, 2, -1, -1, -1]),
        this.room.scene = c.Scene,
        this.room.breathPointManager = c.breathPointComponent,
        this.lightManager = c.lightComponent,
        this.registerStats(),
        await this.setEnv(e),
        await this.room.avatarManager.init(),
        await this._updateSkinAssets(e.id),
        this._setFPS(c)
    }
    pause() {
        clearTimeout(this.renderTimer),
        log$b.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$b.info("Invoke room.resume to render");
        const e = this._createAssetList(this.room.skin);
        await this.loadAssets(e, "")
    }
    async setEnv(e) {
        var o;
        this.lightManager || (this.lightManager = this.room.sceneManager.lightComponent),
        e = e || this.room.skin;
        const i = ModelManager.findModel(e.models, AssetTypeName.Config, AssetClassName.Env);
        return i ? (o = this.lightManager) == null ? void 0 : o.setIBL(i.modelUrl) : (log$b.error("env file not found"),
        Promise.resolve())
    }
    async _parseModelsAndLoad(e, i, o) {
        log$b.info("Invoke _parseModelsAndLoad start", i);
        const s = ["airship", "balloon", "default", "ground_feiting", "ground_reqiqiu"]
          , c = new Map;
        o == null && (o = "xxxx");
        let d = !0;
        for (let k = 0; k < e.length; ++k) {
            d = !0;
            for (let j = 0; j < s.length; ++j)
                if (e[k].modelUrl.toLowerCase().indexOf(s[j]) >= 0) {
                    const $ = c.get(s[j]);
                    $ ? ($.push(e[k]),
                    c.set(s[j], $)) : c.set(s[j], [e[k]]),
                    d = !1;
                    break
                }
            if (d) {
                const j = c.get("default");
                j ? (j.push(e[k]),
                c.set("default", j)) : c.set("default", [e[k]])
            }
        }
        let _ = c.get(i) || [];
        if (this.room.viewMode === "simple" && (_ = _.filter(k=>!k.modelUrl.endsWith("zip"))),
        !_)
            return Promise.reject(`no invalid scene model with group name: ${i}`);
        const b = [];
        for (let k = 0; k < _.length; ++k) {
            const j = _[k];
            if (j.modelUrl.toLowerCase().endsWith("zip"))
                j.modelUrl.toLowerCase().endsWith("zip") && b.push(this.room.sceneManager.addNewLowPolyMesh({
                    url: j.modelUrl,
                    skinInfo: o
                }));
            else {
                const $ = i;
                b.push(this.room.sceneManager.addNewLowPolyMesh({
                    url: j.modelUrl,
                    group: $,
                    pick: !0,
                    skinInfo: o
                }))
            }
        }
        return Promise.all(b)
    }
    async _deleteAssetsLowpolyModel(e) {
        this.room.sceneManager.staticmeshComponent.deleteMeshesBySkinInfo(e),
        this.room.sceneManager.breathPointComponent.clearBreathPointsBySkinInfo(e),
        this.room.sceneManager.decalComponent.deleteDecalBySkinInfo(e);
        const i = [];
        this.room.sceneManager.Scene.meshes.forEach(o=>{
            o.xskinInfo == e && i.push(o)
        }
        ),
        i.forEach(o=>{
            o.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, i="", o=8e3) {
        const s = Date.now();
        return this._loadAssets(e, i)._timeout(o, new InitEngineTimeoutError(`loadAssets timeout(${o}ms)`)).then(c=>(log$b.infoAndReportMeasurement({
            tag: "loadAssets",
            startTime: s,
            metric: "loadAssets"
        }),
        c)).catch(c=>(log$b.infoAndReportMeasurement({
            tag: "loadAssets",
            startTime: s,
            metric: "loadAssets",
            error: c
        }),
        Promise.reject(c)))
    }
    async _loadAssets(e, i="") {
        try {
            const o = [];
            o.push(this._loadAssetsLowpolyModel(e, i)),
            await Promise.all(o),
            this._checkSceneDurationFrameNum = ir._CHECK_DURATION,
            this._checkSceneNotReadyCount = 0,
            this._checkSceneFrameCount = 0,
            this.updateAnimationList()
        } catch (o) {
            return Promise.reject(o)
        }
    }
    updateAnimationList() {
        if (this.room.avatarManager && this.room.avatarManager.xAvatarManager) {
            const e = this.room.skin.animationList;
            if (!e)
                return;
            e.forEach(i=>{
                this.room.avatarManager.xAvatarManager.updateAnimationLists(i.animations, i.avatarId)
            }
            )
        }
    }
    async _loadAssetsLowpolyModel(e, i="") {
        const o = []
          , s = []
          , c = [];
        e.lowPolyModels.forEach($=>{
            $.group === "TV" ? s.push({
                id: "",
                name: "",
                thumbnailUrl: "",
                typeName: AssetTypeName.Model,
                className: AssetClassName.Tv,
                modelUrl: $.url
            }) : $.group === "\u544A\u767D\u5899" ? c.push({
                id: "",
                name: "",
                thumbnailUrl: "",
                typeName: AssetTypeName.Model,
                className: AssetClassName.Lpm,
                modelUrl: $.url
            }) : o.push({
                id: "",
                name: "",
                thumbnailUrl: "",
                typeName: AssetTypeName.Model,
                className: AssetClassName.Lpm,
                modelUrl: $.url
            })
        }
        ),
        i != "" && i != null && this._deleteAssetsLowpolyModel(i);
        const d = e.skinId;
        log$b.info("====> from ", i, "  to  ", d),
        this._tvs.forEach($=>$.clean()),
        this._tvs = [],
        Array.isArray(s) && s.forEach(($,_e)=>{
            this._tvs.push(new TV("squareTv" + _e,$.modelUrl,this.room,{
                fitMode: EFitMode.cover
            }))
        }
        ),
        e.breathPointsConfig.forEach(async$=>{
            let _e;
            try {
                _e = await urlTransformer($.imageUrl)
            } catch (et) {
                _e = $.imageUrl,
                log$b.error("urlTransformer error", et)
            }
            this.room.breathPointManager.addBreathPoint({
                id: $.id,
                position: $.position,
                spriteSheet: _e,
                rotation: $.rotation || {
                    pitch: 0,
                    yaw: 270,
                    roll: 0
                },
                billboardMode: !0,
                type: $.type || "no_type",
                spriteWidthNumber: $.spriteWidthNum || 1,
                spriteHeightNumber: $.spriteHeightNum || 1,
                maxVisibleRegion: $.maxVisibleRegion || 150,
                width: $.width,
                height: $.height,
                skinInfo: $.skinId
            })
        }
        ),
        c.forEach($=>{
            this.room.sceneManager.decalComponent.addDecal({
                id: $.id || "gbq",
                meshPath: $.modelUrl,
                skinInfo: d
            })
        }
        );
        const b = this.room.sceneManager.staticmeshComponent.lowModel_group
          , k = Array.from(b.keys()).filter($=>!$.startsWith("region_"))
          , j = ["airship", "balloon", "ground_feiting", "ground_reqiqiu", "default"];
        return new Promise(($,_e)=>{
            Promise.all(j.map(et=>this._parseModelsAndLoad(o, et, d))).then(()=>{
                let et = !1;
                o.forEach(it=>{
                    it.modelUrl.endsWith("zip") && (et = !0)
                }
                ),
                et == !1 && this.room.sceneManager.staticmeshComponent.deleteLastRegionMesh(),
                this.room.sceneManager.staticmeshComponent.lowModel_group;
                const tt = Array.from(b.keys()).filter(it=>!it.startsWith("region_"))
                  , rt = k.filter(it=>tt.indexOf(it) < 0);
                rt.length > 0 && rt.forEach(it=>{
                    this.room.sceneManager.staticmeshComponent.deleteMeshesByGroup(it)
                }
                ),
                $(!0)
            }
            ).catch(et=>{
                _e(et)
            }
            )
        }
        )
    }
    async _updateSkinAssets(e) {
        const i = this.room.currentState.skinId
          , o = await this.room.getSkin(e)
          , s = this._createAssetList(o);
        try {
            await this.loadAssets(s, i),
            this.room.updateCurrentState({
                versionId: o.versionId,
                skinId: o.id,
                skin: o
            })
        } catch {
            await this.loadAssets(s, i),
            this.room.updateCurrentState({
                versionId: o.versionId,
                skinId: o.id,
                skin: o
            })
        }
        const c = this.room.sceneManager.yuvInfo;
        this.room.sceneManager.changeCameraFovWithShaderUpdate(Zt($t({}, c), {
            fov: o.fov
        })),
        this.room.afterLoadAssetsHook(),
        await this.setEnv(o)
    }
    _createAssetList(e) {
        const i = []
          , o = []
          , s = [];
        let c = e.models;
        const d = this.room.modelManager.config.preload;
        return this.room.viewMode === "simple" ? d && (c = d.baseUrls.map(b=>(b.modelUrl = b.url,
        b))) : this.room.viewMode,
        ModelManager.findModels(c, AssetTypeName.Effects, AssetClassName.Effects).forEach(b=>{
            i.push({
                url: b.modelUrl,
                group: b.className,
                name: b.name
            })
        }
        ),
        ModelManager.findModels(c, AssetTypeName.Model, AssetClassName.Lpm).forEach(b=>{
            o.push({
                url: b.modelUrl,
                group: b.className
            })
        }
        ),
        ModelManager.findModels(c, AssetTypeName.Model, AssetClassName.Gbq).forEach(b=>{
            o.push({
                url: b.modelUrl,
                group: b.className
            })
        }
        ),
        ModelManager.findModels(c, AssetTypeName.Model, AssetClassName.Tv).forEach(b=>{
            o.push({
                url: b.modelUrl,
                group: b.className
            })
        }
        ),
        [].forEach(b=>{
            b.skinId == e.id && s.push(b)
        }
        ),
        {
            roomId: this.room.id,
            effects: i,
            lowPolyModels: o,
            breathPointsConfig: s,
            skinId: e.id
        }
    }
    registerStats() {
        const e = this.room.sceneManager;
        this.room.scene.registerAfterRender(()=>{
            var _t;
            const i = e.statisticComponent.getInterFrameTimeCounter()
              , o = e.statisticComponent.getDrawCall()
              , s = e.statisticComponent.getActiveFaces()
              , c = e.statisticComponent.getFrameTimeCounter()
              , d = e.statisticComponent.getDrawCallTime()
              , _ = e.statisticComponent.getAnimationTime()
              , b = e.statisticComponent.getActiveMeshEvaluationTime()
              , k = e.statisticComponent.getRenderTargetRenderTime()
              , j = e.statisticComponent.getRegisterBeforeRenderTime()
              , $ = e.statisticComponent.getRegisterAfterRenderTime()
              , _e = e.statisticComponent.getActiveParticles()
              , et = e.statisticComponent.getActiveBones()
              , tt = e.Scene._activeAnimatables.length
              , rt = e.statisticComponent.getTotalRootNodes()
              , it = e.Scene.geometries.length
              , nt = e.Scene.onBeforeRenderObservable.observers.length
              , ot = e.Scene.onAfterRenderObservable.observers.length
              , at = e.statisticComponent.getTotalMeshes()
              , st = e.statisticComponent.getTotalTextures()
              , ut = e.statisticComponent.getTotalMaterials()
              , ct = e.statisticComponent.getSystemInfo()
              , lt = ct.resolution
              , ft = ct.driver;
            ct.vender;
            const ht = ct.version
              , pt = ct.hardwareScalingLevel
              , dt = lt + "_" + ft + "_" + ht + "_" + pt;
            this.interFrameCircularArray.add(i),
            this.renderTimeCircularArray.add(c),
            this.animationCircularArray.add(_),
            this.meshSelectCircularArray.add(b),
            this.drawCallTimeCircularArray.add(d),
            this.regAfterRenderCircularArray.add($),
            this.regBeforeRenderCircularArray.add(j),
            this.renderTargetCircularArray.add(k),
            this.drawCallCntCircularArray.add(o),
            this.renderCnt += 1,
            this.renderCnt % 25 == 0 && ((_t = this.room.stats) == null || _t.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: s.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: _e,
                activeBones: et,
                activeAnimation: tt,
                totalMeshes: at,
                totalRootNodes: rt,
                totalGeometries: it,
                totalTextures: st,
                totalMaterials: ut,
                registerBeforeCount: nt,
                registerAfterCount: ot,
                hardwareInfo: dt
            }))
        }
        )
    }
    async updateBillboard() {
        const {options: {skinId: e}} = this.room
          , o = (await this.room.modelManager.findAssetList(e)).filter(d=>d.typeName === AssetTypeName.Textures && d.className === AssetClassName.SayBubble)
          , s = ["bubble01", "bubble02", "bubble03"]
          , c = ["bubble01_npc", "bubble02_npc", "bubble03_npc"];
        if (o.length) {
            const d = o.filter(b=>s.includes(b.name)).map(b=>b.url)
              , _ = o.filter(b=>c.includes(b.name)).map(b=>b.url);
            d.length && (XBillboardManager.userBubbleUrls = d),
            _.length && (XBillboardManager.npcBubbleUrls = _)
        }
    }
}
;
let EngineProxy = ir;
Tt(EngineProxy, "_CHECK_DURATION", 2);
var CameraStates = (a=>(a[a.Normal = 0] = "Normal",
a[a.ItemView = 1] = "ItemView",
a[a.CGView = 2] = "CGView",
a[a.PathView = 3] = "PathView",
a))(CameraStates || {})
  , Direction = (a=>(a.Left = "left",
a.Right = "right",
a))(Direction || {});
const calNormVector = (a,e)=>{
    let i = 0;
    for (let s = 0; s < 3; ++s)
        i = i + (e[s] - a[s]) * (e[s] - a[s]);
    return i = Math.sqrt(i),
    [(e[0] - a[0]) / i, (e[1] - a[1]) / i, (e[2] - a[2]) / i]
}
  , vectorCrossMulti = (a,e)=>{
    const i = a[0]
      , o = a[2]
      , s = e[0]
      , c = e[2];
    return i * c - o * s
}
  , log$a = new Logger("camera");
class Camera extends EventEmitter {
    constructor(i) {
        super();
        Tt(this, "initialFov", 0);
        Tt(this, "_state", CameraStates.Normal);
        Tt(this, "_person", Person.Third);
        Tt(this, "_room");
        Tt(this, "_cameraFollowing", !0);
        Tt(this, "checkPointOnLeftOrRight", i=>{
            const o = ue4Position2Xverse(i);
            if (!o || this.checkPointInView(i))
                return;
            const d = this._room.scene.activeCamera;
            if (!d)
                return;
            const _ = [d.target.x, d.target.y, d.target.z]
              , b = [d.position.x, d.position.y, d.position.z]
              , {x: k, y: j, z: $} = o
              , _e = calNormVector(b, _)
              , et = calNormVector(b, [k, j, $]);
            return vectorCrossMulti(_e, et) < 0 ? Direction.Right : Direction.Left
        }
        );
        Tt(this, "checkPointInView", ({x: i, y: o, z: s})=>{
            const c = ue4Position2Xverse({
                x: i,
                y: o,
                z: s
            });
            if (!c)
                return !1;
            for (let d = 0; d < 6; d++)
                if (this._room.scene.frustumPlanes[d].dotCoordinate(c) < 0)
                    return !1;
            return !0
        }
        );
        this._room = i
    }
    get person() {
        return this._person
    }
    get state() {
        return this._state
    }
    get pose() {
        return this._room.currentClickingState.camera
    }
    set cameraFollowing(i) {
        log$a.info("cameraFollowing setter", i),
        this.setCameraFollowing({
            isFollowHost: i
        })
    }
    get cameraFollowing() {
        return this._cameraFollowing
    }
    setCameraFollowing({isFollowHost: i}) {}
    handleRenderInfo(i) {
        const {cameraStateType: o} = i.renderInfo
          , s = this._room.sceneManager;
        if (o !== this._state && (this._state = o,
        log$a.debug("camera._state changed to", CameraStates[o]),
        o === CameraStates.CGView ? (s.cameraComponent.switchToCgCamera(),
        s.staticmeshComponent.getCgMesh().show()) : (s.cameraComponent.switchToMainCamera(),
        s.staticmeshComponent.getCgMesh().hide()),
        this.emit("stateChanged", {
            state: o
        })),
        this._room.isHost)
            return;
        const {isFollowHost: c} = i.playerState;
        !!c !== this._cameraFollowing && (this._cameraFollowing = !!c,
        this.emit("cameraFollowingChanged", {
            cameraFollowing: !!c
        }))
    }
    setCameraState({state: i}) {
        if (this._state === i) {
            log$a.warn(`You are already in ${CameraStates[i]} camera state`);
            return
        }
        i === CameraStates.Normal || this._state === CameraStates.ItemView && log$a.warn("CloseUp camera state can only be triggerd by room internally")
    }
    turnToFace({extra: i="", offset: o=0}) {
        const s = {
            action_type: Actions.TurnToFace,
            turn_to_face_action: {
                offset: o
            }
        };
        return this.emit("viewChanged", {
            extra: i
        }),
        this._room.actionsHandler.sendData({
            data: s
        })
    }
    isInDefaultView() {
        if (!this._room.isHost) {
            log$a.warn("It is recommended to call the function on the host side");
            return
        }
        if (!this._room._currentClickingState)
            return log$a.error("CurrentState should not be empty"),
            !1;
        const {camera: i, player: o} = this._room._currentClickingState;
        return Math.abs(o.angle.yaw - 180 - i.angle.yaw) % 360 <= 4
    }
    async screenShot({name: i, autoSave: o=!1}) {
        const s = this._room.scene.getEngine()
          , c = this._room.scene.activeCamera;
        try {
            this._room.sceneManager.setImageQuality(EImageQuality.high);
            const d = await CreateScreenshotAsync(s, c, {
                precision: 1
            });
            return this._room.sceneManager.setImageQuality(EImageQuality.low),
            o === !0 && downloadFileByBase64(d, i),
            Promise.resolve(d)
        } catch (d) {
            return this._room.sceneManager.setImageQuality(EImageQuality.low),
            Promise.reject(d)
        }
    }
    changeToFirstPerson(i, o, s) {
        const {camera: c, player: d, attitude: _, areaName: b, pathName: k} = i;
        return this._room.actionsHandler.requestPanorama({
            camera: c,
            player: d,
            attitude: _,
            areaName: b,
            pathName: k
        }, o, s).then(()=>{
            this._room.networkController.rtcp.workers.changePanoMode(!0);
            const {position: j, angle: $} = d || {};
            this._room.sceneManager.cameraComponent.changeToFirstPersonView({
                position: j,
                rotation: $
            })
        }
        )
    }
    setPerson(i, o={
        camera: this._room._currentClickingState.camera,
        player: this._room._currentClickingState.player
    }) {
        const s = Date.now();
        return this._setPerson(i, o).then(c=>(log$a.infoAndReportMeasurement({
            tag: Person[i],
            startTime: s,
            metric: "setPerson"
        }),
        c)).catch(c=>(log$a.infoAndReportMeasurement({
            tag: Person[i],
            startTime: s,
            metric: "setPerson",
            error: c
        }),
        Promise.reject(c)))
    }
    _setPerson(i, o={
        camera: this._room._currentClickingState.camera,
        player: this._room._currentClickingState.player
    }) {
        return i !== Person.First && i !== Person.Third ? Promise.reject("invalid person " + i) : !o.camera || !o.player ? Promise.reject(new ParamError("wrong camera or player")) : i === Person.First ? this._room.panorama.access({
            camera: o.camera,
            player: o.player,
            tag: "setPerson"
        }).then(()=>{
            var d, _;
            this._person = i,
            (d = this._room._userAvatar) == null || d.hide();
            const {position: s, angle: c} = ((_ = this._room.currentClickingState) == null ? void 0 : _.camera) || {};
            !s || !c || this._room.sceneManager.cameraComponent.changeToFirstPersonView({
                position: s,
                rotation: c
            })
        }
        ) : this._room.panorama.exit({
            camera: o.camera,
            player: o.player
        }).then(()=>{
            var s, c;
            this._person = i,
            (s = this._room._userAvatar) != null && s.xAvatar && ((c = this._room._userAvatar) == null || c.xAvatar.show())
        }
        )
    }
    setCameraPose(i) {
        this._room.sceneManager.cameraComponent.setCameraPose({
            position: i.position,
            rotation: i.angle
        })
    }
    async setMainCameraRotationLimit(i) {
        if (!this._room.panorama.actived)
            return Promise.reject(new Error("panorama not actived when setMainCameraRotationLimit"));
        const {limitAxis: o, limitRotation: s} = i;
        await this._room.sceneManager.cameraComponent.setMainCameraRotationLimit(o, s)
    }
    removeMainCameraRotationLimit() {
        this._room.sceneManager.cameraComponent.removeMainCameraRotationLimit()
    }
}
var IEffectType = (a=>(a.Sequence = "sequence",
a.SubSequence = "subSequence",
a))(IEffectType || {});
const log$9 = new Logger("effectManager");
class XverseEffect extends EventEmitter {
    constructor({id: i, jsonPath: o, type: s, room: c, scale: d=1}) {
        super();
        Tt(this, "_id");
        Tt(this, "type");
        Tt(this, "effect");
        Tt(this, "_room");
        Tt(this, "_isLoading", !0);
        Tt(this, "_failed", !1);
        Tt(this, "_scale", 1);
        this._room = c,
        this._id = i,
        this.type = s,
        this._scale = d,
        this.effect = i === "Rain" || i === "Boom" ? new XRain(this._room.scene,o,urlTransformer) : s === IEffectType.Sequence ? new XSequence(this._room.scene,o,"",urlTransformer) : new XSubSequence(this._room.scene,o,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 i;
        return !!((i = this.effect) != null && i.isPlaying)
    }
    async init() {
        try {
            await this.effect.init()._timeout(1e4, new TimeoutError("effect init timeout(10s)")),
            this._isLoading = !1,
            this._failed = !1
        } catch (i) {
            throw this._isLoading = !1,
            this._failed = !0,
            log$9.error(`effect: ${this.id} init error`, i),
            i
        }
    }
    play(i=!1) {
        return new Promise((o,s)=>{
            this.effect.play(i),
            o()
        }
        )
    }
    hide() {
        return this.effect.hide()
    }
    show() {
        return this.effect.show()
    }
    setRotation(i) {
        var o;
        return this.type === IEffectType.Sequence ? Promise.reject("setRotation failed, sequence unSuported") : (o = this.effect) == null ? void 0 : o.setRotation(i)
    }
    setPosition(i) {
        var o;
        return this.type === IEffectType.Sequence ? Promise.reject("setPosition failed, sequence unSuported") : (o = this.effect) == null ? void 0 : o.setPosition(i)
    }
    setScaling(i) {
        var o;
        return this.type === IEffectType.Sequence ? Promise.reject("setScaling failed, sequence unSuported") : (this._scale = i,
        (o = this.effect) == null ? void 0 : o.setScaling({
            x: i,
            y: -i,
            z: i
        }))
    }
    dispose() {
        this.effect.dispose()
    }
}
const log$8 = new Logger("xverse-effect-manager")
  , dr = class extends EventEmitter {
    constructor(i) {
        super();
        Tt(this, "effects", new Map);
        Tt(this, "room");
        this.room = i
    }
    async addEffect(i) {
        var d;
        const {jsonPath: o, id: s, type: c=IEffectType.SubSequence} = i;
        try {
            this.effects.get(s) && ((d = this.effects.get(s)) == null || d.dispose());
            const _ = new dr.subEffect({
                id: s,
                jsonPath: o,
                type: c,
                room: this.room
            });
            return this.effects.set(s, _),
            await _.init(),
            _
        } catch (_) {
            return this.effects.delete(s),
            log$8.error(_),
            Promise.reject(_)
        }
    }
    clearEffects() {
        this.effects.forEach(i=>{
            i.dispose(),
            this.effects.delete(i.id)
        }
        )
    }
    removeEffect(i) {
        const o = this.effects.get(i);
        o == null || o.dispose(),
        o && this.effects.delete(o.id)
    }
}
;
let XverseEffectManager = dr;
Tt(XverseEffectManager, "subEffect", XverseEffect);
Scene.DoubleClickDelay = 500;
class StaticMeshEvent extends EventEmitter {
    constructor(i) {
        super();
        Tt(this, "scene");
        Tt(this, "_staringPointerTime", -1);
        Tt(this, "_pickedMeshID", "0");
        Tt(this, "_pointerDownTime", -1);
        Tt(this, "_currentPickPoint");
        Tt(this, "_longPressDelay", 500);
        Tt(this, "_pointerTapDelay", 200);
        Tt(this, "_pickedMeshType");
        Tt(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)
            }
        }
        );
        Tt(this, "onUp", ()=>{
            if (Date.now() - this._pointerDownTime < this._pointerTapDelay && !this.scene._inputManager._isPointerSwiping()) {
                this.scene._inputManager._totalPointersPressed = 0;
                const i = this._currentPickPoint;
                i != null && this.emit("pointTap", i)
            }
        }
        );
        Tt(this, "onDown", ()=>{
            const i = this.onPointerTap(o=>o.isPickable);
            this._currentPickPoint = i,
            this._pointerDownTime = Date.now()
        }
        );
        Tt(this, "onDoubleTap", ()=>{
            const i = this.onPointerTap(void 0);
            i != null && this.emit("pointDoubleTap", i)
        }
        );
        this.manager = i,
        this.scene = i.Scene,
        this.registerEvent(),
        this._currentPickPoint = null,
        this._pickedMeshType = null
    }
    onPointerTap(i, o=!1) {
        var c, d;
        let s = new PickingInfo;
        if (o) {
            const _ = this.scene.multiPick(this.scene.pointerX, this.scene.pointerY, i, void 0, void 0);
            _ && _.length > 1 ? s = _[1] : _ && (s = _[0])
        } else
            s = this.scene.pick(this.scene.pointerX, this.scene.pointerY, i, !1, null);
        if (s.hit) {
            const _ = (c = s == null ? void 0 : s.pickedPoint) == null ? void 0 : c.asArray();
            if (_) {
                const [b,k,j] = _
                  , $ = xversePosition2Ue4({
                    x: b,
                    y: k,
                    z: j
                });
                return {
                    name: (d = s.pickedMesh) == null ? void 0 : d.name,
                    type: s.pickedMesh.xtype,
                    id: s.pickedMesh.xid,
                    point: $
                }
            }
        }
        return null
    }
}
class RotationEvent {
    constructor(e) {
        Tt(this, "touchStartX");
        Tt(this, "touchStartY");
        Tt(this, "handelResize");
        Tt(this, "_room");
        Tt(this, "_canvas");
        Tt(this, "handleTouchStart", e=>{
            const i = e.touches[0];
            this.touchStartX = i.pageX,
            this.touchStartY = i.pageY,
            this._room.emit("touchStart", {
                event: e
            })
        }
        );
        Tt(this, "handleMouseDown", e=>{
            this.touchStartX = e.pageX,
            this.touchStartY = e.pageY
        }
        );
        Tt(this, "handleMouseMove", e=>{
            if (!this.touchStartX || !this.touchStartY)
                return;
            const i = e.pageX
              , o = e.pageY
              , s = i - this.touchStartX
              , c = o - this.touchStartY
              , d = this._room.options.canvas.offsetHeight
              , _ = this._room.options.canvas.offsetWidth;
            let b = 2 * c / d
              , k = 2 * s / _;
            b > 1 && (b = 1),
            k > 1 && (k = 1),
            this._room.actionsHandler.rotate({
                pitch: b,
                yaw: k
            }),
            this.touchStartX = i,
            this.touchStartY = o
        }
        );
        Tt(this, "handleMouseUp", e=>{
            this.touchStartX = void 0,
            this.touchStartY = void 0,
            this._room.emit("mouseUp", {
                event: e
            })
        }
        );
        Tt(this, "handleTouchMove", e=>{
            if (!this.touchStartX || !this.touchStartY)
                return;
            const i = e.touches[0]
              , o = i.pageX
              , s = i.pageY
              , c = o - this.touchStartX
              , d = s - this.touchStartY
              , _ = this._room.options.canvas.offsetHeight
              , b = this._room.options.canvas.offsetWidth;
            let k = 2 * d / _
              , j = 2 * c / b;
            k > 1 && (k = 1),
            j > 1 && (j = 1),
            this._room.actionsHandler.rotate({
                pitch: k,
                yaw: j
            }),
            this.touchStartX = o,
            this.touchStartY = s,
            this._room.emit("touchMove", {
                pitch: k,
                yaw: j,
                event: e
            })
        }
        );
        Tt(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$7 = new Logger("eventsController");
class EventsController {
    constructor(e) {
        Tt(this, "staticmeshEvent");
        Tt(this, "rotationEvent");
        Tt(this, "resize", ()=>{
            this.room.panorama.actived || this.room.sceneManager.cameraComponent.cameraFovChange(this.room.sceneManager.yuvInfo)
        }
        );
        Tt(this, "clickEvent", e=>{
            const {point: i, name: o, type: s, id: c} = e;
            log$7.debug("pointEvent", e),
            this.room.proxyEvents("pointTap", {
                point: i,
                meshName: o,
                type: s,
                id: c
            }),
            this.room.proxyEvents("_coreClick", e)
        }
        );
        Tt(this, "longPressEvent", e=>{
            this.room.proxyEvents("_corePress", e)
        }
        );
        Tt(this, "handleActionResponseTimeout", ({error: e, event: i})=>{
            this.room.proxyEvents("actionResponseTimeout", {
                error: e,
                event: i
            })
        }
        );
        Tt(this, "handleNetworkStateChange", e=>{
            const {state: i, count: o} = e;
            i == "reconnecting" ? this.room.proxyEvents("reconnecting", {
                count: o || 1
            }) : i === "reconnected" ? (this.room.networkController.rtcp.workers.reset(),
            this.room.proxyEvents("reconnected"),
            this.room.afterReconnected()) : i === "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$6 = new Logger("panorama");
class Panorama {
    constructor(e) {
        Tt(this, "_actived", !1);
        Tt(this, "isLoading", !1);
        Tt(this, "handleReceivePanorama", async e=>{
            const i = e.camera;
            log$6.warn("handle panorama", i);
            const o = {
                data: e.data,
                pose: {
                    position: i.position,
                    rotation: i == null ? void 0 : i.angle
                }
            }
              , s = this.room.sceneManager;
            if (this.room.networkController.rtcp.workers.changePanoMode(!0),
            await s.materialComponent.changePanoImg(0, o),
            !!e.finished)
                if (await s.changePanoShaderForLowModel(0),
                this.room.isPano = !0,
                this._actived = !0,
                i)
                    this.room.sceneManager.cameraComponent.changeToFirstPersonView({
                        position: i.position,
                        rotation: i.angle
                    });
                else {
                    const {skinId: c, pathName: d} = this.room.currentState;
                    if (!c || !d)
                        return;
                    const _ = await this.room.modelManager.findRoute(c, d)
                      , {camera: b} = getRandomItem(_.birthPointList) || {};
                    b && this.room.sceneManager.cameraComponent.changeToFirstPersonView(Zt($t({}, b), {
                        rotation: b.angle
                    }))
                }
        }
        );
        this.room = e
    }
    get actived() {
        return this._actived
    }
    bindListener(e) {
        this.room.networkController.rtcp.workers.registerFunction("panorama", o=>{
            var b;
            log$6.warn("receive panorama");
            const {metadata: s} = o
              , c = JSON.parse(String.fromCharCode.apply(null, s));
            o.parsedMetaData = c;
            const d = (b = o.parsedMetaData.newUserStates) == null ? void 0 : b.find(k=>k.userId === this.room.userId)
              , _ = d == null ? void 0 : d.playerState.camera;
            o.camera = _,
            eventsManager.remove(o.parsedMetaData.traceIds[0], Codes$1.Success, o, !0),
            this.room.isFirstDataUsed || (this.room.isFirstDataUsed = !0,
            this.handleReceivePanorama(o).then(e))
        }
        )
    }
    access(e, i, o) {
        this.isLoading = !0;
        const {camera: s, player: c, attitude: d, areaName: _, pathName: b, tag: k} = e;
        return this.room.actionsHandler.requestPanorama({
            camera: s,
            player: c,
            attitude: d,
            areaName: _,
            pathName: b,
            tag: k
        }, i, o).then(j=>(this.isLoading = !1,
        this.handleReceivePanorama(j))).catch(j=>(this.isLoading = !1,
        Promise.reject(j)))
    }
    exit(e) {
        const {camera: i, player: o, attitude: s, areaName: c, pathName: d} = e;
        return this.room.networkController.rtcp.workers.changePanoMode(!1),
        this.room.actionsHandler.changeRotationRenderType({
            renderType: RenderType.RotationVideo,
            player: o,
            camera: i,
            attitude: s,
            areaName: c,
            pathName: d
        }).then(()=>this.handleExitPanorama()).catch(_=>(this.room.networkController.rtcp.workers.changePanoMode(!0),
        Promise.reject(_)))
    }
    handleExitPanorama() {
        var e, i, o, s, c, d;
        this.room.isPano = !1,
        this._actived = !1,
        (s = (e = this.room.sceneManager) == null ? void 0 : e.cameraComponent) == null || s.forceChangeSavedCameraPose({
            position: (i = this.room._currentClickingState) == null ? void 0 : i.camera.position,
            rotation: (o = this.room._currentClickingState) == null ? void 0 : o.camera.angle
        }),
        this.room.sceneManager.changeVideoShaderForLowModel(),
        (d = (c = this.room.sceneManager) == null ? void 0 : c.cameraComponent) == null || d.changeToThirdPersonView()
    }
}
class PathManager {
    constructor() {
        Tt(this, "currentArea", "");
        Tt(this, "currentPathName", "");
        Tt(this, "currentAttitude", "");
        Tt(this, "speed", 0)
    }
    getSpeed(e) {
        const i = {
            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
            }
        }
          , o = i[this.currentArea] || i.guangchang;
        return this.speed = o[e] * 30,
        this.speed
    }
}
const log$5 = new Logger("http");
class Http extends EventEmitter {
    constructor() {
        super(...arguments);
        Tt(this, "secondArray", new SecondArray)
    }
    async get({url: i, useIndexedDb: o=!1, timeout: s=15e3, key: c, isOutPutObjectURL: d=!0}) {
        if (Xverse$1.NO_CACHE !== void 0 && (o = !Xverse$1.NO_CACHE),
        o)
            if (isIndexedDbSupported()) {
                window.performance.now();
                let _ = null;
                try {
                    _ = await modelTable.query("url", i)
                } catch (b) {
                    return log$5.debug(b),
                    log$5.warn("cache query error", i),
                    Promise.resolve(i)
                }
                if (_ && _.model) {
                    let b = null;
                    const k = Date.now();
                    if (_.model instanceof Blob ? b = _.model : b = dataURItoBlob(_.model),
                    !b)
                        return Promise.reject("blob is null");
                    const j = Date.now();
                    this.secondArray.add(j - k);
                    const $ = Promise.resolve(d ? URL.createObjectURL(b) : b);
                    return window.performance.now(),
                    $
                } else
                    return this.request({
                        url: i,
                        timeout: s,
                        contentType: "blob",
                        key: c
                    }).then(async b=>{
                        const k = await blobToDataURI(b.response);
                        try {
                            await modelTable.put({
                                url: i,
                                model: k
                            })
                        } catch (j) {
                            log$5.warn("unable to add data to indexedDB", j)
                        }
                        return Promise.resolve(d ? URL.createObjectURL(b.response) : b.response)
                    }
                    )
            } else
                return this.request({
                    url: i,
                    timeout: s,
                    contentType: "blob",
                    key: c
                }).then(_=>{
                    const b = _.response;
                    return Promise.resolve(d ? URL.createObjectURL(b) : b)
                }
                ).catch(_=>Promise.reject(_));
        else
            return this.request({
                url: i,
                timeout: s,
                key: c
            }).then(_=>_.getResponseHeader("content-type") === "application/json" ? Promise.resolve(JSON.parse(_.responseText)) : Promise.resolve(_.responseText))
    }
    request(i) {
        const {timeout: o=3e4, contentType: s, key: c, onRequestStart: d} = i
          , {url: _} = i;
        return new Promise((b,k)=>{
            window.performance.now();
            const j = new XMLHttpRequest;
            s && (j.responseType = s),
            j.timeout = o,
            j.addEventListener("readystatechange", ()=>{
                if (j.readyState == 4) {
                    if (j.status == 200)
                        return window.performance.now(),
                        this.emit("loadend", {
                            message: `request ${_} load success`
                        }),
                        b(j);
                    {
                        const $ = `Unable to load the request ${_}`;
                        return this.emit("error", {
                            message: $
                        }),
                        log$5.error($),
                        k($)
                    }
                }
            }
            ),
            d && d(j),
            j.open("GET", _),
            j.send()
        }
        )
    }
}
const http = new Http
  , isIndexedDbSupported = ()=>(window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB) !== void 0
  , blobToDataURI = async a=>new Promise((e,i)=>{
    const o = new FileReader;
    o.readAsDataURL(a),
    o.onload = function(s) {
        var c;
        e((c = s.target) == null ? void 0 : c.result)
    }
    ,
    o.onerror = function(s) {
        i(s)
    }
}
)
  , dataURItoBlob = a=>{
    let e;
    a.split(",")[0].indexOf("base64") >= 0 ? e = atob(a.split(",")[1]) : e = unescape(a.split(",")[1]);
    const i = a.split(",")[0].split(":")[1].split(";")[0]
      , o = new Uint8Array(e.length);
    for (let c = 0; c < e.length; c++)
        o[c] = e.charCodeAt(c);
    return new Blob([o],{
        type: i
    })
}
  , log$4 = new Logger("xverse-signal");
class Signal {
    constructor(e) {
        Tt(this, "_room");
        Tt(this, "signalHandleActived", !0);
        Tt(this, "isUpdatedYUV", !0);
        Tt(this, "handleSignalSecondArray", new SecondArray);
        Tt(this, "handleSignalPartialArray2", new SecondArray);
        Tt(this, "handleSignalPartialArray3", new SecondArray);
        Tt(this, "handleSignalPartialArray4", new SecondArray);
        Tt(this, "handleSignalPartialArray5", new SecondArray);
        Tt(this, "handleSignalPartialArray6", new SecondArray);
        Tt(this, "handleSignalPartialArray7", new SecondArray);
        this._room = e
    }
    getSignalStat() {
        const e = this.handleSignalSecondArray.getStat()
          , i = this.handleSignalPartialArray2.getStat().max
          , o = this.handleSignalPartialArray3.getStat().max
          , s = this.handleSignalPartialArray4.getStat().max
          , c = this.handleSignalPartialArray5.getStat().max
          , d = this.handleSignalPartialArray6.getStat().max
          , _ = this.handleSignalPartialArray7.getStat().max
          , b = http.secondArray.getStat();
        return {
            sdkAvg: e.avg,
            sdkMax: e.max,
            blobSum: b.sum,
            blobMax: b.max,
            partialMax: [i, o, s, c, d, _]
        }
    }
    handleSignal(e, i) {
        var tt, rt, it;
        if (!this.signalHandleActived)
            return;
        const o = Date.now()
          , {signal: s, alreadyUpdateYUV: c} = e;
        this.handleActionResponses(s),
        this._room.handleSignalHook(s);
        const d = Date.now();
        if (this.handleSignalPartialArray2.add(d - o),
        !c) {
            const nt = (tt = s.newUserStates) == null ? void 0 : tt.find(ot=>ot.userId === this._room.userId);
            if ((nt == null ? void 0 : nt.renderInfo) && ((rt = this._room._userAvatar) == null ? void 0 : rt.isMoving)) {
                log$4.debug("stream stoped, make avatar to stop");
                const {isMoving: ot, isRotating: at} = nt.renderInfo;
                this._room.avatarManager._updateAvatarMovingStatus({
                    id: nt.userId,
                    isMoving: !!ot,
                    isRotating: !!at
                })
            }
            return
        }
        this.isUpdatedYUV = c;
        const _ = s;
        if (!s) {
            log$4.warn("metadata signal is empty");
            return
        }
        if (_.actionType === Actions.GetNewUserState) {
            eventsManager.remove(_.traceId, _.code, _);
            return
        }
        if (_.code === Codes$1.RepeatLogin) {
            this._room.handleRepetLogin();
            return
        }
        if (_.code !== void 0 && _.code !== Codes$1.Success && _.code !== Codes$1.ActionMaybeDelay && _.code !== Codes$1.DoActionBlocked && _.code !== Codes$1.GetOnVehicle)
            if (_.code === Codes$1.UnReachable)
                log$4.debug("signal errcode: ", _.code),
                this._room.proxyEvents("unreachable");
            else {
                if (!this._room.joined) {
                    const nt = getErrorByCode(_.code)
                      , ot = new nt(_.msg);
                    i(ot)
                }
                log$4.error("signal errcode: ", _),
                this._room.emit("error", _)
            }
        const b = Date.now();
        this.handleSignalPartialArray3.add(b - d);
        const k = (it = _.newUserStates) == null ? void 0 : it.find(nt=>nt.userId === this._room.userId);
        if (_.broadcastAction)
            try {
                const nt = JSON.parse(_.broadcastAction.data);
                Broadcast.handlers.forEach(ot=>ot(nt))
            } catch (nt) {
                log$4.error(nt)
            }
        const j = Date.now();
        this.handleSignalPartialArray4.add(j - b),
        _.newUserStates && _.newUserStates.length > 0 && this._room.avatarManager.handleAvatar(_);
        const $ = Date.now();
        if (this.handleSignalPartialArray5.add($ - j),
        k != null && k.playerState) {
            this._room._currentClickingState = k.playerState;
            const {pathName: nt, attitude: ot, areaName: at, skinId: st} = k.playerState;
            if (nt && (this._room.pathManager.currentPathName = nt,
            this._room.updateCurrentState({
                pathName: nt
            })),
            at && this._room.updateCurrentState({
                areaName: at
            }),
            ot) {
                const ut = this._room.skin.routeList.find(lt=>lt.areaName === this._room.currentState.areaName)
                  , ct = ((ut == null ? void 0 : ut.step) || 7.5) * 30;
                this._room.updateCurrentState({
                    speed: ct,
                    attitude: ot
                }),
                this._room.pathManager.currentAttitude = ot,
                this._room._userAvatar && (this._room._userAvatar.motionType = ot)
            }
            this._room.sceneManager.getCurrentShaderMode() !== ECurrentShaderMode.pano && !this._room.isPano && k.playerState.camera && !this._room.panorama.isLoading && this._room.camera.setCameraPose(k.playerState.camera)
        }
        k != null && k.renderInfo && this._room.camera.handleRenderInfo(k);
        const _e = Date.now();
        if (this.handleSignalPartialArray6.add(_e - $),
        _.actionType !== void 0) {
            const {actionType: nt, code: ot, echoMsg: at, traceId: st} = _;
            nt === Actions.Echo && ot === Codes$1.Success && this._room.networkController.rtcp.heartbeat.pong(at, st),
            ot !== Codes$1.Success ? eventsManager.remove(st, ot) : [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, Actions.GetNewUserState, Actions.SetSyncPolicy].includes(nt) && eventsManager.remove(st, ot, _)
        }
        const et = Date.now();
        this.handleSignalSecondArray.add(et - o),
        this.handleSignalPartialArray7.add(et - _e)
    }
    handleActionResponses(e) {
        !(e != null && e.actionResponses) || e.actionResponses.length === 0 || e.actionResponses.forEach(i=>{
            if (i.actionType == null)
                return;
            const {pointType: o, extra: s, actionType: c, traceId: d, code: _, msg: b} = i;
            c === Actions.GetNeighborPoints ? eventsManager.remove(d, _, i.nps) : c === Actions.GetUserWithAvatar ? eventsManager.remove(d, _, i.userWithAvatarList) : eventsManager.remove(d, _, b),
            o === PointType.Path && c === Actions.Clicking && (this._room.moveToExtra = decodeURIComponent(s))
        }
        )
    }
}
const BREATH_POINT_TYPE = "debugBreathPoint"
  , TAP_BREATH_POINT_TYPE = "debugTapBreathPoint"
  , DEFAULT_SEARCH_RANGE = 1e3;
class Debug {
    constructor(e) {
        Tt(this, "isShowNearbyBreathPoints", !1);
        Tt(this, "isShowTapBreathPoints", !1);
        Tt(this, "isSceneShading", !0);
        Tt(this, "searchRange", DEFAULT_SEARCH_RANGE);
        Tt(this, "nearbyBreathPointListening", !1);
        Tt(this, "tapBreathPointListening", !1);
        Tt(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, i=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()
        }
        , i)
    }
    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: i}) {
        let o;
        if (o = this.room.breathPointManager.breathPoints.get(i)) {
            o.position = e;
            return
        }
        this.room.breathPointManager.addBreathPoint({
            id: i,
            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 o, s;
        const e = this.searchRange
          , i = ((o = this.room._userAvatar) == null ? void 0 : o.position) && await this.getNeighborPoints({
            point: (s = this.room._userAvatar) == null ? void 0 : s.position,
            containSelf: !0,
            searchRange: e
        }) || [];
        this.room.breathPointManager.breathPoints.forEach(c=>{
            !!i.find(_=>JSON.stringify(_) === c._id) || this.room.breathPointManager.clearBreathPoints(c._id)
        }
        ),
        i.forEach(c=>{
            const d = JSON.stringify(c);
            this.room.breathPointManager.breathPoints.get(d) || this.room.breathPointManager.addBreathPoint({
                id: d,
                position: c,
                type: BREATH_POINT_TYPE,
                rotation: {
                    pitch: 90,
                    yaw: 0,
                    roll: 0
                },
                forceLeaveGround: !0
            })
        }
        )
    }
    getNeighborPoints(e) {
        const {point: i, containSelf: o=!1, searchRange: s=500} = e;
        return this.room.actionsHandler.getNeighborPoints({
            point: i,
            containSelf: o,
            searchRange: s
        })
    }
}
const log$3 = new Logger("xverse-room");
class XverseRoom$1 extends EventEmitter {
    constructor(i) {
        super();
        Tt(this, "disableAutoTurn", !1);
        Tt(this, "options");
        Tt(this, "_currentNetworkOptions");
        Tt(this, "lastSkinId");
        Tt(this, "debug");
        Tt(this, "isFirstDataUsed", !1);
        Tt(this, "userId", null);
        Tt(this, "pathManager", new PathManager);
        Tt(this, "networkController");
        Tt(this, "_startTime", Date.now());
        Tt(this, "canvas");
        Tt(this, "modelManager");
        Tt(this, "eventsController");
        Tt(this, "panorama");
        Tt(this, "engineProxy");
        Tt(this, "_id");
        Tt(this, "skinList", []);
        Tt(this, "isHost", !1);
        Tt(this, "avatarManager", new XverseAvatarManager(this));
        Tt(this, "effectManager", new XverseEffectManager(this));
        Tt(this, "sceneManager");
        Tt(this, "scene");
        Tt(this, "breathPointManager");
        Tt(this, "_currentState");
        Tt(this, "joined", !1);
        Tt(this, "disableRotate", !1);
        Tt(this, "isPano", !1);
        Tt(this, "movingByClick", !1);
        Tt(this, "camera", new Camera(this));
        Tt(this, "stats", new Stats(this));
        Tt(this, "isUpdatedRawYUVData", !1);
        Tt(this, "actionsHandler", new ActionsHandler(this));
        Tt(this, "_currentClickingState", null);
        Tt(this, "signal", new Signal(this));
        Tt(this, "allowRender", !0);
        Tt(this, "firstFrameTimestamp");
        Tt(this, "receiveRtcData", async()=>{
            log$3.info("Invoke receiveRtcData");
            let i = !1
              , o = !1
              , s = !1
              , c = !1;
            return this.viewMode === "serverless" ? (log$3.warn("set view mode to serverless"),
            this.setViewMode("observer").then(()=>this, ()=>this)) : new Promise((d,_)=>{
                const b = this.networkController.rtcp.workers;
                b.registerFunction("signal", k=>{
                    this.signal.handleSignal(k, _)
                }
                ),
                b.registerFunction("stream", k=>{
                    var j;
                    if (this.emit("streamTimestamp", {
                        timestamp: Date.now()
                    }),
                    o || (o = !0,
                    log$3.info("Invoke stream event")),
                    k.stream) {
                        s || (s = !0,
                        log$3.info("Invoke updateRawYUVData")),
                        this.isUpdatedRawYUVData = !1;
                        const $ = (j = this._currentState.skin) == null ? void 0 : j.fov;
                        this.sceneManager.materialComponent.updateRawYUVData(k.stream, k.width, k.height, $),
                        this.isUpdatedRawYUVData = !0
                    }
                    i || (log$3.info("Invoke isAfterRenderRegistered"),
                    i = !0,
                    this.scene.registerAfterRender(()=>{
                        this.engineProxy.frameRenderNumber >= 2 && (c || (c = !0,
                        log$3.info("Invoke registerAfterRender")),
                        this.isFirstDataUsed || (log$3.info("Invoke isStreamAvailable"),
                        this.isFirstDataUsed = !0,
                        this.firstFrameTimestamp = Date.now(),
                        d(this),
                        this.afterJoinRoom()))
                    }
                    ))
                }
                ),
                this.panorama.bindListener(()=>{
                    d(this),
                    this.afterJoinRoom()
                }
                ),
                b.registerFunction("reconnectedFrame", ()=>{}
                ),
                log$3.info("Invoke decoderWorker.postMessage"),
                b.decoderWorker.postMessage({
                    t: 5
                })
            }
            )
        }
        );
        Tt(this, "moveToExtra", "");
        this.options = i,
        this.options.wsServerUrl || (this.options.wsServerUrl = SERVER_URLS.DEV),
        this.modelManager = ModelManager.getInstance(i.appId, i.releaseId),
        this.updateReporter();
        const c = i
          , {canvas: o} = c
          , s = gr(c, ["canvas"]);
        log$3.infoAndReportMeasurement({
            metric: "startJoinRoomAt",
            startTime: Date.now(),
            group: "joinRoom",
            extra: s,
            value: 0
        })
    }
    get currentNetworkOptions() {
        return this._currentNetworkOptions
    }
    get viewMode() {
        var i;
        return ((i = this._currentState) == null ? void 0 : i.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 i;
        return Zt($t({}, this._currentState), {
            state: (i = this.networkController) == null ? void 0 : i._state
        })
    }
    get _userAvatar() {
        return this.avatars.find(i=>i.userId === this.userId)
    }
    get tvs() {
        return this.engineProxy._tvs
    }
    get tv() {
        return this.tvs[0]
    }
    get currentClickingState() {
        return this._currentClickingState
    }
    afterJoinRoomHook() {}
    beforeJoinRoomResolveHook() {}
    afterReconnectedHook() {}
    handleSignalHook(i) {}
    skinChangedHook() {}
    async beforeStartGameHook(i) {}
    afterLoadAssetsHook() {}
    afterUserAvatarLoadedHook() {}
    audienceViewModeHook(i) {}
    setViewModeToObserver() {}
    handleVehicleHook(i) {}
    updateReporter() {
        const {avatarId: i, skinId: o, userId: s, roomId: c, role: d, appId: _, wsServerUrl: b} = this.options;
        reporter.updateHeader({
            userId: s
        }),
        reporter.updateBody({
            roomId: c,
            role: d,
            skinId: o,
            avatarId: i,
            appId: _,
            wsServerUrl: b
        })
    }
    async initRoom() {
        const {timeout: i=DEFAULT_JOINROOM_TIMEOUT} = this.options;
        return isSupported() ? this._initRoom()._timeout(i, new TimeoutError("initRoom timeout")) : Promise.reject(new UnsupportedError)
    }
    async _initRoom() {
        const i = this.validateOptions(this.options);
        if (i)
            return log$3.error("initRoom param error", i),
            Promise.reject(i);
        const {canvas: o, avatarId: s, skinId: c, userId: d, wsServerUrl: _, role: b, token: k, pageSession: j, rotationRenderType: $, isAllSync: _e=!1, appId: et, camera: tt, player: rt, avatarComponents: it, nickname: nt, avatarScale: ot, firends: at=[], syncByEvent: st=!1, areaName: ut, attitude: ct=MotionType.Walk, pathName: lt, viewMode: ft="full", person: ht, roomId: pt, roomTypeId: dt, hasAvatar: _t=!1, syncToOthers: mt=!1, prioritySync: vt=!1, removeWhenDisconnected: yt=!0, extra: Et} = this.options;
        this.setCurrentNetworkOptions({
            avatarId: s,
            skinId: c,
            roomId: pt,
            userId: d,
            wsServerUrl: _,
            role: b,
            token: k,
            pageSession: j,
            rotationRenderType: $,
            isAllSync: _e,
            appId: et,
            camera: tt,
            player: rt,
            avatarComponents: it,
            nickname: nt,
            avatarScale: ot,
            firends: at,
            syncByEvent: st,
            areaName: ut,
            attitude: ct,
            pathName: lt,
            person: ht,
            roomTypeId: dt,
            hasAvatar: _t,
            syncToOthers: mt,
            prioritySync: vt,
            extra: Et,
            removeWhenDisconnected: yt
        }),
        this.userId = d,
        this.canvas = o,
        ut && (this.pathManager.currentArea = ut),
        this.networkController = new NetworkController(this),
        this.setCurrentState({
            areaName: ut,
            pathName: lt,
            attitude: ct,
            speed: 0,
            viewMode: ft,
            state: this.networkController._state,
            skinId: c
        });
        try {
            await Promise.all([this.initNetwork(), this.initConfig(), this.initWasm()]),
            log$3.info("network config wasm all ready, start to create game");
            const At = await this.requestCreateRoom({
                skinId: c
            })
              , gt = At.routeList.find(xt=>xt.areaName === ut)
              , St = ((gt == null ? void 0 : gt.step) || 7.5) * 30;
            this.updateCurrentState({
                skin: At,
                skinId: At.id,
                versionId: At.versionId,
                speed: St
            }),
            await this.initEngine(At)
        } catch (At) {
            return Promise.reject(At)
        }
        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 || Date.now() - this._startTime,
            startTime: Date.now(),
            metric: "joinRoom",
            reportOptions: {
                immediate: !0
            }
        }),
        this.camera.initialFov = this.sceneManager.cameraComponent.getCameraFov(),
        this.stats.on("stats", ({stats: i})=>{
            reporter.report("stats", $t({}, i))
        }
        ),
        this.debug = new Debug(this),
        this.afterJoinRoomHook(),
        setInterval(()=>{
            this.actionsHandler.getNewUserState(NewUserStateType.NUST_Undefined).then(i=>{
                this.avatarManager.handleAvatar(i)
            }
            ).catch(()=>{}
            )
        }
        , 2e3)
    }
    afterReconnected() {
        this.avatarManager.clearOtherUsers(),
        this.afterReconnectedHook()
    }
    leave() {
        var i, o;
        return log$3.info("Invoke room.leave"),
        (i = this.eventsController) == null || i.clearEvents(),
        (o = this.networkController) == null || o.quit(),
        this
    }
    validateOptions(i) {
        const {canvas: o, avatarId: s, skinId: c, userId: d, role: _, roomId: b, token: k, appId: j, avatarComponents: $} = i || {}
          , _e = [];
        return o instanceof HTMLCanvasElement || _e.push(new ParamError("`canvas` must be instanceof of HTMLCanvasElement")),
        (!d || typeof d != "string") && _e.push(new ParamError("`userId` must be string")),
        (!k || typeof k != "string") && _e.push(new ParamError("`token` must be string")),
        (!j || typeof j != "string") && _e.push(new ParamError("`appId` must be string")),
        _ == "audience" || (!s || !c) && _e.push(new ParamError("`avatarId` and `skinId` is required when create room")),
        _e[0]
    }
    async initNetwork() {
        if (this.viewMode === "serverless")
            return Promise.resolve();
        const i = 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: i,
                group: "joinRoom"
            })
        } catch (o) {
            throw log$3.infoAndReportMeasurement({
                metric: "networkInitAt",
                startTime: i,
                group: "joinRoom",
                error: o
            }),
            o
        }
    }
    async initConfig() {
        const i = 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: i,
                group: "joinRoom"
            })
        } catch (o) {
            throw log$3.infoAndReportMeasurement({
                metric: "configInitAt",
                startTime: i,
                group: "joinRoom",
                error: o
            }),
            o
        }
    }
    async initEngine(i) {
        const o = Date.now();
        try {
            this.engineProxy = new EngineProxy(this),
            await this.engineProxy.initEngine(i)._timeout(8e3, new InitEngineError("init engine timeout in 8s")),
            log$3.infoAndReportMeasurement({
                metric: "webglInitAt",
                startTime: this._startTime,
                group: "joinRoom"
            }),
            log$3.infoAndReportMeasurement({
                metric: "webglInitCost",
                startTime: o,
                group: "joinRoom"
            });
            return
        } catch (s) {
            let c = s;
            return s.code !== Codes$1.InitEngineTimeout && (c = new InitEngineError(s)),
            log$3.error(s),
            log$3.infoAndReportMeasurement({
                metric: "webglInitAt",
                startTime: o,
                group: "joinRoom",
                error: c
            }),
            Promise.reject(c)
        }
    }
    async initWasm() {
        if (this.viewMode === "serverless")
            return Promise.resolve();
        const i = Date.now();
        try {
            await this.networkController.rtcp.workers.init({
                width: 1920,
                height: 1080,
                userID: this.userId,
                pageSession: this.options.pageSession,
                serverSession: ""
            })._timeout(8e3, new InitDecoderTimeoutError),
            this.networkController.rtcp.workers.registerFunction("error", o=>{
                log$3.error("decode error", o);
                const {code: s, message: c} = o;
                this.emit("error", {
                    code: s,
                    msg: c
                })
            }
            ),
            log$3.infoAndReportMeasurement({
                metric: "wasmInitAt",
                group: "joinRoom",
                startTime: this._startTime
            }),
            log$3.infoAndReportMeasurement({
                metric: "wasmInitCost",
                group: "joinRoom",
                startTime: i
            }),
            eventsManager.on("traceId", o=>{
                this.networkController.rtcp.workers.onTraceId(o)
            }
            )
        } catch (o) {
            throw log$3.infoAndReportMeasurement({
                metric: "wasmInitAt",
                group: "joinRoom",
                startTime: i,
                error: o
            }),
            o
        }
    }
    async requestCreateRoom({skinId: i}) {
        let o;
        if (i) {
            o = await this.getSkin(i),
            this.updateCurrentState({
                skin: o
            });
            const s = await this.modelManager.findRoute(i, this.options.pathName);
            this.updateCurrentNetworkOptions({
                areaName: s.areaName,
                attitude: s.attitude,
                versionId: o.versionId
            });
            const {camera: c, player: d} = getRandomItem(s.birthPointList) || this.options;
            this.options.camera || this.updateCurrentNetworkOptions({
                camera: c
            }),
            this.options.player || this.updateCurrentNetworkOptions({
                player: d
            })
        }
        if (this.viewMode === "serverless")
            return o;
        try {
            await this.beforeStartGameHook(this.options);
            const {room_id: s, data: c, session_id: d} = await this.networkController.startGame();
            this._id = s;
            const _ = JSON.parse(c);
            this.isHost = _.IsHost,
            i = _.SkinID || i;
            const b = await this.getSkin(i);
            return this.updateCurrentNetworkOptions({
                roomId: s,
                sessionId: d
            }),
            reporter.updateBody({
                roomId: s,
                skinId: i,
                serverSession: d
            }),
            b
        } catch (s) {
            return log$3.error("requestCreateRoom error:", s),
            Promise.reject(s)
        }
    }
    pause() {
        return this.engineProxy.pause()
    }
    resume() {
        return this.engineProxy.resume()
    }
    reconnect() {
        this.networkController.reconnect()
    }
    async setViewMode(i) {}
    handleRepetLogin() {
        log$3.warn("receive " + Codes$1.RepeatLogin + " for repeat login"),
        this.emit("repeatLogin"),
        reporter.disable(),
        this.networkController.quit()
    }
    setPictureQualityLevel(i) {
        const o = {
            high: EImageQuality.high,
            low: EImageQuality.low,
            average: EImageQuality.mid
        };
        return this.updateCurrentState({
            pictureQualityLevel: i
        }),
        this.sceneManager.setImageQuality(o[i])
    }
    async getSkin(i) {
        let o = null;
        if (o = (this.skinList = await this.modelManager.getSkinsList()).find(c=>c.id === i || c.id === i),
        o)
            return o;
        {
            const c = `skin is invalid: skinId: ${i}`;
            return Promise.reject(new ParamError(c))
        }
    }
    setupStats() {
        this.stats.assign({
            roomId: this.id,
            userId: this.userId
        }),
        setInterval(this.engineProxy.updateStats, 1e3)
    }
    proxyEvents(i, o) {
        this.emit(i, o)
    }
    setCurrentNetworkOptions(i) {
        this._currentNetworkOptions = i
    }
    updateCurrentNetworkOptions(i) {
        Object.assign(this._currentNetworkOptions, i),
        Object.assign(this.options, i)
    }
    setCurrentState(i) {
        this._currentState = i
    }
    updateCurrentState(i) {
        i.skinId && (this.lastSkinId = this.currentState.skinId,
        this.updateCurrentNetworkOptions({
            skinId: i.skinId
        })),
        i.versionId && this.updateCurrentNetworkOptions({
            versionId: i.versionId
        }),
        Object.assign(this._currentState, i)
    }
    afterSetUrlHook() {}
    afterTvStopedHook() {}
    afterTvPlayedHook() {}
    pageShowHandler() {
        this.engineProxy.setEnv(this.skin),
        this.allowRender = !0
    }
    pageHideHandler() {
        this.allowRender = !1
    }
}
var RenderType = (a=>(a[a.PathVideo = 0] = "PathVideo",
a[a.RotationVideo = 1] = "RotationVideo",
a[a.RotationImage = 2] = "RotationImage",
a[a.PanoramaImage = 3] = "PanoramaImage",
a[a.CGVideo = 4] = "CGVideo",
a[a.ClientRotationPano = 5] = "ClientRotationPano",
a[a.CloudRotationPano = 6] = "CloudRotationPano",
a))(RenderType || {})
  , Person = (a=>(a[a.Third = 0] = "Third",
a[a.First = 1] = "First",
a))(Person || {})
  , LandingType = (a=>(a[a.Stay = 0] = "Stay",
a[a.InitPoint = 1] = "InitPoint",
a[a.NewPoint = 2] = "NewPoint",
a))(LandingType || {})
  , ClickType = (a=>(a[a.Screen = 0] = "Screen",
a[a.ThreeDimension = 1] = "ThreeDimension",
a[a.ThreeDimensionQuick = 2] = "ThreeDimensionQuick",
a[a.IgnoreView = 3] = "IgnoreView",
a))(ClickType || {})
  , ChangeMode = (a=>(a[a.Preview = 0] = "Preview",
a[a.Confirm = 1] = "Confirm",
a[a.Cancel = 2] = "Cancel",
a))(ChangeMode || {})
  , PointType = (a=>(a[a.Path = 0] = "Path",
a[a.Item = 1] = "Item",
a[a.Closeup = 2] = "Closeup",
a[a.NoValidMatched = 3] = "NoValidMatched",
a))(PointType || {});
const log$2 = new Logger("xverse-avatar-tools")
  , isSuit = a=>a === "suit"
  , avatarComponentsParser = async(a=null,e,i=[])=>new Promise(async(o,s)=>{
    var k, j;
    if (e.find($=>isSuit($.type))) {
        const $ = (j = (k = a == null ? void 0 : a.components) == null ? void 0 : k.find(_e=>isSuit(_e.type))) == null ? void 0 : j.suitComb;
        e = e.filter(_e=>($ == null ? void 0 : $.indexOf(_e.type)) === -1)
    }
    const d = e.filter($=>!i.some(_e=>_e.id === $.id));
    d.length === 0 && o([]);
    const _ = [];
    d.forEach(async$=>{
        var tt;
        let _e = (tt = a == null ? void 0 : a.components) == null ? void 0 : tt.find(rt=>rt.type === $.type);
        if (!_e) {
            const rt = `changeComponents, no such component with type: ${$.type}`;
            log$2.error(rt),
            s(rt)
        }
        _e = JSON.parse(JSON.stringify(_e));
        let et = _e == null ? void 0 : _e.units.find(rt=>rt.id === $.id);
        et || (log$2.warn(`changeComponents, no unit with type: ${$.type}, id: ${$.id}`),
        et = _e == null ? void 0 : _e.units.find(rt=>rt.isDefault),
        !et && log$2.warn(`changeComponents, no default unit with type: ${$.type}`)),
        et && _.push({
            id: et.id,
            url: et.url,
            suitComb: (_e == null ? void 0 : _e.suitComb) || [],
            type: $.type
        })
    }
    );
    const b = [];
    Promise.all(b).then($=>{
        _.forEach((_e,et)=>{
            var tt, rt;
            if (!isSuit(_e.type)) {
                const it = ((rt = (tt = a == null ? void 0 : a.components) == null ? void 0 : tt.find(nt=>isSuit(nt.type))) == null ? void 0 : rt.suitComb) || [];
                it.length > 0 && (it == null ? void 0 : it.indexOf(_e.type)) !== -1 && (_e.suitComb = ["suit"])
            }
            _e.url = $[et]
        }
        ),
        o(_)
    }
    ).catch($=>{
        s($)
    }
    )
}
)
  , avatarComponentsModify = (a,e)=>new Promise((i,o)=>{
    var b;
    let s = [];
    const c = []
      , d = [];
    let _ = e.some(k=>isSuit(k.type));
    if ((b = a == null ? void 0 : a.components) == null || b.forEach(k=>{
        var _e;
        const j = e.find(et=>et.type === k.type)
          , $ = j && ((_e = a == null ? void 0 : a.components) == null ? void 0 : _e.find(et=>et.type === j.type && et.units.some(tt=>tt.id === j.id))) !== void 0;
        if (j)
            if ($)
                s.push(j);
            else {
                const et = k.units.find(tt=>tt.isDefault) || k.units[0];
                et ? s.push({
                    type: k.type,
                    id: et.id
                }) : c.push(`component with type: ${k.type} without default and available unit`)
            }
        else if (isSuit(k.type)) {
            const et = k.units.find(tt=>tt.isDefault);
            et && s.push({
                type: k.type,
                id: et.id
            })
        } else {
            const et = k.units.find(tt=>tt.isDefault) || k.units[0];
            et ? s.push({
                type: k.type,
                id: et.id
            }) : c.push(`component with type: ${k.type} without default and available unit`)
        }
    }
    ),
    _ = s.some(k=>isSuit(k.type)),
    _) {
        const k = a == null ? void 0 : a.components.find(j=>isSuit(j.type));
        s = s.filter(j=>(k == null ? void 0 : k.suitComb.indexOf(j.type)) === -1)
    }
    c.length > 0 && (log$2.error(c.join(", ")),
    o(c.join(", "))),
    d.length > 0 && log$2.warn(d.join(", ")),
    i(s)
}
)
  , positionPrecisionProtect = a=>{
    const {x: e, y: i, z: o} = a;
    return {
        x: +e.toFixed(2),
        y: +i.toFixed(2),
        z: +o.toFixed(2)
    }
}
  , rotationPrecisionProtect = a=>{
    const {pitch: e, yaw: i, roll: o} = a;
    return {
        pitch: +e.toFixed(2),
        yaw: +i.toFixed(2),
        roll: +o.toFixed(2)
    }
}
  , avatarComponentsValidate = (a,e)=>{
    a = a.filter(s=>s.type !== "effect");
    const i = []
      , o = {};
    return Array.isArray(a) ? (a.forEach(s=>{
        o[s.type] ? o[s.type].num++ : o[s.type] = {
            num: 1,
            isSuit: isSuit(s.type)
        }
    }
    ),
    Object.keys(o).forEach(s=>{
        if (o[s].num > 1 && i.push(new ParamError(`avatarComponent with type: ${s} repeated`)),
        o[s].isSuit) {
            const c = e.components.find(d=>isSuit(d.type));
            c == null || c.suitComb.forEach(d=>{
                Object.keys(o).indexOf(d) > -1 && i.push(new ParamError(`suit already contains: ${d},  ${d} repeated`))
            }
            )
        }
    }
    ),
    i[0]) : (i.push(new ParamError("avatarComponents must be array")),
    i[0])
}
  , safeParseComponents = a=>{
    let e = [];
    try {
        e = JSON.parse(a || "[]")
    } catch {
        e = [],
        log$2.error(`avatarComponents parse error: ${a}`)
    }
    return e
}
;
var QueueType = (a=>(a.Move = "Move",
a.Rotate = "Rotate",
a))(QueueType || {});
class Queue {
    constructor() {
        Tt(this, "queue", []);
        Tt(this, "currentAction")
    }
    async append(e) {
        var i, o;
        this.queue.length === 0 || ((i = this.currentAction) == null ? void 0 : i.type) === e.type && this.queue.length === 1 ? (this.queue = [],
        this.queue.push(e),
        await this.go()) : (((o = this.queue[this.queue.length - 1]) == null ? void 0 : o.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: i, isHost: o, room: s, avatarId: c, isSelf: d, group: _=AvatarGroup.Npc}) {
        super();
        Tt(this, "xAvatar");
        Tt(this, "_isHost", !1);
        Tt(this, "_room");
        Tt(this, "_withModel", !1);
        Tt(this, "_userId");
        Tt(this, "group", AvatarGroup.User);
        Tt(this, "state", "idle");
        Tt(this, "isLoading", !0);
        Tt(this, "_isMoving", !1);
        Tt(this, "_isRotating", !1);
        Tt(this, "_failed", !1);
        Tt(this, "disconnected", !1);
        Tt(this, "_avatarId");
        Tt(this, "prioritySync", !1);
        Tt(this, "priority", EAvatarRelationRank.Stranger);
        Tt(this, "_avatarModel");
        Tt(this, "_motionType", MotionType.Walk);
        Tt(this, "isSelf", !1);
        Tt(this, "_lastAnimTraceId", "");
        Tt(this, "statusSyncQueue", new Queue);
        Tt(this, "extraInfo", {});
        Tt(this, "attachedEffects", new Set);
        Tt(this, "currentPathName", "");
        Tt(this, "setPosition", i=>{
            var o;
            !this._room.signal.isUpdatedYUV || (o = this.xAvatar) == null || o.setPosition(positionPrecisionProtect(i), !0)
        }
        );
        Tt(this, "setRotation", i=>{
            var o;
            !this._room.signal.isUpdatedYUV || (o = this.xAvatar) == null || o.setRotation(rotationPrecisionProtect(i))
        }
        );
        Tt(this, "stopAnimation", ()=>{
            var i, o;
            (o = (i = this.xAvatar) == null ? void 0 : i.controller) == null || o.stopAnimation()
        }
        );
        Tt(this, "_playAnimation", async(i,o=!0,s=!1)=>{
            var d;
            if (!this._room.signal.isUpdatedYUV)
                return;
            if (this.state !== "idle" && !s)
                return log$1.warn("_playAnimation", i, "state is not idle, play animation failed"),
                Promise.resolve("_playAnimation, state is not idle");
            const c = Date.now();
            try {
                if (!((d = this.xAvatar) != null && d.controller))
                    return Promise.reject(new InternalError(`[avatar: ${this.userId}] Play animation failed: ${i}, no controller`));
                this.isSelf && setTimeout(()=>{
                    log$1.infoAndReportMeasurement({
                        tag: i,
                        startTime: c,
                        value: 0,
                        metric: "playAnimationStart"
                    })
                }
                );
                const _ = uuid$1();
                this._lastAnimTraceId = _,
                await this.xAvatar.controller.playAnimation(i, o),
                _ === this._lastAnimTraceId && !this.isMoving && !o && i !== "Idle" && this.xAvatar.controller.playAnimation("Idle", o).catch(b=>{
                    log$1.error(`[avatar: ${this.userId}] Play animation failed [force idle]`, b)
                }
                ),
                this.isSelf && log$1.infoAndReportMeasurement({
                    tag: i,
                    startTime: c,
                    extra: {
                        loop: o
                    },
                    metric: "playAnimationEnd"
                })
            } catch (_) {
                return log$1.error(`[avatar: ${this.userId}] Play animation failed: ${i}`, _),
                this.isSelf && log$1.infoAndReportMeasurement({
                    tag: i,
                    startTime: c,
                    metric: "playAnimationEnd",
                    error: _,
                    extra: {
                        loop: o
                    }
                }),
                Promise.reject(_)
            }
        }
        );
        Tt(this, "avatarComponentsSync", i=>{
            i = i.map(o=>({
                type: o.type,
                id: o.id
            })),
            this._room.actionsHandler.avatarComponentsSync(i)
        }
        );
        Tt(this, "hide", ()=>{
            var i;
            if ((i = this.xAvatar) != null && i.hide())
                return Promise.resolve(`avatar: ${this.userId} hide success`);
            {
                const o = `avatar: ${this.userId} hide failed ${!this.xAvatar && "without instance: xAvatar"}`;
                return log$1.warn(o),
                Promise.reject(o)
            }
        }
        );
        Tt(this, "show", ()=>{
            var i;
            if ((i = this.xAvatar) != null && i.show())
                return Promise.resolve(`avatar: ${this.userId} show success`);
            {
                const o = `avatar: ${this.userId} show failed ${!this.xAvatar && "without instance: xAvatar"}`;
                return log$1.warn(o),
                Promise.reject(o)
            }
        }
        );
        Tt(this, "sayTimer");
        this._userId = i,
        this._room = s,
        this.isSelf = d || !1,
        this._withModel = !!c,
        this._isHost = o || !1,
        this._avatarId = c,
        this.group = _,
        this._room.modelManager.getAvatarModelList().then(b=>{
            const k = b.find(j=>j.id === c);
            k && (this._avatarModel = k)
        }
        )
    }
    get avatarId() {
        return this._avatarId
    }
    get isRender() {
        var i;
        return !!((i = this.xAvatar) != null && i.isRender)
    }
    get isHidden() {
        var i;
        return !!((i = this.xAvatar) != null && i.isHide)
    }
    get motionType() {
        return this._motionType
    }
    set motionType(i) {
        this._motionType = i
    }
    get nickname() {
        var i;
        return (i = this.xAvatar) == null ? void 0 : i.nickName
    }
    get words() {
        var i;
        return (i = this.xAvatar) == null ? void 0 : i.words
    }
    get isHost() {
        return this._isHost
    }
    get failed() {
        return this._failed
    }
    get scale() {
        var i;
        return (i = this.xAvatar) == null ? void 0 : i.scale
    }
    get animations() {
        var i;
        return !this.xAvatar || !this.xAvatar.controller ? [] : ((i = this.xAvatar) == null ? void 0 : i.getAvaliableAnimations()) || []
    }
    get position() {
        var i;
        return (i = this.xAvatar) == null ? void 0 : i.position
    }
    get rotation() {
        var i;
        return (i = this.xAvatar) == null ? void 0 : i.rotation
    }
    get pose() {
        return {
            position: this.position,
            angle: this.rotation
        }
    }
    get id() {
        return this.userId
    }
    get isMoving() {
        return this._isMoving
    }
    set isMoving(i) {
        this._isMoving = i,
        this.state = i ? "moving" : "idle"
    }
    get isRotating() {
        return this._isRotating
    }
    set isRotating(i) {
        this._isRotating = i,
        this.state = i ? "rotating" : "idle"
    }
    get withModel() {
        return this._withModel
    }
    get avatarComponents() {
        var i;
        return JSON.parse(JSON.stringify(((i = this.xAvatar) == null ? void 0 : i.clothesList) || []))
    }
    get userId() {
        return this._userId
    }
    get removeWhenDisconnected() {
        return this.extraInfo && this.extraInfo.removeWhenDisconnected !== void 0 ? this.extraInfo.removeWhenDisconnected : !0
    }
    setConnectionStatus(i) {
        this.disconnected !== i && (this.disconnected = i,
        i ? this.emit("disconnected") : this.emit("reconnected"),
        log$1.warn(`avatar ${this.userId} status changed, disconnected:`, i))
    }
    setScale(i) {
        var o;
        this.scale !== i && ((o = this.xAvatar) == null || o.setScale(i > 0 ? i : 1))
    }
    async playAnimation(i) {
        const {animationName: o, loop: s, extra: c} = i || {};
        if (this.isSelf) {
            if (this.isMoving)
                try {
                    await this.stopMoving()
                } catch (_) {
                    return log$1.error(`stopMoving error before playAnimation ${o}`, _),
                    Promise.reject(`stopMoving error before playAnimation ${o}`)
                }
            const d = {
                info: {
                    userId: this.userId,
                    animation: o,
                    loop: s,
                    extra: encodeURIComponent(c || "")
                },
                broadcastType: CoreBroadcastType.PlayAnimation
            };
            this._room.avatarManager.broadcast.broadcast({
                data: d
            })
        }
        return this.isSelf && (log$1.warn("animationStart emit", o),
        this.emit("animationStart", {
            animationName: o,
            extra: safeDecodeURIComponent(c || "")
        })),
        this._playAnimation(o, s).then(()=>{
            this.isSelf && (log$1.warn("animationEnd emit", o),
            this.emit("animationEnd", {
                animationName: o,
                extra: safeDecodeURIComponent(c || "")
            }))
        }
        )
    }
    async changeComponents(i) {
        const {mode: o, endAnimation: s=""} = i || {}
          , c = JSON.parse(JSON.stringify(i.avatarComponents));
        let d = avatarComponentsValidate(c, this._avatarModel);
        return !ChangeComponentsMode[o] && !d && (d = new ParamError(`changeComponents failed, mode: ${o} is invalid`)),
        d ? (log$1.error(d),
        Promise.reject(d)) : this._changeComponents({
            avatarComponents: c,
            mode: o,
            endAnimation: s
        }).then(()=>{
            this.isSelf && o !== ChangeComponentsMode.Preview && this.avatarComponentsSync(this.avatarComponents)
        }
        )
    }
    async _changeComponents(i) {
        var d;
        const {avatarComponents: o=[], mode: s} = i || {}
          , c = Date.now();
        try {
            if (!this.xAvatar)
                return Promise.reject(new InternalError("changeComponents failed, without instance: xAvatar"));
            const _ = await avatarComponentsModify(this._avatarModel, o)
              , b = []
              , k = await avatarComponentsParser(this._avatarModel, _, this.avatarComponents);
            if (k.length === 0)
                return this.avatarComponents;
            await this.beforeChangeComponentsHook(i);
            for (const j of k) {
                const {id: $, type: _e, url: et, suitComb: tt} = j;
                b.push((d = this.xAvatar) == null ? void 0 : d.addComponent($, _e, et, tt))
            }
            return await Promise.all(b),
            this.emit("componentsChanged", {
                components: this.avatarComponents,
                mode: s
            }),
            this.isSelf && log$1.infoAndReportMeasurement({
                tag: "changeComponents",
                startTime: c,
                metric: "changeComponents",
                extra: {
                    inputComponents: o,
                    finalComponents: this.avatarComponents,
                    mode: ChangeComponentsMode[s]
                }
            }),
            this.avatarComponents
        } catch (_) {
            return this.isSelf && log$1.infoAndReportMeasurement({
                tag: "changeComponents",
                startTime: c,
                metric: "changeComponents",
                error: _,
                extra: {
                    inputComponents: o,
                    finalComponents: this.avatarComponents,
                    mode: ChangeComponentsMode[s]
                }
            }),
            Promise.reject(_)
        }
    }
    async beforeChangeComponentsHook(i) {}
    turnTo(i) {
        if (this._room.viewMode === "observer") {
            this._room.sceneManager.cameraComponent.MainCamera.setTarget(ue4Position2Xverse(i.point));
            return
        }
        return this._room.actionsHandler.turnTo(i).then(()=>{
            this.emit("viewChanged", {
                extra: (i == null ? void 0 : i.extra) || ""
            })
        }
        )
    }
    async moveTo(i) {
        const {point: o, extra: s=""} = i || {};
        if (!this.position)
            return Promise.reject(new ParamError("avatar position is empty"));
        if (typeof s != "string" || typeof s == "string" && s.length > 64) {
            const _ = "extra shoud be string which length less than 64";
            return log$1.warn(_),
            Promise.reject(new ParamError(_))
        }
        const d = getDistance(this.position, o) / 100 > 100 ? MotionType.Run : MotionType.Walk;
        return this._room.actionsHandler.moveTo({
            point: o,
            motionType: d,
            extra: s
        })
    }
    async stopMoving() {
        if (!!this.isMoving)
            return this._room.actionsHandler.stopMoving()
    }
    rotateTo(i) {
        return this._room.actionsHandler.rotateTo(i)
    }
    setRayCast(i) {
        this.xAvatar && (this.xAvatar.isRayCastEnable = i)
    }
    say(i, o) {
        let s, c, d, _;
        if (typeof o == "object" ? (s = o.duration,
        c = o.background,
        d = o.fontSize,
        _ = o.fontColor) : typeof o == "number" && (s = o),
        this.sayTimer && window.clearTimeout(this.sayTimer),
        !this.xAvatar) {
            log$1.error("say failed, without instance: xAvatar");
            return
        }
        this.xAvatar.say(i, {
            scale: this.xAvatar.scale,
            isUser: this.group === AvatarGroup.User,
            background: c,
            fontsize: d,
            fontcolor: _
        }),
        !(s === void 0 || s <= 0) && (this.sayTimer = window.setTimeout(()=>{
            this.silent()
        }
        , s))
    }
    silent() {
        var i;
        if (!this.xAvatar) {
            log$1.error("silent failed, without instance: xAvatar");
            return
        }
        (i = this.xAvatar) == null || i.silent()
    }
    setMotionType({type: i=MotionType.Walk}) {
        return this.motionType === i ? Promise.resolve() : this._room.actionsHandler.setMotionType(i).then(()=>{
            this._motionType = i
        }
        )
    }
    setNickname(i) {
        return this._room.actionsHandler.setNickName(encodeURIComponent(i))
    }
    _setNickname(i) {
        var s, c;
        if (!i)
            return;
        const o = safeDecodeURIComponent(i);
        ((s = this.xAvatar) == null ? void 0 : s.nickName) !== o && (this.isSelf && (this._room.updateCurrentNetworkOptions({
            nickname: o
        }),
        this._room.options.nickname = o),
        (c = this.xAvatar) == null || c.setNickName(o, {
            scale: this.xAvatar.scale
        }))
    }
    _move(i) {
        var k;
        const {start: o, end: s, walkSpeed: c, moveAnimation: d="Walking", inter: _=[], enforceRaycast: b=!0} = i || {};
        return (k = this.xAvatar) == null ? void 0 : k.move(o, s, c, d, _, b)
    }
    moveHermite(i) {
        var k;
        const {start: o, end: s, moveAnimation: c="Walking", duration: d, tension: _, enforceRaycast: b=!1} = i || {};
        return (k = this.xAvatar) == null ? void 0 : k.moveHermite(o, s, d, _, c, b)
    }
    move(i) {
        return this._move(i)
    }
    setPickBoxScale(i=1) {
        return this.xAvatar ? (this.xAvatar.setPickBoxScale(i),
        !0) : (log$1.error("setPickBoxScale failed, without instance: xAvatar"),
        !1)
    }
    transfer(i) {
        const {player: o, camera: s, areaName: c, attitude: d, pathName: _} = i;
        return this._room.actionsHandler.transfer({
            renderType: RenderType.RotationVideo,
            player: o,
            camera: s,
            areaName: c,
            attitude: d,
            pathName: _,
            tag: "transfer"
        })
    }
    avatarLoadedHook() {}
    avatarStartMovingHook() {}
    avatarStopMovingHook() {}
    async statusSync(i) {
        var o, s, c;
        try {
            if ((o = i.event) != null && o.rotateEvent) {
                const {angle: d, speed: _} = i.event.rotateEvent
                  , b = this.motionType === MotionType.Run ? "Running" : "Walking";
                this.rotation && (this.rotation.yaw = this.rotation.yaw % 360,
                d.yaw - this.rotation.yaw > 180 && (d.yaw = 180 - d.yaw),
                this.isRotating = !0,
                await this.xAvatar.rotateTo(d, this.rotation, b).then(()=>{
                    this._playAnimation("Idle", !0),
                    this.isRotating = !1
                }
                ))
            }
            if (i.event && (((s = i.event) == null ? void 0 : s.points.length) || 0) > 1 && !this.isSelf) {
                this.isMoving = !0,
                i.playerState.attitude && (this._motionType = i.playerState.attitude);
                const d = this.motionType === MotionType.Run ? "Running" : "Walking"
                  , _ = this._room.skin.routeList.find(k=>k.areaName === this.currentPathName)
                  , b = ((_ == null ? void 0 : _.step) || 7.5) * 30 * (25 / 30);
                this.position && await this._move({
                    start: this.position,
                    end: i.event.points[i.event.points.length - 1],
                    walkSpeed: b,
                    moveAnimation: d,
                    inter: (c = i.event) == null ? void 0 : c.points.slice(0, -1)
                }).then(()=>{
                    this.isMoving = !1
                }
                )
            }
        } catch {
            return
        }
    }
    removeAttachedEffects() {
        this.attachedEffects.forEach((i,o)=>{
            this._room.effectManager.removeEffect(o)
        }
        ),
        this.attachedEffects.clear()
    }
    removeAttachedEffect(i) {
        this.attachedEffects.delete(i),
        this._room.effectManager.removeEffect(i)
    }
    faceTo({point: i, rotateSpeed: o=.1}) {
        return this.xAvatar.faceTo(i, o)
    }
}
var SyncEventType = (a=>(a[a.Reset = 0] = "Reset",
a[a.Appear = 1] = "Appear",
a[a.Disappear = 2] = "Disappear",
a[a.Move = 3] = "Move",
a[a.ChangeRenderInfo = 4] = "ChangeRenderInfo",
a[a.KeepAlive = 5] = "KeepAlive",
a[a.Rotate = 6] = "Rotate",
a[a.ET_RemoveVisitor = 7] = "ET_RemoveVisitor",
a))(SyncEventType || {});
const log = new Logger("xverse-avatar-manager")
  , pr = class {
    constructor(e) {
        Tt(this, "xAvatarManager");
        Tt(this, "_room");
        Tt(this, "avatars", new Map);
        Tt(this, "syncAvatarsLength", 0);
        Tt(this, "broadcast");
        this._room = e,
        this._usersStatistics(),
        this.broadcast = this.setupBroadcast(),
        e.on("skinChanged", ()=>{
            this.avatars.forEach(i=>{
                i.disconnected && this.removeAvatar(i.userId, !0)
            }
            )
        }
        )
    }
    setupBroadcast() {
        return new Broadcast(this._room,async e=>{
            const {broadcastType: i, info: o} = e;
            if (i !== CoreBroadcastType.PlayAnimation)
                return;
            const {userId: s, animation: c, extra: d, loop: _=!1} = o
              , b = this.avatars.get(s);
            b && !b.isSelf && (b.emit("animationStart", {
                animationName: c,
                extra: decodeURIComponent(d)
            }),
            await (b == null ? void 0 : b._playAnimation(c, _)),
            b.emit("animationEnd", {
                animationName: c,
                extra: decodeURIComponent(d)
            }))
        }
        )
    }
    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: i} = e;
            if (i) {
                await avatarLoader.parse(this._room.sceneManager, i);
                return
            }
            return Promise.reject("cannot find avatar config list")
        } catch (e) {
            return log.error(e),
            Promise.reject("avatar mananger init error!" + e)
        }
    }
    async handleAvatar(e) {
        if (this._room.viewMode === "simple" || !this._room.joined || !e.newUserStates)
            return;
        const i = e.newUserStates;
        if (e.actionType === Actions.GetNewUserState) {
            this.syncAvatarsLength = (i || []).length;
            const o = this._room.avatars.filter(d=>d.group == AvatarGroup.User);
            o.filter(d=>!(i != null && i.find(_=>_.userId == d.userId))).forEach(d=>{
                this.removeAvatar(d.userId)
            }
            );
            const c = i.filter(d=>!o.find(_=>_.userId == d.userId));
            this._handleAvatar(c)
        } else
            this._handleAvatar(i)
    }
    async _handleAvatar(e) {
        e == null || e.forEach(i=>{
            var s, c, d, _, b, k, j, $, _e;
            const o = this._room.userId === i.userId;
            if (((s = i.event) == null ? void 0 : s.type) === SyncEventType.ET_RemoveVisitor) {
                const et = (d = (c = i.event) == null ? void 0 : c.removeVisitorEvent) == null ? void 0 : d.removeVisitorEvent
                  , tt = JSON.parse(safeDecodeURIComponent(((b = (_ = i.event) == null ? void 0 : _.removeVisitorEvent) == null ? void 0 : b.extraInfo) || ""))
                  , {code: rt, msg: it} = tt;
                et === RemoveVisitorType.RVT_ChangeToObserver ? this._room.audienceViewModeHook(tt) : et === RemoveVisitorType.RVT_MoveOutOfTheRoom && this._room.leave(),
                this._room.proxyEvents("kicked", {
                    code: rt,
                    msg: it
                }),
                log.warn("kicked emit: ", {
                    code: rt,
                    msg: it
                })
            }
            if (i.event && [SyncEventType.Appear, SyncEventType.Reset].includes(i.event.type)) {
                let et = this.avatars.get(i.userId);
                if (et && i.playerState.avatarId && (et == null ? void 0 : et.avatarId) !== i.playerState.avatarId && (et = void 0,
                this.removeAvatar(i.userId, !0)),
                et) {
                    if (i.playerState.pathName && (et.currentPathName = i.playerState.pathName),
                    et.disconnected && et.setConnectionStatus(!1),
                    (k = i.event) != null && k.id && this._room.actionsHandler.confirmEvent(i.event.id),
                    i.playerState.nickName && (et == null || et._setNickname(i.playerState.nickName)),
                    i.playerState.avatarComponents && !et.isSelf && et.xAvatar) {
                        const tt = safeParseComponents(i.playerState.avatarComponents);
                        et._changeComponents({
                            avatarComponents: tt,
                            mode: ChangeComponentsMode.Preview
                        })
                    }
                    if (!et.isSelf && et.position && (et.statusSyncQueue.queue.length === 0 || !et.statusSyncQueue.currentAction)) {
                        const {x: tt, y: rt} = et.position
                          , {x: it, y: nt} = i.playerState.player.position;
                        (Math.abs(tt - it) > 50 || Math.abs(rt - nt) > 50) && (et.setPosition(i.playerState.player.position),
                        et.setRotation(i.playerState.player.angle))
                    }
                } else {
                    if (!i.playerState.player)
                        return;
                    const {position: tt, angle: rt} = i.playerState.player
                      , it = i.playerState.avatarId
                      , nt = i.playerState.prioritySync
                      , ot = safelyJsonParse(i.playerState.extra)
                      , at = safeParseComponents(i.playerState.avatarComponents)
                      , st = safeDecodeURIComponent(i.playerState.nickName)
                      , ut = this.calculatePriority(i.userId, ot);
                    this.addAvatar({
                        userId: i.userId,
                        isHost: i.playerState.isHost,
                        nickname: st,
                        avatarPosition: tt,
                        avatarRotation: rt,
                        avatarScale: i.playerState.avatarSize,
                        avatarId: it,
                        avatarComponents: i.playerState.person === Person.First ? [] : at,
                        priority: ut,
                        group: AvatarGroup.User,
                        prioritySync: nt,
                        extraInfo: ot
                    }).then(ct=>{
                        var lt;
                        i.playerState.pathName && (ct.currentPathName = i.playerState.pathName),
                        (lt = i.event) != null && lt.id && this._room.actionsHandler.confirmEvent(i.event.id),
                        this.updateAvatarPositionAndRotation(i),
                        o && (this.xAvatarManager.setMainAvatar(i.userId),
                        this._room.emit("userAvatarLoaded"),
                        log.info("userAvatarLoaded"))
                    }
                    ).catch(ct=>{
                        o && (this.xAvatarManager.setMainAvatar(i.userId),
                        this._room.emit("userAvatarFailed", {
                            error: ct
                        }),
                        log.error("userAvatarFailed", ct))
                    }
                    )
                }
            }
            if (i.event && SyncEventType.Disappear === i.event.type && ((j = i == null ? void 0 : i.event) != null && j.id && this._room.actionsHandler.confirmEvent(i.event.id),
            this.removeAvatar(i.userId)),
            i.event && [SyncEventType.Move, SyncEventType.ChangeRenderInfo].includes(i.event.type) || !i.event) {
                ($ = i == null ? void 0 : i.event) != null && $.id && this._room.actionsHandler.confirmEvent(i.event.id);
                const et = this.avatars.get(i.userId);
                et && et.withModel && !et.isLoading && this.updateAvatarPositionAndRotation(i)
            }
            if (!o && ((_e = i.event) == null ? void 0 : _e.type) === SyncEventType.Rotate) {
                const et = this.avatars.get(i.userId);
                et.statusSyncQueue.append({
                    type: QueueType.Rotate,
                    action: ()=>et.statusSync(i)
                })
            }
        }
        )
    }
    calculatePriority(e, i) {
        var s;
        return e === this._room.userId ? EAvatarRelationRank.Self : (s = this._room.options.firends) != null && s.includes(e) ? EAvatarRelationRank.Friend : EAvatarRelationRank.Stranger
    }
    updateAvatarPositionAndRotation(e) {
        var i, o;
        if ((i = e == null ? void 0 : e.playerState) != null && i.player) {
            let {position: s, angle: c} = e.playerState.player;
            const d = this.avatars.get(e.userId);
            if (!d)
                return;
            if (s = positionPrecisionProtect(s),
            c = rotationPrecisionProtect(c),
            d.isSelf && !this._room.networkController.rtcp.workers.inPanoMode && (d.setPosition(s),
            d.setRotation(c)),
            e.event && (((o = e.event) == null ? void 0 : o.points.length) || 0) > 1 && !d.isSelf && d.statusSyncQueue.append({
                type: QueueType.Move,
                action: ()=>d.statusSync(e)
            }),
            e.renderInfo && d.isSelf) {
                const {isMoving: _, isRotating: b} = e.renderInfo;
                this._updateAvatarMovingStatus({
                    id: e.userId,
                    isMoving: !!_,
                    isRotating: !!b
                })
            }
        }
    }
    async addAvatar(e) {
        const {userId: i, isHost: o, avatarPosition: s, avatarId: c, avatarRotation: d, nickname: _, avatarComponents: b=[], priority: k, group: j=AvatarGroup.Npc, avatarScale: $=DEFAULT_AVATAR_SCALE, extraInfo: _e, prioritySync: et} = e
          , tt = i === this._room.userId;
        let rt = this.avatars.get(i);
        if (rt)
            return Promise.resolve(rt);
        if (rt = new pr.subAvatar({
            userId: i,
            isHost: o,
            isSelf: tt,
            room: this._room,
            avatarComponents: b,
            avatarId: c,
            nickname: _,
            group: j
        }),
        this.avatars.set(i, rt),
        !rt.withModel)
            return rt.isLoading = !1,
            rt.avatarLoadedHook(),
            this._room.emit("avatarChanged", {
                avatars: this._room.avatars
            }),
            rt;
        const nt = (await this._room.modelManager.getAvatarModelList()).find(at=>at.id === c)
          , ot = Date.now();
        if (!nt)
            return this._room.emit("avatarChanged", {
                avatars: this._room.avatars
            }),
            this.avatars.delete(i),
            Promise.reject(`no such avatar model with id: ${c}`);
        try {
            let at = await avatarComponentsModify(nt, b);
            at = at.filter(ct=>ct.type != "pendant");
            const st = await avatarComponentsParser(nt, at)
              , ut = await this.xAvatarManager.loadAvatar({
                id: i,
                avatarType: c,
                priority: k,
                avatarManager: this.xAvatarManager,
                assets: st,
                status: {
                    avatarPosition: s,
                    avatarRotation: d,
                    avatarScale: $
                }
            })._timeout(8e3, new TimeoutError$1("loadAvatar timeout(8s)"));
            return ut.setPickBoxScale(i === this._room.userId ? 0 : 1),
            rt.xAvatar = ut,
            rt.setScale($),
            s && rt.setPosition(s),
            rt.extraInfo = _e,
            rt.priority = k,
            rt.isLoading = !1,
            rt.prioritySync = !!et,
            rt._playAnimation("Idle", !0, !0),
            rt.avatarLoadedHook(),
            this._room.emit("avatarChanged", {
                avatars: this._room.avatars
            }),
            _ && rt._setNickname(_),
            i === this._room.userId && (log.infoAndReportMeasurement({
                metric: "avatarLoadDuration",
                startTime: ot,
                group: "costs"
            }),
            log.infoAndReportMeasurement({
                metric: "avatarLoadAt",
                startTime: this._room._startTime,
                group: "costs"
            })),
            rt
        } catch (at) {
            return rt.isLoading = !1,
            this._room.emit("avatarChanged", {
                avatars: this._room.avatars
            }),
            log.error(at),
            Promise.reject(at)
        }
    }
    removeAvatar(e, i=!1) {
        const o = this.avatars.get(e);
        if (!!o) {
            if (o.removeWhenDisconnected || i) {
                o.removeAttachedEffects(),
                o.xAvatar && this.xAvatarManager.deleteAvatar(o.xAvatar),
                this.avatars.delete(e),
                this._room.emit("avatarChanged", {
                    avatars: this._room.avatars
                });
                return
            }
            o.setConnectionStatus(!0)
        }
    }
    clearOtherUsers() {
        this.avatars.forEach(e=>{
            !e.isSelf && e.group === AvatarGroup.User && this.removeAvatar(e.userId)
        }
        )
    }
    async _updateAvatarMovingStatus(e) {
        var d, _;
        const {id: i, isMoving: o, isRotating: s} = e
          , c = this.avatars.get(i);
        if (!!c) {
            if (c.isRotating !== s) {
                c.isRotating = s;
                let b = "Idle";
                s && (b = "Walking",
                c.motionType === MotionType.Run && (b = "Running")),
                c._playAnimation(b, !0, !0),
                log.infoAndReportMeasurement({
                    startTime: Date.now(),
                    value: 0,
                    metric: s ? "userAvatarStartRotating" : "userAvatarStopRotating",
                    extra: {
                        motionType: c.motionType,
                        moveToExtra: this._room.moveToExtra
                    }
                })
            }
            if (c.isMoving !== o) {
                c.isMoving = o;
                let b = "Idle";
                o && (b = "Walking",
                c.motionType === MotionType.Run && (b = "Running")),
                o ? (c.avatarStartMovingHook(),
                c.isSelf && (log.warn("startMoving emit", this._room.moveToExtra),
                c.emit("startMoving", {
                    target: c,
                    extra: this._room.moveToExtra
                }))) : (c.avatarStopMovingHook(),
                c.isSelf && (log.warn("stopMoving emit", this._room.moveToExtra),
                c.emit("stopMoving", {
                    target: c,
                    extra: this._room.moveToExtra
                }))),
                c._playAnimation(b, !0, !0),
                log.infoAndReportMeasurement({
                    startTime: Date.now(),
                    value: 0,
                    metric: o ? "userAvatarStartMoving" : "userAvatarStopMoving",
                    extra: {
                        motionType: c.motionType,
                        moveToExtra: this._room.moveToExtra
                    }
                })
            }
            if (o && ((_ = (d = c.xAvatar) == null ? void 0 : d.controller) == null ? void 0 : _.onPlay) === "Idle") {
                let b = "Walking";
                c.motionType === MotionType.Run && (b = "Running"),
                log.error("force avoiding slide step"),
                c._playAnimation(b, !0, !0)
            }
        }
    }
    _usersStatistics() {
        this._room.on("userAvatarLoaded", ()=>{
            window.setInterval(()=>{
                const e = this._room.avatars.filter(o=>o.group === AvatarGroup.User).length || 0
                  , i = this._room.avatars.filter(o=>o.group === AvatarGroup.User && o.isRender).length || 0;
                this._room.stats.assign({
                    userNum: e,
                    syncUserNum: this.syncAvatarsLength,
                    renderedUserNum: i
                })
            }
            , 3e3)
        }
        )
    }
}
;
let XverseAvatarManager = pr;
Tt(XverseAvatarManager, "subAvatar", XverseAvatar);
new Logger("Wsutils");
function downloadFileByBase64(a, e) {
    const i = dataURLtoBlob(a)
      , o = URL.createObjectURL(i);
    downloadFile(o, e)
}
function dataURLtoBlob(a) {
    var d;
    const e = a.split(",")
      , i = (d = e[0].match(/:(.*?);/)) == null ? void 0 : d[1]
      , o = atob(e[1]);
    let s = o.length;
    const c = new Uint8Array(s);
    for (; s--; )
        c[s] = o.charCodeAt(s);
    return new Blob([c],{
        type: i
    })
}
function downloadFile(a, e="screenShot.png") {
    const i = document.createElement("a");
    i.setAttribute("href", a),
    i.setAttribute("download", e),
    i.setAttribute("target", "_blank");
    const o = document.createEvent("MouseEvents");
    o.initEvent("click", !0, !0),
    i.dispatchEvent(o)
}
const distance = (a,e)=>{
    const i = e.x - a.x
      , o = e.y - a.y;
    return Math.sqrt(i * i + o * o)
}
  , angle = (a,e)=>{
    const i = e.x - a.x
      , o = e.y - a.y;
    return degrees(Math.atan2(o, i))
}
  , findCoord = (a,e,i)=>{
    const o = {
        x: 0,
        y: 0
    };
    return i = radians(i),
    o.x = a.x - e * Math.cos(i),
    o.y = a.y - e * Math.sin(i),
    o
}
  , radians = a=>a * (Math.PI / 180)
  , degrees = a=>a * (180 / Math.PI)
  , isPressed = a=>isNaN(a.buttons) ? a.pressure !== 0 : a.buttons !== 0
  , timers = new Map
  , throttle = a=>{
    timers.has(a) && clearTimeout(timers.get(a)),
    timers.set(a, setTimeout(a, 100))
}
  , bindEvt = (a,e,i)=>{
    const o = e.split(/[ ,]+/g);
    let s;
    for (let c = 0; c < o.length; c += 1)
        s = o[c],
        a.addEventListener ? a.addEventListener(s, i, !1) : a.attachEvent && a.attachEvent(s, i)
}
  , unbindEvt = (a,e,i)=>{
    const o = e.split(/[ ,]+/g);
    let s;
    for (let c = 0; c < o.length; c += 1)
        s = o[c],
        a.removeEventListener ? a.removeEventListener(s, i) : a.detachEvent && a.detachEvent(s, i)
}
  , prepareEvent = a=>(a.preventDefault(),
a.type.match(/^touch/) ? a.changedTouches : a)
  , getScroll = ()=>{
    const a = window.pageXOffset !== void 0 ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft
      , e = window.pageYOffset !== void 0 ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    return {
        x: a,
        y: e
    }
}
  , applyPosition = (a,e)=>{
    e.top || e.right || e.bottom || e.left ? (a.style.top = e.top,
    a.style.right = e.right,
    a.style.bottom = e.bottom,
    a.style.left = e.left) : (a.style.left = e.x + "px",
    a.style.top = e.y + "px")
}
  , getTransitionStyle = (a,e,i)=>{
    const o = configStylePropertyObject(a);
    for (let s in o)
        if (o.hasOwnProperty(s))
            if (typeof e == "string")
                o[s] = e + " " + i;
            else {
                let c = "";
                for (let d = 0, _ = e.length; d < _; d += 1)
                    c += e[d] + " " + i + ", ";
                o[s] = c.slice(0, -2)
            }
    return o
}
  , getVendorStyle = (a,e)=>{
    const i = configStylePropertyObject(a);
    for (let o in i)
        i.hasOwnProperty(o) && (i[o] = e);
    return i
}
  , configStylePropertyObject = a=>{
    const e = {};
    return e[a] = "",
    ["webkit", "Moz", "o"].forEach(function(o) {
        e[o + a.charAt(0).toUpperCase() + a.slice(1)] = ""
    }),
    e
}
  , extend = (a,e)=>{
    for (let i in e)
        e.hasOwnProperty(i) && (a[i] = e[i]);
    return a
}
  , safeExtend = (a,e)=>{
    const i = {};
    for (let o in a)
        a.hasOwnProperty(o) && e.hasOwnProperty(o) ? i[o] = e[o] : a.hasOwnProperty(o) && (i[o] = a[o]);
    return i
}
  , map = (a,e)=>{
    if (a.length)
        for (let i = 0, o = a.length; i < o; i += 1)
            e(a[i]);
    else
        e(a)
}
  , clamp = (a,e,i)=>({
    x: Math.min(Math.max(a.x, e.x - i), e.x + i),
    y: Math.min(Math.max(a.y, e.y - i), e.y + i)
});
var isTouch = "ontouchstart"in window, isPointer = !!window.PointerEvent, isMSPointer = !!window.MSPointerEvent, events = {
    touch: {
        start: "touchstart",
        move: "touchmove",
        end: "touchend, touchcancel"
    },
    mouse: {
        start: "mousedown",
        move: "mousemove",
        end: "mouseup"
    },
    pointer: {
        start: "pointerdown",
        move: "pointermove",
        end: "pointerup, pointercancel"
    },
    MSPointer: {
        start: "MSPointerDown",
        move: "MSPointerMove",
        end: "MSPointerUp"
    }
}, toBind, secondBind = {};
isPointer ? toBind = events.pointer : isMSPointer ? toBind = events.MSPointer : isTouch ? (toBind = events.touch,
secondBind = events.mouse) : toBind = events.mouse;
function Super() {}
Super.prototype.on = function(a, e) {
    var i = this, o = a.split(/[ ,]+/g), s;
    i._handlers_ = i._handlers_ || {};
    for (var c = 0; c < o.length; c += 1)
        s = o[c],
        i._handlers_[s] = i._handlers_[s] || [],
        i._handlers_[s].push(e);
    return i
}
;
Super.prototype.off = function(a, e) {
    var i = this;
    return i._handlers_ = i._handlers_ || {},
    a === void 0 ? i._handlers_ = {} : e === void 0 ? i._handlers_[a] = null : i._handlers_[a] && i._handlers_[a].indexOf(e) >= 0 && i._handlers_[a].splice(i._handlers_[a].indexOf(e), 1),
    i
}
;
Super.prototype.trigger = function(a, e) {
    var i = this, o = a.split(/[ ,]+/g), s;
    i._handlers_ = i._handlers_ || {};
    for (var c = 0; c < o.length; c += 1)
        s = o[c],
        i._handlers_[s] && i._handlers_[s].length && i._handlers_[s].forEach(function(d) {
            d.call(i, {
                type: s,
                target: i
            }, e)
        })
}
;
Super.prototype.config = function(a) {
    var e = this;
    e.options = e.defaults || {},
    a && (e.options = safeExtend(e.options, a))
}
;
Super.prototype.bindEvt = function(a, e) {
    var i = this;
    return i._domHandlers_ = i._domHandlers_ || {},
    i._domHandlers_[e] = function() {
        typeof i["on" + e] == "function" ? i["on" + e].apply(i, arguments) : console.warn('[WARNING] : Missing "on' + e + '" handler.')
    }
    ,
    bindEvt(a, toBind[e], i._domHandlers_[e]),
    secondBind[e] && bindEvt(a, secondBind[e], i._domHandlers_[e]),
    i
}
;
Super.prototype.unbindEvt = function(a, e) {
    var i = this;
    return i._domHandlers_ = i._domHandlers_ || {},
    unbindEvt(a, toBind[e], i._domHandlers_[e]),
    secondBind[e] && unbindEvt(a, secondBind[e], i._domHandlers_[e]),
    delete i._domHandlers_[e],
    this
}
;
function Nipple(a, e) {
    return this.identifier = e.identifier,
    this.position = e.position,
    this.frontPosition = e.frontPosition,
    this.collection = a,
    this.defaults = {
        size: 100,
        threshold: .1,
        color: "white",
        fadeTime: 250,
        dataOnly: !1,
        restJoystick: !0,
        restOpacity: .5,
        mode: "dynamic",
        zone: document.body,
        lockX: !1,
        lockY: !1,
        shape: "circle"
    },
    this.config(e),
    this.options.mode === "dynamic" && (this.options.restOpacity = 0),
    this.id = Nipple.id,
    Nipple.id += 1,
    this.buildEl().stylize(),
    this.instance = {
        el: this.ui.el,
        on: this.on.bind(this),
        off: this.off.bind(this),
        show: this.show.bind(this),
        hide: this.hide.bind(this),
        add: this.addToDom.bind(this),
        remove: this.removeFromDom.bind(this),
        destroy: this.destroy.bind(this),
        setPosition: this.setPosition.bind(this),
        resetDirection: this.resetDirection.bind(this),
        computeDirection: this.computeDirection.bind(this),
        trigger: this.trigger.bind(this),
        position: this.position,
        frontPosition: this.frontPosition,
        ui: this.ui,
        identifier: this.identifier,
        id: this.id,
        options: this.options
    },
    this.instance
}
Nipple.prototype = new Super;
Nipple.constructor = Nipple;
Nipple.id = 0;
Nipple.prototype.buildEl = function(a) {
    return this.ui = {},
    this.options.dataOnly ? this : (this.ui.el = document.createElement("div"),
    this.ui.back = document.createElement("div"),
    this.ui.front = document.createElement("div"),
    this.ui.el.className = "nipple collection_" + this.collection.id,
    this.ui.back.className = "back",
    this.ui.front.className = "front",
    this.ui.el.setAttribute("id", "nipple_" + this.collection.id + "_" + this.id),
    this.ui.el.appendChild(this.ui.back),
    this.ui.el.appendChild(this.ui.front),
    this)
}
;
Nipple.prototype.stylize = function() {
    if (this.options.dataOnly)
        return this;
    var a = this.options.fadeTime + "ms"
      , e = getVendorStyle("borderRadius", "50%")
      , i = getTransitionStyle("transition", "opacity", a)
      , o = {};
    return o.el = {
        position: "absolute",
        opacity: this.options.restOpacity,
        display: "block",
        zIndex: 999
    },
    o.back = {
        position: "absolute",
        display: "block",
        width: this.options.size + "px",
        height: this.options.size + "px",
        marginLeft: -this.options.size / 2 + "px",
        marginTop: -this.options.size / 2 + "px",
        background: this.options.color,
        opacity: ".5"
    },
    o.front = {
        width: this.options.size / 2 + "px",
        height: this.options.size / 2 + "px",
        position: "absolute",
        display: "block",
        marginLeft: -this.options.size / 4 + "px",
        marginTop: -this.options.size / 4 + "px",
        background: this.options.color,
        opacity: ".5"
    },
    extend(o.el, i),
    this.options.shape === "circle" && extend(o.back, e),
    extend(o.front, e),
    this.applyStyles(o),
    this
}
;
Nipple.prototype.applyStyles = function(a) {
    for (var e in this.ui)
        if (this.ui.hasOwnProperty(e))
            for (var i in a[e])
                this.ui[e].style[i] = a[e][i];
    return this
}
;
Nipple.prototype.addToDom = function() {
    return this.options.dataOnly || document.body.contains(this.ui.el) ? this : (this.options.zone.appendChild(this.ui.el),
    this)
}
;
Nipple.prototype.removeFromDom = function() {
    return this.options.dataOnly || !document.body.contains(this.ui.el) ? this : (this.options.zone.removeChild(this.ui.el),
    this)
}
;
Nipple.prototype.destroy = function() {
    clearTimeout(this.removeTimeout),
    clearTimeout(this.showTimeout),
    clearTimeout(this.restTimeout),
    this.trigger("destroyed", this.instance),
    this.removeFromDom(),
    this.off()
}
;
Nipple.prototype.show = function(a) {
    var e = this;
    return e.options.dataOnly || (clearTimeout(e.removeTimeout),
    clearTimeout(e.showTimeout),
    clearTimeout(e.restTimeout),
    e.addToDom(),
    e.restCallback(),
    setTimeout(function() {
        e.ui.el.style.opacity = 1
    }, 0),
    e.showTimeout = setTimeout(function() {
        e.trigger("shown", e.instance),
        typeof a == "function" && a.call(this)
    }, e.options.fadeTime)),
    e
}
;
Nipple.prototype.hide = function(a) {
    var e = this;
    if (e.options.dataOnly)
        return e;
    if (e.ui.el.style.opacity = e.options.restOpacity,
    clearTimeout(e.removeTimeout),
    clearTimeout(e.showTimeout),
    clearTimeout(e.restTimeout),
    e.removeTimeout = setTimeout(function() {
        var i = e.options.mode === "dynamic" ? "none" : "block";
        e.ui.el.style.display = i,
        typeof a == "function" && a.call(e),
        e.trigger("hidden", e.instance)
    }, e.options.fadeTime),
    e.options.restJoystick) {
        const i = e.options.restJoystick
          , o = {};
        o.x = i === !0 || i.x !== !1 ? 0 : e.instance.frontPosition.x,
        o.y = i === !0 || i.y !== !1 ? 0 : e.instance.frontPosition.y,
        e.setPosition(a, o)
    }
    return e
}
;
Nipple.prototype.setPosition = function(a, e) {
    var i = this;
    i.frontPosition = {
        x: e.x,
        y: e.y
    };
    var o = i.options.fadeTime + "ms"
      , s = {};
    s.front = getTransitionStyle("transition", ["top", "left"], o);
    var c = {
        front: {}
    };
    c.front = {
        left: i.frontPosition.x + "px",
        top: i.frontPosition.y + "px"
    },
    i.applyStyles(s),
    i.applyStyles(c),
    i.restTimeout = setTimeout(function() {
        typeof a == "function" && a.call(i),
        i.restCallback()
    }, i.options.fadeTime)
}
;
Nipple.prototype.restCallback = function() {
    var a = this
      , e = {};
    e.front = getTransitionStyle("transition", "none", ""),
    a.applyStyles(e),
    a.trigger("rested", a.instance)
}
;
Nipple.prototype.resetDirection = function() {
    this.direction = {
        x: !1,
        y: !1,
        angle: !1
    }
}
;
Nipple.prototype.computeDirection = function(a) {
    var e = a.angle.radian, i = Math.PI / 4, o = Math.PI / 2, s, c, d;
    if (e > i && e < i * 3 && !a.lockX ? s = "up" : e > -i && e <= i && !a.lockY ? s = "left" : e > -i * 3 && e <= -i && !a.lockX ? s = "down" : a.lockY || (s = "right"),
    a.lockY || (e > -o && e < o ? c = "left" : c = "right"),
    a.lockX || (e > 0 ? d = "up" : d = "down"),
    a.force > this.options.threshold) {
        var _ = {}, b;
        for (b in this.direction)
            this.direction.hasOwnProperty(b) && (_[b] = this.direction[b]);
        var k = {};
        this.direction = {
            x: c,
            y: d,
            angle: s
        },
        a.direction = this.direction;
        for (b in _)
            _[b] === this.direction[b] && (k[b] = !0);
        if (k.x && k.y && k.angle)
            return a;
        (!k.x || !k.y) && this.trigger("plain", a),
        k.x || this.trigger("plain:" + c, a),
        k.y || this.trigger("plain:" + d, a),
        k.angle || this.trigger("dir dir:" + s, a)
    } else
        this.resetDirection();
    return a
}
;
function Collection(a, e) {
    var i = this;
    i.nipples = [],
    i.idles = [],
    i.actives = [],
    i.ids = [],
    i.pressureIntervals = {},
    i.manager = a,
    i.id = Collection.id,
    Collection.id += 1,
    i.defaults = {
        zone: document.body,
        multitouch: !1,
        maxNumberOfNipples: 10,
        mode: "dynamic",
        position: {
            top: 0,
            left: 0
        },
        catchDistance: 200,
        size: 100,
        threshold: .1,
        color: "white",
        fadeTime: 250,
        dataOnly: !1,
        restJoystick: !0,
        restOpacity: .5,
        lockX: !1,
        lockY: !1,
        shape: "circle",
        dynamicPage: !1,
        follow: !1
    },
    i.config(e),
    (i.options.mode === "static" || i.options.mode === "semi") && (i.options.multitouch = !1),
    i.options.multitouch || (i.options.maxNumberOfNipples = 1);
    const o = getComputedStyle(i.options.zone.parentElement);
    return o && o.display === "flex" && (i.parentIsFlex = !0),
    i.updateBox(),
    i.prepareNipples(),
    i.bindings(),
    i.begin(),
    i.nipples
}
Collection.prototype = new Super;
Collection.constructor = Collection;
Collection.id = 0;
Collection.prototype.prepareNipples = function() {
    var a = this
      , e = a.nipples;
    e.on = a.on.bind(a),
    e.off = a.off.bind(a),
    e.options = a.options,
    e.destroy = a.destroy.bind(a),
    e.ids = a.ids,
    e.id = a.id,
    e.processOnMove = a.processOnMove.bind(a),
    e.processOnEnd = a.processOnEnd.bind(a),
    e.get = function(i) {
        if (i === void 0)
            return e[0];
        for (var o = 0, s = e.length; o < s; o += 1)
            if (e[o].identifier === i)
                return e[o];
        return !1
    }
}
;
Collection.prototype.bindings = function() {
    var a = this;
    a.bindEvt(a.options.zone, "start"),
    a.options.zone.style.touchAction = "none",
    a.options.zone.style.msTouchAction = "none"
}
;
Collection.prototype.begin = function() {
    var a = this
      , e = a.options;
    if (e.mode === "static") {
        var i = a.createNipple(e.position, a.manager.getIdentifier());
        i.add(),
        a.idles.push(i)
    }
}
;
Collection.prototype.createNipple = function(a, e) {
    var i = this
      , o = i.manager.scroll
      , s = {}
      , c = i.options
      , d = {
        x: i.parentIsFlex ? o.x : o.x + i.box.left,
        y: i.parentIsFlex ? o.y : o.y + i.box.top
    };
    if (a.x && a.y)
        s = {
            x: a.x - d.x,
            y: a.y - d.y
        };
    else if (a.top || a.right || a.bottom || a.left) {
        var _ = document.createElement("DIV");
        _.style.display = "hidden",
        _.style.top = a.top,
        _.style.right = a.right,
        _.style.bottom = a.bottom,
        _.style.left = a.left,
        _.style.position = "absolute",
        c.zone.appendChild(_);
        var b = _.getBoundingClientRect();
        c.zone.removeChild(_),
        s = a,
        a = {
            x: b.left + o.x,
            y: b.top + o.y
        }
    }
    var k = new Nipple(i,{
        color: c.color,
        size: c.size,
        threshold: c.threshold,
        fadeTime: c.fadeTime,
        dataOnly: c.dataOnly,
        restJoystick: c.restJoystick,
        restOpacity: c.restOpacity,
        mode: c.mode,
        identifier: e,
        position: a,
        zone: c.zone,
        frontPosition: {
            x: 0,
            y: 0
        },
        shape: c.shape
    });
    return c.dataOnly || (applyPosition(k.ui.el, s),
    applyPosition(k.ui.front, k.frontPosition)),
    i.nipples.push(k),
    i.trigger("added " + k.identifier + ":added", k),
    i.manager.trigger("added " + k.identifier + ":added", k),
    i.bindNipple(k),
    k
}
;
Collection.prototype.updateBox = function() {
    var a = this;
    a.box = a.options.zone.getBoundingClientRect()
}
;
Collection.prototype.bindNipple = function(a) {
    var e = this, i, o = function(s, c) {
        i = s.type + " " + c.id + ":" + s.type,
        e.trigger(i, c)
    };
    a.on("destroyed", e.onDestroyed.bind(e)),
    a.on("shown hidden rested dir plain", o),
    a.on("dir:up dir:right dir:down dir:left", o),
    a.on("plain:up plain:right plain:down plain:left", o)
}
;
Collection.prototype.pressureFn = function(a, e, i) {
    var o = this
      , s = 0;
    clearInterval(o.pressureIntervals[i]),
    o.pressureIntervals[i] = setInterval(function() {
        var c = a.force || a.pressure || a.webkitForce || 0;
        c !== s && (e.trigger("pressure", c),
        o.trigger("pressure " + e.identifier + ":pressure", c),
        s = c)
    }
    .bind(o), 100)
}
;
Collection.prototype.onstart = function(a) {
    var e = this
      , i = e.options
      , o = a;
    a = prepareEvent(a),
    e.updateBox();
    var s = function(c) {
        e.actives.length < i.maxNumberOfNipples ? e.processOnStart(c) : o.type.match(/^touch/) && (Object.keys(e.manager.ids).forEach(function(d) {
            if (Object.values(o.touches).findIndex(function(b) {
                return b.identifier === d
            }) < 0) {
                var _ = [a[0]];
                _.identifier = d,
                e.processOnEnd(_)
            }
        }),
        e.actives.length < i.maxNumberOfNipples && e.processOnStart(c))
    };
    return map(a, s),
    e.manager.bindDocument(),
    !1
}
;
Collection.prototype.processOnStart = function(a) {
    var e = this, i = e.options, o, s = e.manager.getIdentifier(a), c = a.force || a.pressure || a.webkitForce || 0, d = {
        x: a.pageX,
        y: a.pageY
    }, _ = e.getOrCreate(s, d);
    _.identifier !== s && e.manager.removeIdentifier(_.identifier),
    _.identifier = s;
    var b = function(j) {
        j.trigger("start", j),
        e.trigger("start " + j.id + ":start", j),
        j.show(),
        c > 0 && e.pressureFn(a, j, j.identifier),
        e.processOnMove(a)
    };
    if ((o = e.idles.indexOf(_)) >= 0 && e.idles.splice(o, 1),
    e.actives.push(_),
    e.ids.push(_.identifier),
    i.mode !== "semi")
        b(_);
    else {
        var k = distance(d, _.position);
        if (k <= i.catchDistance)
            b(_);
        else {
            _.destroy(),
            e.processOnStart(a);
            return
        }
    }
    return _
}
;
Collection.prototype.getOrCreate = function(a, e) {
    var i = this, o = i.options, s;
    return /(semi|static)/.test(o.mode) ? (s = i.idles[0],
    s ? (i.idles.splice(0, 1),
    s) : o.mode === "semi" ? i.createNipple(e, a) : (console.warn("Coudln't find the needed nipple."),
    !1)) : (s = i.createNipple(e, a),
    s)
}
;
Collection.prototype.processOnMove = function(a) {
    var e = this
      , i = e.options
      , o = e.manager.getIdentifier(a)
      , s = e.nipples.get(o)
      , c = e.manager.scroll;
    if (!isPressed(a)) {
        this.processOnEnd(a);
        return
    }
    if (!s) {
        console.error("Found zombie joystick with ID " + o),
        e.manager.removeIdentifier(o);
        return
    }
    if (i.dynamicPage) {
        var d = s.el.getBoundingClientRect();
        s.position = {
            x: c.x + d.left,
            y: c.y + d.top
        }
    }
    s.identifier = o;
    var _ = s.options.size / 2
      , b = {
        x: a.pageX,
        y: a.pageY
    };
    i.lockX && (b.y = s.position.y),
    i.lockY && (b.x = s.position.x);
    var k = distance(b, s.position), j = angle(b, s.position), $ = radians(j), _e = k / _, et = {
        distance: k,
        position: b
    }, tt, rt;
    if (s.options.shape === "circle" ? (tt = Math.min(k, _),
    rt = findCoord(s.position, tt, j)) : (rt = clamp(b, s.position, _),
    tt = distance(rt, s.position)),
    i.follow) {
        if (k > _) {
            let at = b.x - rt.x
              , st = b.y - rt.y;
            s.position.x += at,
            s.position.y += st,
            s.el.style.top = s.position.y - (e.box.top + c.y) + "px",
            s.el.style.left = s.position.x - (e.box.left + c.x) + "px",
            k = distance(b, s.position)
        }
    } else
        b = rt,
        k = tt;
    var it = b.x - s.position.x
      , nt = b.y - s.position.y;
    s.frontPosition = {
        x: it,
        y: nt
    },
    i.dataOnly || applyPosition(s.ui.front, s.frontPosition);
    var ot = {
        identifier: s.identifier,
        position: b,
        force: _e,
        pressure: a.force || a.pressure || a.webkitForce || 0,
        distance: k,
        angle: {
            radian: $,
            degree: j
        },
        vector: {
            x: it / _,
            y: -nt / _
        },
        raw: et,
        instance: s,
        lockX: i.lockX,
        lockY: i.lockY
    };
    ot = s.computeDirection(ot),
    ot.angle = {
        radian: radians(180 - j),
        degree: 180 - j
    },
    s.trigger("move", ot),
    e.trigger("move " + s.id + ":move", ot)
}
;
Collection.prototype.processOnEnd = function(a) {
    var e = this
      , i = e.options
      , o = e.manager.getIdentifier(a)
      , s = e.nipples.get(o)
      , c = e.manager.removeIdentifier(s.identifier);
    !s || (i.dataOnly || s.hide(function() {
        i.mode === "dynamic" && (s.trigger("removed", s),
        e.trigger("removed " + s.id + ":removed", s),
        e.manager.trigger("removed " + s.id + ":removed", s),
        s.destroy())
    }),
    clearInterval(e.pressureIntervals[s.identifier]),
    s.resetDirection(),
    s.trigger("end", s),
    e.trigger("end " + s.id + ":end", s),
    e.ids.indexOf(s.identifier) >= 0 && e.ids.splice(e.ids.indexOf(s.identifier), 1),
    e.actives.indexOf(s) >= 0 && e.actives.splice(e.actives.indexOf(s), 1),
    /(semi|static)/.test(i.mode) ? e.idles.push(s) : e.nipples.indexOf(s) >= 0 && e.nipples.splice(e.nipples.indexOf(s), 1),
    e.manager.unbindDocument(),
    /(semi|static)/.test(i.mode) && (e.manager.ids[c.id] = c.identifier))
}
;
Collection.prototype.onDestroyed = function(a, e) {
    var i = this;
    i.nipples.indexOf(e) >= 0 && i.nipples.splice(i.nipples.indexOf(e), 1),
    i.actives.indexOf(e) >= 0 && i.actives.splice(i.actives.indexOf(e), 1),
    i.idles.indexOf(e) >= 0 && i.idles.splice(i.idles.indexOf(e), 1),
    i.ids.indexOf(e.identifier) >= 0 && i.ids.splice(i.ids.indexOf(e.identifier), 1),
    i.manager.removeIdentifier(e.identifier),
    i.manager.unbindDocument()
}
;
Collection.prototype.destroy = function() {
    var a = this;
    a.unbindEvt(a.options.zone, "start"),
    a.nipples.forEach(function(i) {
        i.destroy()
    });
    for (var e in a.pressureIntervals)
        a.pressureIntervals.hasOwnProperty(e) && clearInterval(a.pressureIntervals[e]);
    a.trigger("destroyed", a.nipples),
    a.manager.unbindDocument(),
    a.off()
}
;
function Manager(a) {
    var e = this;
    e.ids = {},
    e.index = 0,
    e.collections = [],
    e.scroll = getScroll(),
    e.config(a),
    e.prepareCollections();
    var i = function() {
        var s;
        e.collections.forEach(function(c) {
            c.forEach(function(d) {
                s = d.el.getBoundingClientRect(),
                d.position = {
                    x: e.scroll.x + s.left,
                    y: e.scroll.y + s.top
                }
            })
        })
    };
    bindEvt(window, "resize", function() {
        throttle(i)
    });
    var o = function() {
        e.scroll = getScroll()
    };
    return bindEvt(window, "scroll", function() {
        throttle(o)
    }),
    e.collections
}
Manager.prototype = new Super;
Manager.constructor = Manager;
Manager.prototype.prepareCollections = function() {
    var a = this;
    a.collections.create = a.create.bind(a),
    a.collections.on = a.on.bind(a),
    a.collections.off = a.off.bind(a),
    a.collections.destroy = a.destroy.bind(a),
    a.collections.get = function(e) {
        var i;
        return a.collections.every(function(o) {
            return i = o.get(e),
            !i
        }),
        i
    }
}
;
Manager.prototype.create = function(a) {
    return this.createCollection(a)
}
;
Manager.prototype.createCollection = function(a) {
    var e = this
      , i = new Collection(e,a);
    return e.bindCollection(i),
    e.collections.push(i),
    i
}
;
Manager.prototype.bindCollection = function(a) {
    var e = this, i, o = function(s, c) {
        i = s.type + " " + c.id + ":" + s.type,
        e.trigger(i, c)
    };
    a.on("destroyed", e.onDestroyed.bind(e)),
    a.on("shown hidden rested dir plain", o),
    a.on("dir:up dir:right dir:down dir:left", o),
    a.on("plain:up plain:right plain:down plain:left", o)
}
;
Manager.prototype.bindDocument = function() {
    var a = this;
    a.binded || (a.bindEvt(document, "move").bindEvt(document, "end"),
    a.binded = !0)
}
;
Manager.prototype.unbindDocument = function(a) {
    var e = this;
    (!Object.keys(e.ids).length || a === !0) && (e.unbindEvt(document, "move").unbindEvt(document, "end"),
    e.binded = !1)
}
;
Manager.prototype.getIdentifier = function(a) {
    var e;
    return a ? (e = a.identifier === void 0 ? a.pointerId : a.identifier,
    e === void 0 && (e = this.latest || 0)) : e = this.index,
    this.ids[e] === void 0 && (this.ids[e] = this.index,
    this.index += 1),
    this.latest = e,
    this.ids[e]
}
;
Manager.prototype.removeIdentifier = function(a) {
    var e = {};
    for (var i in this.ids)
        if (this.ids[i] === a) {
            e.id = i,
            e.identifier = this.ids[i],
            delete this.ids[i];
            break
        }
    return e
}
;
Manager.prototype.onmove = function(a) {
    var e = this;
    return e.onAny("move", a),
    !1
}
;
Manager.prototype.onend = function(a) {
    var e = this;
    return e.onAny("end", a),
    !1
}
;
Manager.prototype.oncancel = function(a) {
    var e = this;
    return e.onAny("end", a),
    !1
}
;
Manager.prototype.onAny = function(a, e) {
    var i = this, o, s = "processOn" + a.charAt(0).toUpperCase() + a.slice(1);
    e = prepareEvent(e);
    var c = function(_, b, k) {
        k.ids.indexOf(b) >= 0 && (k[s](_),
        _._found_ = !0)
    }
      , d = function(_) {
        o = i.getIdentifier(_),
        map(i.collections, c.bind(null, _, o)),
        _._found_ || i.removeIdentifier(o)
    };
    return map(e, d),
    !1
}
;
Manager.prototype.destroy = function() {
    var a = this;
    a.unbindDocument(!0),
    a.ids = {},
    a.index = 0,
    a.collections.forEach(function(e) {
        e.destroy()
    }),
    a.off()
}
;
Manager.prototype.onDestroyed = function(a, e) {
    var i = this;
    if (i.collections.indexOf(e) < 0)
        return !1;
    i.collections.splice(i.collections.indexOf(e), 1)
}
;
const factory = new Manager;
var nipplejs = {
    create: function(a) {
        return factory.create(a)
    },
    factory
};
class JoyStick {
    constructor(e) {
        Tt(this, "_zone");
        Tt(this, "_joystick", null);
        Tt(this, "_room");
        this._room = e
    }
    get zone() {
        return this._zone
    }
    init(e) {
        var _e, et;
        this.destroy();
        const i = {
            position: "absolute",
            width: "200px",
            height: "200px",
            left: "0px",
            bottom: "0px",
            zIndex: "999",
            userSelect: "none",
            webkitUserSelect: "none"
        }
          , {interval: o=33, triggerDistance: s=25, size: c=110, zoneClassName: d="xverse-joystick-zone"} = e || {};
        typeof ((_e = e == null ? void 0 : e.style) == null ? void 0 : _e.left) == "number" && (e.style.left = e.style.left + "px"),
        typeof ((et = e == null ? void 0 : e.style) == null ? void 0 : et.bottom) == "number" && (e.style.bottom = e.style.bottom + "px");
        const _ = Object.assign(i, e == null ? void 0 : e.style)
          , b = (tt,rt)=>{
            this._room.actionsHandler.joystick({
                degree: Math.floor(tt),
                level: Math.floor(rt / 5)
            })
        }
          , k = this._zone = document.createElement("div");
        document.body.appendChild(k),
        k.className = d,
        Object.keys(_).forEach(tt=>{
            const rt = _[tt];
            rt !== void 0 && (k.style[tt] = rt)
        }
        ),
        this._joystick = nipplejs.create({
            zone: k,
            mode: "static",
            position: {
                left: "50%",
                top: "50%"
            },
            color: "white",
            restOpacity: .3,
            size: c
        }),
        this.customizeStyle();
        let j, $;
        return this._joystick.on("move", (tt,rt)=>{
            j = rt
        }
        ),
        this._joystick.on("start", ()=>{
            $ = window.setInterval(()=>{
                j && j.distance > s && b && b(j.angle.degree, j.distance)
            }
            , o)
        }
        ),
        this._joystick.on("end", ()=>{
            $ && window.clearInterval($),
            $ = void 0
        }
        ),
        this._joystick
    }
    destroy() {
        if (!!this._joystick) {
            this._joystick.destroy();
            try {
                this._zone && document.body.removeChild(this._zone)
            } catch {}
        }
    }
    customizeStyle() {
        var c, d;
        const e = this._zone;
        if (!e)
            return;
        const i = e.querySelector(".front")
          , o = e.querySelector(".back")
          , s = 30;
        i.style.width = s + "px",
        i.style.height = s + "px",
        i.style.marginLeft = s / -2 + "px",
        i.style.marginTop = s / -2 + "px",
        o.style.boxSizing = "border-box",
        o.style.backgroundColor = "black",
        o.style.backgroundClip = "padding-box",
        o.style.border = "2px solid white",
        (c = this._joystick) == null || c.on("start", ()=>{
            o.style.border = "2px solid #FFEA95",
            o.style.boxShadow = "inset 0px 0px 8px rgba(255, 255, 255, 0.25)",
            i.style.opacity = "1"
        }
        ),
        (d = this._joystick) == null || d.on("end", ()=>{
            o.style.border = "2px solid white",
            o.style.boxShadow = "none"
        }
        )
    }
    show() {
        if (!this._joystick || !this._zone)
            throw new Error("joystick is not created");
        this._zone.style.display = "block"
    }
    hide() {
        this._zone && (this._zone.style.display = "none")
    }
}
var app = "";
function toast(a, e) {
    const {onClick: i, duration: o} = e || {};
    return window.Toastify({
        text: a,
        duration: o || 3e3,
        position: "center",
        onClick: function() {
            i && i()
        }
    }).showToast()
}
class XverseRoom extends XverseRoom$1 {
    constructor() {
        super(...arguments);
        Tt(this, "joyStick", new JoyStick(this))
    }
    afterJoinRoomHook() {
        this.joyStick.init({
            style: {
                width: "150px",
                height: "150px"
            }
        })
    }
}
class Xverse extends Xverse$1 {
    async joinRoom(e) {
        const i = e.pathName || "thirdwalk"
          , o = e.rotationRenderType || RenderType.RotationVideo
          , s = e.person || Person.Third
          , c = new XverseRoom(Zt($t({}, e), {
            appId: e.appId || this.appId,
            releaseId: e.releaseId || this.releaseId,
            pageSession: this.pageSession,
            isAllSync: !0,
            rotationRenderType: o,
            syncByEvent: !0,
            pathName: i,
            person: s,
            role: e.role || "audience"
        }));
        return c.initRoom().then(()=>c)
    }
}
var loadingImage = "./assets/loading.f375926b.png"
  , jsxRuntime = {
    exports: {}
}
  , reactJsxRuntime_production_min = {};
/** @license React v17.0.2
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var f = react.exports
  , g = 60103;
reactJsxRuntime_production_min.Fragment = 60107;
if (typeof Symbol == "function" && Symbol.for) {
    var h = Symbol.for;
    g = h("react.element"),
    reactJsxRuntime_production_min.Fragment = h("react.fragment")
}
var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner
  , n = Object.prototype.hasOwnProperty
  , p = {
    key: !0,
    ref: !0,
    __self: !0,
    __source: !0
};
function q(a, e, i) {
    var o, s = {}, c = null, d = null;
    i !== void 0 && (c = "" + i),
    e.key !== void 0 && (c = "" + e.key),
    e.ref !== void 0 && (d = e.ref);
    for (o in e)
        n.call(e, o) && !p.hasOwnProperty(o) && (s[o] = e[o]);
    if (a && a.defaultProps)
        for (o in e = a.defaultProps,
        e)
            s[o] === void 0 && (s[o] = e[o]);
    return {
        $$typeof: g,
        type: a,
        key: c,
        ref: d,
        props: s,
        _owner: m.current
    }
}
reactJsxRuntime_production_min.jsx = q;
reactJsxRuntime_production_min.jsxs = q;
jsxRuntime.exports = reactJsxRuntime_production_min;
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
  , scale = Number(urlParam.get("scale") || 1)
  , isDebug = !!urlParam.get("debug");
appId || alert("AppId \u4E0D\u80FD\u4E3A\u7A7A");
const xverse = new Xverse({
    env: "DEV",
    appId,
    releaseId
});
let room;
function App() {
    const [a,e] = react.exports.useState(!0)
      , [i,o] = react.exports.useState(!0)
      , [s,c] = react.exports.useState("high")
      , [d,_] = react.exports.useState("");
    react.exports.useEffect(()=>{
        b()
    }
    , []);
    const b = async()=>{
        var ft;
        const _e = document.querySelector("#canvas")
          , et = urlParam.get("roomId") || "e629ef3e-022d-4e64-8654-703bb96410eb"
          , tt = urlParam.get("userId") || Math.random().toString(16).slice(2)
          , rt = urlParam.get("avatarId") || void 0
          , it = urlParam.get("appId") || void 0
          , nt = urlParam.get("skinId") || void 0
          , ot = urlParam.get("pathName") || void 0
          , at = urlParam.get("objectFit") || void 0
          , st = {
            width: parseInt(urlParam.get("width") || "1920"),
            height: parseInt(urlParam.get("height") || "1080")
        }
          , ut = urlParam.get("ws") ? decodeURIComponent(urlParam.get("ws")) : "wss://uat-eks.xverse.cn/ws"
          , ct = !!urlParam.get("preload")
          , lt = "full";
        if (Logger.setLevel(isDebug ? LoggerLevels.Debug : LoggerLevels.Warn),
        ct)
            try {
                await ((ft = xverse.preload) == null ? void 0 : ft.start(lt, (ht,pt)=>{
                    const dt = `(${ht}/${pt})`;
                    _(dt)
                }
                ))
            } catch (ht) {
                if (console.error(ht),
                ht.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: _e,
                skinId: nt,
                avatarId: rt,
                roomId: et,
                userId: tt,
                wsServerUrl: ut,
                appId: it,
                token: " ",
                nickname: tt,
                firends: ["user1"],
                viewMode: "full",
                resolution: st,
                pathName: ot,
                objectFit: at,
                hasAvatar: !0,
                syncToOthers: !0,
                avatarScale: scale
            }),
            k(),
            j(),
            window.room = room,
            e(!1)
        } catch (ht) {
            console.error(ht),
            alert(ht);
            return
        }
    }
      , k = ()=>{
        room.on("_coreClick", ({point: _e})=>{
            room._userAvatar.moveTo({
                point: _e
            })
        }
        )
    }
      , j = ()=>{
        room.on("repeatLogin", function() {
            toast("\u8BE5\u7528\u6237\u5DF2\u7ECF\u5728\u5176\u4ED6\u5730\u70B9\u767B\u5F55", {
                duration: 1e4
            })
        }),
        room.on("reconnecting", function({count: _e}) {
            toast(`\u5C1D\u8BD5\u7B2C${_e}\u6B21\u91CD\u8FDE`)
        }),
        room.on("reconnected", function() {
            toast("\u91CD\u8FDE\u6210\u529F")
        }),
        room.on("disconnected", function() {
            const _e = toast("\u8FDE\u63A5\u5931\u8D25\uFF0C\u624B\u52A8\u70B9\u51FB\u91CD\u8BD5", {
                duration: 1e5,
                onClick() {
                    _e.hideToast(),
                    room.reconnect()
                }
            })
        })
    }
    ;
    return jsxs("div", {
        className: "App",
        children: [jsx("canvas", {
            id: "canvas",
            className: "stream unselect"
        }), !a && isDebug && (()=>jsxs("div", {
            className: "debug_control_btns",
            children: [jsx("button", {
                onClick: ()=>{
                    var at, st;
                    (at = room.stats) != null && at.isShow ? room.stats.hide() : (st = room.stats) == null || st.show()
                }
                ,
                children: "Toggle Stats"
            }), jsx("button", {
                onClick: ()=>{
                    room.debug.toggleSceneshading(),
                    o(room.debug.isSceneShading)
                }
                ,
                children: i ? "\u53D6\u6D88\u4F4E\u6A21\u7740\u8272" : "\u4F4E\u6A21\u7740\u8272"
            }), jsxs("button", {
                onClick: ()=>{
                    let at = "average";
                    s === "high" ? at = "average" : s === "average" ? at = "low" : s === "low" ? at = "high" : at = "average",
                    c(at),
                    room.setPictureQualityLevel(at)
                }
                ,
                children: ["\u753B\u8D28\uFF1A", s === "high" ? "\u9AD8" : s === "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"
            }), jsx("input", {
                onBlur: at=>{
                    at.preventDefault();
                    const st = at.target.value
                      , ut = Number(st);
                    if (ut > 0) {
                        urlParam.set("scale", String(ut));
                        const ct = urlParam.toString();
                        location.href = location.origin + location.pathname + "?" + ct
                    }
                }
                ,
                placeholder: "\u81EA\u5B9A\u4E49Avatar\u7F29\u653E",
                defaultValue: scale || ""
            })]
        }))(), a && jsxs("div", {
            className: "loading",
            id: "loading",
            children: [jsx("img", {
                src: loadingImage,
                alt: ""
            }), jsxs("div", {
                children: ["\u5373\u5C06\u8FDB\u5165\u573A\u666F ", d]
            })]
        })]
    })
}
ReactDOM.render(jsx(React.StrictMode, {
    children: jsx(App, {})
}), document.getElementById("root"));
